tags:

views:

60

answers:

3

Hello,

I have a MySQL table called "privatemessage" with a primary key field called "messageid."

I would like to have a PHP query that deletes any row from "privatemessage" where "messageid = $messageid."

What sort of query does this?

Thanks in advance,

John

+4  A: 
DELETE FROM `privatemessage` WHERE `messageid` = $messageid

That's just the raw SQL query. Things like validating and escaping user input should certainly be considered.

For example, given messageid as an AUTO_INCREMENT integer primary key I'd simply run this in PHP (converting $messageid to an int using intval()):

mysql_query('DELETE FROM `privatemessage` WHERE `messageid` = ' . intval($messageid));
BoltClock
To expand slightly, [this](http://www.w3schools.com/php/php_mysql_delete.asp) webpage has a small but useful example.
Stephen
And you should use parameters, so that messageid of "1 or 1 == 1" will not delete all of your private messages (sql injection)
Vitaly Polonetsky
Indeed, if you are accepting input from the user for $messageid, be careful to avoid SQL injection. For example, the user might enter `5 OR 1==1` as their input. This then forms the query: `DELETE FROM 'privatemessage' WHERE 'messageid' = '5' OR 1 == 1`. Since 1==1 is always true, this would delete every row.
Stephen
Obligatory edit to account for security implications.
BoltClock
A: 

$query = "DELETE FROM privatemessage WHERE messageid = '$messageid'"; mysql_query($query);

But first of all, check that $messageid is a number (http://en.wikipedia.org/wiki/SQL_injection)

Read more: about MySQL delete

Slava
Who downvoted this? And why?
EFraim
+1  A: 

You might want to use a preprared statement, so you're on the safe side regarding SQL-injection...

$conn = new mysqli($host, $user, $password, $database);
if ($conn->connect_error) {
    die('could not connet to database.');
}
$statement = $conn->prepare("DELETE FROM privatemessage WHERE messageid = ?");
$statement->bind_param("messageid", $messageid);
$statement->execute();
Martin