ntzm
ntzm

Reputation: 4821

How do I update a certain column when a value from the same row equals a variable?

I have been trying to do this for hours now, and I can't quite get my head round it. I have a table called "requests" that has the columns "deletekey" and "deleted". "deletekey" is a random unique number (data-type text), and "deleted" is by default set to 0 (data-type boolean), and when the user inputs the deletekey, it changes "deleted" to 1. But I can't get it to work. Here is the code I have, and I have no idea what I'm doing wrong:

$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = True WHERE deletekey = "$key"';
$result = $link->query($query);

Upvotes: 0

Views: 46

Answers (6)

Robin Andersson
Robin Andersson

Reputation: 87

the query is a string. And to add a variable to a string you need to type

$query = 'UPDATE requests SET deleted = True WHERE deleted = '".$key."';

the difference is how to make a variable put into the string. You have to do like this in php. $query = "randomtext ". $randomvar ." "; where the important point is to ". $var ." inside the string. This i similar to javas "+ var +"

Upvotes: 0

Mihai
Mihai

Reputation: 26804

$query = 'UPDATE requests SET deleted = 1 WHERE deletekey = "$key"';

Upvotes: 0

Sajuna Fernando
Sajuna Fernando

Reputation: 1384

Try this?

 $link = mysqli_connect("localhost","username","password","dbname");
 $key = $link->real_escape_string($_GET["delkey"]);
 $query = "UPDATE `requests` SET `deleted` = true WHERE `deletedkey` = $key";
 $result = $link->query($query);

Upvotes: 0

Phil LaNasa
Phil LaNasa

Reputation: 3035

This should help, and will also provide protection against SQL injection:

$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = sprintf("UPDATE requests SET deleted = 1 WHERE deletekey = '%s'", $key);
$result = $link->query($query);

Upvotes: 1

Marc B
Marc B

Reputation: 360792

Shouldn't it be WHERE deletekey = '$key', then? The deleted field could NEVER equal whatever's in $key, since deleted is a simple boolean, and $key is probably an int/char/varchar-type thing.

Note that you are vulnerable to SQL injection attacks. Stop working on this sort of code until you've learned about the problem and how to avoid it.

Upvotes: 1

Jonysuise
Jonysuise

Reputation: 1840

Its deletedkey = "$key" right ? and not deleted = "$key" :

$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = true WHERE deletedkey = "$key"';
$result = $link->query($query);

Upvotes: 0

Related Questions