大家好,我在尝试发布到我的数据库时遇到这两个错误
注意:未定义变量:第 17 行 C:\xampp\htdocs\phptuts\sandbox\blog\admin\index.php 中的 conn
这是代码;
> <?php
require '../functions.php';
require '../db.php';
$data = array();
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
$title = $_POST['title'];
$body = $_POST['body'];
if ( empty($title) || empty($body) ) {
$data['status'] = 'Please fill out both inputs';
} else {
Blog\DB\query(
"INSERT INTO posts(title, body) VALUES(:title, :body)",
array('title' => $title, 'body' => $body),
$conn); // line 17
}
}
view('admin/create', $data);
这是第二个
致命错误:在第 26 行调用 C:\xampp\htdocs\phptuts\sandbox\blog\db.php 中非对象的成员函数 prepare()
function query($query, $bindings, $conn)
{
$stmt = $conn->prepare($query); //line 26
return $stmt->execute($bindings);
}
希望有人可以帮助我,因为我正在 tutsplus The Obligatory Blog 上学习 php 基础课程:第 4 部分在这里找到https://tutsplus.com/lesson/the-obligatory-blog-part-4/
这里更新的是 db.php 文件
<?php namespace Blog\DB;
$config = array(
'username' => 'root',
'password' => 'foobar',
'database' => 'blog'
);
function connect($config)
{
try {
$conn = new \PDO('mysql:host=localhost;dbname=' . $config['database'],
$config['username'],
$config['password']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (Exception $e) {
return false;
}
}
function query($query, $bindings, $conn)
{
$stmt = $conn->prepare($query);
$stmt->execute($bindings);
return ($stmt->rowCount() > 0) ? $stmt : false;
}
function get($tableName, $conn, $limit = 10)
{
try {
$result = $conn->query("SELECT * FROM $tableName ORDER BY id DESC LIMIT $limit");
return ( $result->rowCount() > 0 )
? $result
: false;
} catch(Exception $e) {
return false;
}
}
function get_by_id($id, $conn)
{
$query = query(
'SELECT * FROM posts WHERE id = :id LIMIT 1',
array('id' => $id),
$conn
);
if ( $query ) return $query->fetchAll();
// else
}