php 写入数据库时Call to a member function bind_param() on a non-object

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests VALUES(?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// 设置参数并执行
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>

 运行时报错:

Call to a member function bind_param() on a non-object

原因:
bind_param 的第二个参数是起引用传递的
直接写成字符串,这是在 php 5.3 及以后是不允许的

解决方法:
将 $stmt = $conn->prepare("INSERT INTO myguests VALUES(?,?,?)");
改成$stmt = $conn->prepare("INSERT INTO myguests(firstname, lastname, email) VALUES(?,?,?)");
posted @ 2016-08-04 08:48  JohnYunhan  Views(903)  Comments(0Edit  收藏  举报