开发者

Delete record in MySQL with php targeting auto_incremented int?

开发者 https://www.devze.com 2022-12-22 19:29 出处:网络
Why doesnt this delete work to delete the whole r开发者_开发百科ecord: $query = \'DELETE FROM tblEvents WHERE index = $_GET[\"id\"]\';

Why doesnt this delete work to delete the whole r开发者_开发百科ecord:

$query = 'DELETE FROM tblEvents WHERE index = $_GET["id"]';
$result = mysql_query($query, $db) or die(mysql_error($db));

Where index is variable of type int, auto_incremented in MySQL?


Your question php is related, not mysql.
print $query; and see.
then refer to php strings syntax, http://php.net/types.string for the proper syntax.

Also, a variable that goes to the query, must be properly prepared, escaped, or, in case of integer value, manually cast to this type,

$id=intval($_GET["id"]);

or, to make it single line,

$query = 'DELETE FROM tblEvents WHERE `index` = '.intval($_GET["id"]);

also, index is reserved word that can cause problems too, you can escape it with backticks,

`index`

but it will be much better if you rename it to just id


You should test for delete success with a separate query

$query = 'DELETE FROM tblEvents WHERE index = $_GET["id"]';
mysql_query($query, $db);
if( mysql_affected_rows < 1 ) die();


Col. Shrapnel is right, you can't use variables directly in a string in single quotes. If you use double quotes around your query, it will work.

EDIT: As Col. Shrapnel said in his comment, in this case you'll also have to change the double quotes in the array offset to single quotes.


Hopefully you already know this, but you need to secure that $_GET['id'] so people can't do SQL Injection. Try using the following instead:

$query = sprintf('DELETE FROM tblEvents WHERE index = %d',mysql_real_escape_string($_GET['id']));

This also solves your problem of using a variable in single quotes instead of double quotes.

if you wanted you could also do:

$id = mysql_real_escape_string($_GET['id']);
$query = "DELETE FROM tblEvents WHERE index = {$id}";

This works too.

0

精彩评论

暂无评论...
验证码 换一张
取 消