問題描述
我知道很多人偶爾會遇到同樣的錯誤,但是我已經查看了所有以前的答案和我的代碼,并且我嘗試了帶有和不帶有反引號的 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"表示字符串,實際上您可以將它用于任何類型)而不是實際變量.
- 并執行()
通過這種方式,您可以始終確保添加到查詢中的數據不會導致任何 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 插入錯誤不正確的語法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!