简体   繁体   中英

store result of query and use in another query

I am trying to store the result of one query $sql and use this result in the second query $sql1.

$sql selects the value in the column clear and should store this in $result.

$sql1 should update the column that is found from $sql and switch the value of that column to NOT $result, boolean column.

The reason I need this is because the column I am updating depends on the value of column clear, which contains the names of various columns. These columns are also all in the same table.

<?php

$userIdentity = $_SESSION['userIdentity'];

$sql = "SELECT clear FROM UserInfo WHERE userIdentity = '$userIdentity'";

$result = $dbc->query($sql); 

$sql1 ="UPDATE UserInfo SET $result = NOT $result WHERE userIdentity = '$userIdentity'";

$result1 = $dbc->query($sql1); 

?>

Since $dbc is a mysqli object, mysqli::query() returns a mysqli_result object on a successful query. This means that $result is not going to be the single value you expect it to be; instead, it's going to be an object that represents the entire response to the query.

You will want to do something like this to actually get the value of your clear column:

$result = $dbc->query($sql);
$row = $result->fetch_object(); //get the first row from the result
$clear = $row->clear;

You can then use $clear to update your database in the second query. (You can't easily do this in one query because the column you are modifying depends on the value of a row in the database. Doing this in entirely in one query may be possible, but is probably also more trouble than it's worth.)

Caveats:

  • If the query returns no rows, $row will be null. So you will need to check for this.
  • Note that you do have a potential SQL injection vulnerability by passing $clear and $userIdentity directly into the sql query. For $userIdentity , you should use parameterized queries (which means you can't use mysqli::query() ; see mysqli::prepare for an example of how to do this). Since $clear is used as a column name, and you can't parameterize column names, you will need to take extra care to ensure that it is valid.

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