What are some best practices for storing chat history in a database using PHP?

Storing chat history in a database using PHP requires creating a database table to store messages with columns for message content, sender, receiver, timestamp, etc. It's important to sanitize input to prevent SQL injection attacks and use prepared statements for database queries to prevent SQL injection and improve performance.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "chat_app";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize input
$message = mysqli_real_escape_string($conn, $_POST['message']);
$sender = mysqli_real_escape_string($conn, $_POST['sender']);
$receiver = mysqli_real_escape_string($conn, $_POST['receiver']);
$timestamp = date('Y-m-d H:i:s');

// Insert message into database
$sql = "INSERT INTO chat_history (message, sender, receiver, timestamp) VALUES ('$message', '$sender', '$receiver', '$timestamp')";

if ($conn->query($sql) === TRUE) {
    echo "Message stored successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close database connection
$conn->close();