简体   繁体   中英

Use PHP UPDATE with SET as a variable set to another variable?

Im wondering if something like this is possible?

$joinguild = "UPDATE guild SET '.$rank.'='.$receiver.' WHERE name ='"$dupecheckinfo["guild"]"'";

Im trying to SET '.$rank.'='.$receiver.', but I dont know if I can use a variable where $rank is. Is there a proper way to write this. Is it even possible? If not how would you approach it? Thanks!

Here is my SQL table im working with

Edit: See how my table has Rank1 Rank2 Rank3 etc. Well I am passing the rank value that I want to set so for example

$rank = $_POST["rank"];

$joinguild = "UPDATE guild SET '.$rank.'='.$username.' WHERE name ='"$dupecheckinfo["guild"]"'";

Your question in not clear but you have some problems in your PHP statement. I think you are trying to create your SQL UPDATE query using PHP variables.

Try this:

$joinguild = "UPDATE guild SET $rank='$receiver' WHERE name='" . $dupecheckinfo["guild"] . "'";

Here $rank should have valid column name in your table. Also read about SQL injection.

Your question is quite unclear but to update records from a table you can use this line of code:

  $sql=mysqli_query($conn, "UPDATE `table` SET option1='$op1', option2='$op2', option3='$op3', option4='$op4' where id='$id'");      

If this is unclear please let me know.

Yes, you can use variables for table and field names in your queries. However, you should avoid it whenever possible, because it generally leads to SQL injection vulnerabilities. Instead of building queries with string concatenation, use prepared statements with bound parameters . See this page and this post for some good examples.

Unfortunately, the bind mechanism works only for values and not for table names or field names, so it's best to try avoiding variable table/field names. If you find that you absolutely must, the best approach would be to ensure that the contents of the variable matches with a pre-set whitelist of allowed table/field names.

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