调用成员函数 execute() on



在第 27 行遇到问题,不太清楚为什么,因为我对 PHP/MySQL 很陌生。想知道是否有人可以告诉我为什么我会出现错误;

"致命错误:在非对象上调用成员函数 execute() C:\xampp\htdocs\testscripts\usercreate.php 在第 27 行"

在以下代码中:

<?php
$name = $_POST["name"];
$psswrd = $_POST["psswrd"];
$username = "root";
$password = "hidden";
$hostname = "localhost";
$table = "testtable";

// create connection to database
// ...

$db= new mysqli($hostname, $username, $password, $table);
// sanitize the inputs
// ...
// create an MD5 hash of the password
$psswrd = md5($psswrd);
// save the values to the database
$sql = "INSERT INTO accounts (name, psswrd) VALUES (:name, :psswrd)";
$stmt = $db->prepare($sql);
$stmt->execute(array(
    ":name" => $name,
    ":psswrd" => $psswrd
));

->prepare 如果发生错误,则返回false。由于$stmt->execute抱怨在非对象上被调用,因此可以合理地假设查询出了问题。

检查$db->error

试试这个:

$db= new mysqli($hostname, $username, $password, $table);
if ($db->connect_errno) {
    throw new Exception($db->connect_error, $db->connect_errno);
}
$psswrd = md5($psswrd);
// save the values to the database
$sql = "INSERT INTO accounts (name, psswrd) VALUES (:name, :psswrd)";
$stmt = $db->prepare($sql);
if (!$stmt) {
    throw new Exception($db->error);
}
$stmt->execute(array(
    ":name" => $name,
    ":psswrd" => $psswrd
));

显示您的所有异常,以便更好地了解给定的错误。

首先,MySQLi 类采用的第四个参数是数据库名称,而不是表名称。

因此,将$table = 'testtable';更改为如下所示:$dbname = 'dbname';

此外,在代码中,您正在使用命名参数(:name and :passwrd) .这不起作用,因为MySQLi不支持命名参数。PDO(PHP 数据对象)支持命名参数。如果使用 PDO 类连接到数据库,则脚本将正常工作!

如果要使用 MySQLi 类连接到数据库,请执行以下操作:

$name = $_POST['name'];
$psswrd = $_POST['psswrd'];
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "dbname";

// create connection to database
// ...

$db= new mysqli($hostname, $username, $password, $dbname);
// sanitize the inputs
// ...
// create an MD5 hash of the password
$psswrd = md5($psswrd);
// save the values to the database
$sql = "INSERT INTO `testtable` (id, name) VALUES (?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $name, $psswrd);
$stmt->execute();

试试看。使用问号而不是命名参数。

在 bind_param() 函数中,我将第一个参数编写为 'ss' 。这里的两个"s"代表字符串。如果您有整数数据,则可以将"s"替换为'i'

至于为什么有两个"s",这是不言自明的。这是因为您将两个变量绑定到 SQL 查询,它们都是字符串。因此,两个"s"。

相关内容

最新更新