简体   繁体   中英

How to construct an SQL query correctly in a PHP script?

I am trying to create an SQL query to insert user info into a database. The $fname and $lname variables contain correct values ("John" and "Doe") but the query fails. Here is my code:

$fname = $_POST['first_name'];
$lname = $_POST['last_name'];  
$sql = "INSERT INTO users (fname, lname) VALUES ($fname, $lname)";
mysqli_query($conn, $sql);

after checking the error message I've found that this query fails with error saying

Unknown column 'John' in 'field list'

How can I properly include variables into SQL query to make it run without an error?

  • This question is not about SQL syntax which I am quite familiar with, but about the rules of creating a query dynamically using variables in a PHP script.
  • I don't want a quick patch that only eliminates the immediate error, but a state-of-art solution which is error free and secure as well.

The most mistake-proof way to add a variable into an SQL query is to add it through a prepared statement .

It is very important to understand that simply adding quotes around a variable is not enough and will eventually lead to innumerable problems, from syntax errors to SQL injections. On the other hand, due to the very nature of prepared statements, it's a bullet-proof solution that makes it impossible to introduce any problem through a data variable.

So, for every query you run, if at least one variable is going to be used, you have to substitute it with a placeholder, then prepare your query, and then execute it, passing variables separately.

First of all, you have to alter your query, adding placeholders in place of variables. Your query will become:

$sql = "INSERT INTO users (fname, lname) VALUES (?, ?)";

Then, you will have to prepare it, bind variables, and execute:

$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $fname, $lname);
mysqli_stmt_execute($stmt);

As you can see, it's just three simple commands:

  • prepare() where you send a query with placeholders
  • bind_param where you send a string with types ("s" is for string and you can use it for any type actually) and than actual variables.
  • and execute()

This way, you can always be sure that not a single SQL syntax error can be caused by the data you added to the query! As a bonus, this code is bullet-proof against SQL injection too!

There is a pinch of salt though, as running a SELECT query with mysqli prepared statements could be more complicated. So I would strongly suggest to choose PDO as your database driver for many reasons .

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