插入stmt bind params的问题

时间:2014-07-15 03:41:27

标签: php mysql sql

我的SQL有另一个问题。您可以在下面看到我正在使用的代码:

<?php
$con=mysqli_connect("localhost","user","pass","my_db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$name = mysqli_real_escape_string($con, $_POST['name']);
$contactpersonname = mysqli_real_escape_string($con, $_POST['contactpersonname']);
$departmentname = mysqli_real_escape_string($con, $_POST['departmentname']);
$title = mysqli_real_escape_string($con, $_POST['title']);
$email= mysqli_real_escape_string($con, $_POST['email']);

$stmt = $con -> prepare("INSERT INTO Contacts (Name, ContactPerson, Department, Title, EmailAddress) VALUES ('?', '?', '?', '?', '?')");
$stmt -> bind_param("sssss", $name, $contactpersonname, $departmentname, $title, $email);
$stmt -> execute();


echo "1 record added";

mysqli_close($con);
?>

由于某种原因,参数没有正确绑定,数据库只有&#39;?&#39; (问号)插入。我有正确的数据库插入数据,但没有绑定参数。一个人告诉我,它让我容易受到SQLi的攻击,因此我尝试过渡到stmt。我几乎不知道为什么会发生这种情况。如果可能的话,请帮帮我。 PS。我通过php手册阅读了stmt绑定,但我不确定我是否做得对。

1 个答案:

答案 0 :(得分:0)

单引号(')表示SQL中的varchar文字。通过用引号括住?,您可以防止它们受到约束。只需删除引号就可以了:

$stmt = $con -> prepare("INSERT INTO Contacts (Name, ContactPerson, Department, Title, EmailAddress) VALUES (?, ?, ?, ?, ?)");