在非对象中调用成员函数execute()

时间:2015-02-07 15:14:41

标签: php mysql session

我有以下错误,这是我用于注册用户的完全相同的表单处理文件,但我更改了适当的表和列。虽然reg每次都很好。 以下是错误所在的代码:

$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
 
这是完整的代码:

<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];


if($eventname == '') {
  $errmsg_arr[] = 'You must enter your Email';
  $errflag = true;
}
if($about == '') {
  $errmsg_arr[] = 'You must enter your Password';
  $errflag = true;
}
if($website == '') {
  $errmsg_arr[] = 'You must enter First Name';
  $errflag = true;
}

$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
 


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

1 个答案:

答案 0 :(得分:2)

你混淆了PDO和mysqli。 mysqli不支持命名参数,因此stmt没有编译,Mysqli::prepare返回false。另外mysqli不支持传递param以通过mysqli_stmt::execute绑定,所以即使你切换到位置占位符,你的执行也会失败。

这就是你需要的mysqli:

$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);

// check to make sure the statement was prepared without error
if ($stmt) {
   // the statement is good - proceed
   $stmt->bind_param('sss', $eventname, $about, $website);
   $stmt->execute();
}

此外这根本没有意义:

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

这将再次运行相同的查询,无论是插入完全相同的数据的第二行,还是根据您的架构创建重复的键错误。

如果您想测试上一个查询是否成功,您可以执行以下操作:

$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param('sss', $eventname, $about, $website);
    $success = $stmt->execute();
} else {
    $success = false;
}

if ($success === true) {
     echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

如果您想使用PDO(我更喜欢并且通常建议使用),您的代码将如下所示:

$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


try {
    $sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
    echo "New record created successfully";
} catch (PDOException $e) {
    echo "Error: " . $sql . "<br>" . $e->getMessage();
}