我知道这个问题已被多次询问,但我不能让它适用于我的代码,请耐心等待我,我是php
oop
{{1 }}
我的目标
使用pdo
php
oop
问题
它返回此错误:
pdo
我查看了php docs about pdostatement
我从this tutorial学到了Undefined property: PDOStatement::$fetch
,但我无法用我的代码翻译它,
这是我的代码:
Crud.php
crud
Index.php (我要帖子发布到哪里)
<?php
include 'connection.php';
class Crud{
private $db;
function __construct($pdo)
{
$this->db = $pdo;
}
public function create_post($post_title, $post_content)
{
try{
$query = "INSERT INTO posts(post_title, post_content) VALUES (:ptitle, :pbody)";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':ptitle', $post_title);
$stmt->bindParam(':pbody', $post_content);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
$e->getMessage();
}
}
public function setQuery($sql)
{
try{
$query = $this->db->prepare($sql);
$query->execute();
return $query;
}
catch (PDOException $e)
{
$e->getMessage();
}
}
}
我很困惑。任何建议和最佳做法(适用于<?php
error_reporting(E_ALL);
require_once 'inc/Crud.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to house</title>
</head>
<body>
<h1>This is the home page</h1>
<?php
$crud = new Crud($pdo);
$sql = "SELECT * FROM posts";
if($result=$crud->setQuery($sql) )
{
if($count = $result->fetch)
{
echo '<p>', $count, '</p>';
while($row = $result->fetch_assoc())
{
echo $row['post_title'], '<br>';
}
}
}
?>
</body>
</html>
及以上)?
答案 0 :(得分:1)
fetch
是一个函数,而不是属性
请改用:
if($count = $result->fetch())
^^
答案 1 :(得分:0)
感谢所有帮助过的人,你们都指引我朝着正确的方向前进。
这是正确的代码
<?php
error_reporting(E_ALL);
require_once 'inc/Crud.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to house</title>
</head>
<body>
<h1>This is the home page</h1>
<?php
$crud = new Crud($pdo);
$sql = "SELECT * FROM posts";
if($result=$crud->setQuery($sql) )
{
if($count = $result->fetchColumn(PDO::FETCH_ASSOC))
{
echo '<p>', $count, '</p>';
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
echo $row['post_title'], '<br>';
}
}
}
?>
</body>
</html>