0

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

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

在以下代码中:

<?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
));
4

3 回答 3

0

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

检查$db->error

于 2013-12-24T12:21:51.120 回答
0

首先,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'。

于 2013-12-24T14:35:03.080 回答
0

尝试这个 :

$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
));

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

于 2013-12-24T12:28:14.663 回答