PHP错误:在非对象上调用成员函数execute()

时间:2012-08-25 12:40:14

标签: php mysql function

  

可能重复:
  PHP Fatal error: Call to a member function Execute() on a non-object

我对php和mysql很新,所以请耐心等待。我写了这段代码,但是当我尝试从数据库中删除记录时,我收到以下错误:

<?php
require_once 'login_rankings.php';
$mysqli = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if ($mysqli->connect_errno) {
echo "Failed to connect to database: " . $mysqli->connect_errno . ": " .
$mysqli->connect_error;
}

$query = "SELECT * FROM nfl";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows); echo "<br /><br /><br />";

if (isset($_POST['delete']) && isset($_POST['id']))
{
// $id = get_post('id');
$query = "DELETE FROM nfl WHERE id= :id LIMIT 1";



try{
$stmt = $mysqli->prepare($query);
$stmt->execute(array(':id' => $_POST['id']));
}catch(Exception $e){
error_log($e->getMessage() . '\r\n',3, errors.log);
}

/* not working either
  $stmt = $mysqli->prepare($query);
  $stmt->bind_param("id", $id);
  $stmt->execute(); */
}


$rows = $stmt->num_rows;
$res = $mysqli->query($query);

for ($j = 0; $j < $rows; ++$j)
{
$row = $res->fetch_assoc();
require_once 'abbrs.php';

echo <<<_END
<pre>
Last name: $row[lastname]
First name: $row[firstname]
Team: $row[team]
Position: $row[position]
Number: $row[number]
Age: $row[age]
Id: $row[id]</pre>
<form action="ranking_nfl.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="$row[id]" />
<input type="submit" value="DELETE" />
</form>
_END;

}


$stmt->close();

$mysqli->close();
?>
  

致命错误:在第24行的C:\ web \ project2 \ ranking_nfl.php中的非对象上调用成员函数execute()

我想我的代码缺少一个从表单中获取'id'结果的函数?我不知道应该写些什么。

1 个答案:

答案 0 :(得分:3)

你正在混淆PDO和mysqli语法。

在PDO中,您可以使用:id之类的变量并在之后绑定它们。在mysqli中,你必须使用问号,然后在execute语句之前绑定变量,而不是通过输入数组。

在您的情况下(取自manual,我通常使用PDO):

$query = "DELETE FROM nfl WHERE id= ? LIMIT 1";

try{
  $stmt = $mysqli->prepare($query);
  $stmt->bind_param('i', $_POST['id']);
  $stmt->execute();