【发布时间】:2017-04-10 19:59:38
【问题描述】:
我正在尝试使用 php 将数据插入 mysql 数据库。看起来很简单。
在使用虚拟数据(只是文本字符串)时,它工作得非常好。当我用实际变量替换虚拟数据时,我得到了这个错误:
ERROR: Could not able to execute INSERT INTO tbl_users (id, timestamp, testid, email, wants_newsletter, ip, country) VALUES (NULL, CURRENT_TIMESTAMP, , , , , ). You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , , )' at line 1
下面是我正在使用的脚本。我 100% 确定所有变量都有效。我目前也让他们吐出虚拟数据。
$testid = 1;
$email = 'test@yahoo.com'
$wants_newsletter = true;
//get $ip
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$country = 'US';
$user_id = 100;
$question = 14
$answer = 14
function saveToDB() {
/* Attempt MySQL server connection. */
$link = mysqli_connect("localhost", "$user", "$pass", "$db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO tbl_users (id, timestamp, testid, email, wants_newsletter, ip, country) VALUES (NULL, CURRENT_TIMESTAMP, $testid, $useremail, $newsletter, $ip, $country)";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
$user_id = $link->insert_id;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Attempt insert query execution
$sql = "INSERT INTO tbl_answers (id, user_id, question_id, answer) VALUES (NULL, $user_id, $question, $answer)";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
}//end saveToDB
saveToDB(); //Call saveToDB()
为了找出这个错误,我已经绞尽脑汁好几个小时了。它可能是我忽略的小东西,也许我需要一双新的眼睛。
任何帮助将不胜感激。
【问题讨论】:
-
您应该使用准备好的语句。就目前而言,您有
string类型变量,并且值周围没有引号。 -
您需要在字符串周围加上单引号。 '$useremail'
-
我尝试在字符串周围使用单引号,但我得到一个空(或 0)值
-
@AbraCadaver 这不是重复的帖子。
-
您从哪里获得变量的值?我没有看到它们被设置。函数内部。
标签: php mysql insert syntax-error