检查与您的MySQL服务器版本相对应的手册,以在'?,?,?,?

时间:2018-09-12 00:03:26

标签: php sql mysqli

我正在尝试创建表单并将提交的数据导入数据库,

<?php
// db has to be manually created first
$host = "localhost";
$userName = "user";
$password = "";
$dbName = "test";

// Create database connection
$conn = new mysqli($host, $userName, $password, $dbName);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


if((isset($_POST['your_name'])&& $_POST['your_name'] !='') && (isset($_POST['your_email'])&& $_POST['your_email'] !=''))
{

$yourName = $conn->real_escape_string($_POST['your_name']);
$yourEmail = $conn->real_escape_string($_POST['your_email']);
$yourPhone = $conn->real_escape_string($_POST['your_phone']);
$comments = $conn->real_escape_string($_POST['comments']);


$sql = "INSERT INTO contact_form_info (name, email, phone, comments)
        VALUES (?,?,?,?)";



//$stmt = mysqli_prepare($sql);
//if ($stmt = $conn->prepare(" INSERT INTO contact_form_info WHERE name = ?  email = ? phone = ? comments = ? ")) {
if ($stmt = $conn->prepare($sql)) {

$stmt->bind_param("ssss", $yourName, $yourEmail, $yourPhone,$comments);

$stmt->execute();
}

提交表单时,出现以下错误

  

检查与您的MySQL服务器版本相对应的手册,以在'?,?,?,?)?附近使用正确的语法。

有人可以检查我的代码并告诉我它怎么了吗?

在此先感谢

1 个答案:

答案 0 :(得分:0)

此错误表明,由于某些原因,问号未绑定到适当的变量。 MySQL抱怨,因为问号没有用""封装。

Ass @RiggsFolly指出,在使用准备好的语句时,不需要调用$conn->real_escape_string

(此外,无需检查isset()和一个空字符串,empty()基本上还是会isset

<?php
// db has to be manually created first
$host = "localhost";
$userName = "user";
$password = "";
$dbName = "test";

// Create database connection
$conn = new mysqli($host, $userName, $password, $dbName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(!empty($_POST['your_name']) && !empty($_POST['your_email']) {

    $sql = "INSERT INTO contact_form_info (name, email, phone, comments) VALUES (?,?,?,?)";

    $stmt = $conn->prepare($sql);

    $stmt->bind_param("ssss", $_POST['your_name'], $_POST['your_email'], $_POST['your_phone'],$_POST['comments']);

    $stmt->execute();
}