mysqli插入错误语法不正确 [英] mysqli insert error incorrect syntax
问题描述
我知道很多人偶尔也会遇到相同的错误,但是我查看了以前的所有答案和我的代码,并且尝试了带反斜线和不带反斜线的col
这是我当前的代码
我也尝试过使用$var
以及$var
但相同的
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
推荐答案
向SQL查询中添加变量的最防错的方法是通过准备好的语句将其添加.
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(),使用占位符发送查询
- bind_param,您在其中发送带有类型的字符串("s"用于字符串,并且可以将其实际用于任何类型),而不是实际变量.
- 和execute()
这样,您始终可以确保添加到查询中的数据不会引起单个SQL语法错误!另外,此代码也可以防止SQL注入!
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!
非常重要的一点是要理解,仅在变量周围加上引号还不够,并且最终会导致无数问题,从语法错误到SQL注入.另一方面,由于预准备语句的本质,它是一种防弹解决方案,无法通过数据变量引入任何问题.
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.
这篇关于mysqli插入错误语法不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!