user1320260
user1320260

Reputation:

Mysqli DELETE not working with variable

I'll jump straight into it. Using php I'm having a problem deleting a record from the database if i use a variable as the value. The line of code below works perfectly

mysqli_query($con,"DELETE FROM highScores WHERE Name='David'");

But the name of the user will change, therefore I need to declare it as a variable. I've tried all kinds of variations but nothing seems to work. My latest failed attempt was the code below, which is the way i declare a varible when i'm inserting.

mysqli_query($con,"DELETE FROM highScores WHERE Name='{$name}'");

Upvotes: 2

Views: 6282

Answers (4)

Cedric Ipkiss
Cedric Ipkiss

Reputation: 6347

I landed here while searching for solutions to the same problem, but just discovered my database user didn't have delete privileges. I had earlier removed this privilege for security reasons.

Upvotes: 0

MrVimes
MrVimes

Reputation: 3312

In situations like this it is good to check that variables actually contain something you expect it to. And I find also that echoing entire query strings is a good way to find out why a query isn''t working.

$sqlquery = "DELETE FROM highScores WHERE Name='{$name}'";

// have a look at the query...

echo "<pre>$sqlquery</pre>";

// use it...

mysqli_query($conn,$sqlquery);

I should warn you that if $name comes from somewhere untrusted, such as a publicly viewable html form, then it needs to be made 'safe' before using it in a query. Look into 'prepared statements'. Once you know your code is correctly populating your variable, make sure it is made safe before putting it in your query.

Upvotes: 3

Bjoern
Bjoern

Reputation: 16304

Try this to get it running:

mysqli_query($con,"DELETE FROM highScores WHERE Name='".$name."'");

Make sure $name is a proper formed string like string(5) David, otherwise it might not lead to the desired results or may even break your query completely. You can make sure of this if you put a mysqli_real_escape_string like this

$name = mysqli_real_escape_string($con,$name);

before you execute the query

Upvotes: 0

Kayla
Kayla

Reputation: 475

I'm not sure if.. {$variable} is valid in a query.

The way I insert a variable into a query, is called concentration.

mysqli_query($con,"DELETE FROM highScores WHERE Name='" . $name . "'");

The period adds 2 strings together.

However, what you're trying to do is vulnerable to SQL injection. If I were you, I'd be careful on what could be inside $name.

EDIT: My mistake, I'm used to a class that inserts the quotes for me.

Upvotes: 0

Related Questions