简体   繁体   中英

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);

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.

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);

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);

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);

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 +"

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

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