0

Forgive me if this already exists, but I didn't see anything close enough to my issue to offer any kind of solution or path toward solving.

My Query: $sql = "UPDATE users SET FirstName=$fname WHERE id=$id";

$fname does equal Jason. But it should be changing the sql field FirstName to "Jason". Instead, it is trying to find a field named Jason. I have tried hardcoding in "Jason", but then it says that there is an unexpected string. Hardcoding it in would actually cause issues as the data needs to be a variable so the user can change to their First Name to whatever they want. I have echo'd $id and that value is coming across correctly. My code is in php.

Long time reader of stackoverflow.com, first time poster. If there is any additional code or info that might be helpful, please let me know.

EDIT: I had not realized that variables also need to be within quotes. I assumed the quotes were specifically for hardcoded strings. Placing $fname within single quotes as '$fname' solved it. Thank you, everyone!!!

1 Answers1

0

Use single quotations:

$sql = "UPDATE users SET FirstName='$fname' WHERE id=$id";

Be sure about securing your SQL query; if the $fname's value is dynamic, then you must escape special characters using mysqli_real_escape_string to avoid a very dangerous vulnerability SQL Injection.

  • Thank you SOOO much! I can't believe it was so simple! All the tutorials I could find online showed the data hardcoded instead of as variables and I just assumed the single quotes were because the hardcoded values were strings instead of variables. I GREATLY appreciate it! =) – Jason Singell Aug 17 '21 at 20:25
  • 2
    Don't rely on the `*_real_escape_string()` functions to prevent SQL injection, [they alone are not sufficient](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string). Instead, always use [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) with [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). See [**this page**](https://phptherightway.com/#databases) and [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for some good examples. – Alex Howansky Aug 17 '21 at 20:26
  • @AlexHowansky Thank you for the information! I have seen an example of bound parameters but it was little outside my grasp. So, I felt that first getting a simple version to work and then polishing it up to work as bound parameters and prepared statements might help me to understand it better. My school had taught us javascript and python, but no php. So, php is a language I am taking on myself to learn. I look forward to reading the resources you have provided for me!!! – Jason Singell Aug 17 '21 at 20:31
  • @AlexHowansky, I agree, using prepared statements is the best and easiest way to prevent SQL injections. – Mohammad ALTAWEEL Aug 17 '21 at 20:39