0

こんにちは、データベースに投稿しようとすると、これらの 2 つのエラーが発生します

注意: 未定義の変数: C:\xampp\htdocs\phptuts\sandbox\blog\admin\index.php の 17 行目の 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);

そして2つ目はこちら

致命的なエラー: 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 で php の基礎コースを行っていたので、誰かが私を助けてくれることを願っています。

ここでの更新は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
}
4

2 に答える 2