mysqli insert error incorrect syntax [duplicate]

2020-01-24 01:01发布

问题:

I know a lot of people have the same error occasionally however I have looked at all previous answers and my code and i have tried col with and without backticks Here is my current code I also have tried with $var as well as just $var but same

if(!empty($_POST['email'])){
 $date = date('dmY'); #Todays Date
 $ip = str_replace('.','',$_SERVER['REMOTE_ADDR']); #Visitor IP
 $verify = md5($date.$ip); #MD5 ENCRYPT THE 2 VALUES
 $fname = $_POST['fname'];
 $lname = $_POST['lname'];  
 $email = $_POST['email'];
 $password = md5($_POST['password']);
 $link = mysqli_connect($dbh,$dbu, $dbp, $dbn);

 $query = mysqli_query($link, "INSERT INTO `users` (`email`,`fname`,`lname`,`verify`,`password`,`joined`)
VALUES($email,$fname,$lname,$verify,$password,$date)");

 if($query){ 
  echo "inserted"; 
 }
 else { 
  echo mysqli_error($link);
 }

There are other columns in the table however its only the above columns I want to add data for the rest can use default values initially

I've been looking at this code for so long now I just cant spot my problem, I know its something silly

回答1:

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

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!

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.