-1

I'm using PDO in PHP to connect to MySQL. My project is a chat app

Everytime someone sends a new message, I insert the message into table chat_messages, and I update a timestamp in table chat_users to indicate that that was the last time the user was active.

$sql = "INSERT INTO chat_messages
                (email_sender, message, sent) 
        VALUES  ('" . $email . "', '" . $message . "', '" . time() . "')";
$query = $pdo->prepare($sql);
if ($query->execute()) {
    $sql2 = "UPDATE chat_users SET last_active = UNIX_TIMESTAMP() 
                WHERE email = '$email'";
    $pdo->prepare($sql2)->execute();
    // to test my query syntax is correct:
    echo $sql2;
}

The timestamp is not being updated in the database. When i copy paste the output of echo $sql2 into phpMyAdmin, the query works.

What am i doing wrong?

Thank you

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89

1 Answers1

4

You're really missing out on a lot of the benefit of using prepared statements if you concat variables into the SQL like that. If you prepare with placeholders and bind your values, it will probably take care of your problems as well as being more secure against SQL injections.

$sql = "INSERT INTO chat_messages(email_sender, message, sent) VALUES (?, ?, ?)";
$query = $pdo->prepare($sql);
if ($query->execute([$email, $message, $time])) {
    $sql2 = "UPDATE chat_users SET last_active = UNIX_TIMESTAMP() WHERE email = ?";
    $pdo->prepare($sql2)->execute([$email]);
    // to test my query syntax is correct:
    echo $sql2;
}

If your query is failing (and even if it isn't) you should set PDO to throw exceptions when queries fail, so you'll get a descriptive error message as to what went wrong.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80