简体   繁体   中英

PHP MYSQL Delete Syntax Error

I have looked into my query statement. When I run "DELETE FROM users WHERE id = (Some Int)" in MYSQL it sucessfully executes and everything appears to be fine. However I get a syntax error in MYSQL near " when I try to execute this same command.

include 'db_connect.php'; // connects to db

 $action = isset($_GET['action']) ? $_GET['action'] : "";

 if($action=='delete'){ //if the user clicked ok, run our delete query

 $query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id'])."";

//execute query

if( $mysqli->query($query) ){

//if successful deletion

echo "User was deleted.";

}else{

//if there's a database problem

echo "Database Error: Unable to delete record.";
$disp = mysqli_error($mysqli);
print($disp);
}

Edit 1: When I print out $query, I get: "DELETE FROM users WHERE id =". id is blank.

I've Tried Changing $query to the following:

 $query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id']);// prints nothing
 $query = "DELETE FROM users WHERE id = ".$mysqli->$_GET['id'];// prints nothing
 $query = "DELETE FROM users WHERE id = ".$mysqli->$id;// prints nothing

I still do not understand why I cannot use $id here. I call a javascript function that uses id and it works fine... I get a popup window with the correct id printed in it.

echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
function delete_user( id ){
var answer = confirm('Are you sure?'+id);
if ( answer ){ //if user clicked ok
    window.location = 'delete.php?action=delete&amp;id=' + id;
    }
}

try $_GET['amp;id'] or $_REQUEST['amp;id'];

When output the var_dump

var_dump($_REQUEST);

it returns the output like:

array(2) { ["action"]=> string(6) "delete" ["amp;id"]=> string(2) "39" }

See the form field name is not id it is amp;id . So check the form field name once.

Note:

$_REQUEST An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE

Then query become

$query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_REQUEST['amp;id']);

Better way is to get the id and place in a var to check if its null. example $id = ($_get['id']);

then you use $id in sql query WHERE id = '$id'

some time query don't allow you to put in the whole system codes. do the long way make sure your 1st step is working and get the data you want before u query it in mysql

Did you receive correct value of ID and datatype from $mysqli->real_escape_string($_GET['id']) ?

Check data type in your database. That may also be datatype error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM