簡體   English   中英

使用帶有 PDO::query() 的字符串查詢數據庫時遇到問題

[英]Having trouble querying the database with a String with PDO::query()

我正在使用 PDO 驅動程序連接到 mySQL 數據庫。 當我按 ID 搜索時,我很幸運地查詢了這個數據庫; 但是,當我嘗試將查詢從 ID 更改為 first_name 時,我只是收到一個錯誤。 下面是我的代碼:

此代碼有效

//functions.php file

function query_database($id) {
    include("connection.php");

    try {
        $results = $db->query("SELECT first_name, last_name FROM master_tradesmen WHERE id = $id");
        }catch(Exception $e) {
            echo "Something went wrong with the query.";
        }

        $data = $results->fetch();
        return $data;
    }

    $res = query_database(1);
    print_r($res);

這將返回:

Array ( [first_name] => Steve [0] => Steve [last_name] => Albertsen [1] => Albertsen )

所以現在,我只想按名字搜索,而不是按 ID 搜索。 這是稍微改變的代碼:

function query_database($name) {
    include("connection.php");

    try {
        $results = $db->query("SELECT first_name, last_name FROM master_tradesmen WHERE first_name = $name");
        }catch(Exception $e) {
            echo "Something went wrong with the query.";
        }

        $data = $results->fetch();
        return $data;
    }

    $res = query_database('Steve');
    print_r($res);

這將返回以下錯誤:

Notice: Undefined variable: results in /home/locompre/public_html/php/functions.php on line 12

Fatal error: Uncaught Error: Call to a member function fetch() on null in /home/locompre/public_html/php/functions.php:12 Stack trace: #0 /home/locompre/public_html/php/functions.php(16): query_database('Steve') #1 {main} thrown in /home/locompre/public_html/php/functions.php on line 12

關於為什么會發生這種情況的任何見解?

您可以接受 SQL 注入! 發生錯誤是因為您在try塊內初始化了變量result 如果發生錯誤,則在try-catch塊之外無法訪問該變量,這是事實,因為在 SQL 查詢中字符串需要用單引號括起來!。

一個更好的方法是:

function query_database($name) {
    include("connection.php");
    try {
        $stmt = $db->prepare("SELECT first_name, last_name FROM master_tradesmen WHERE first_name = :name");
        $stmt->bindValue(':name', $name);
        $stmt->execute();

        $data = $stmt->fetchAll();
        return $data;
    }catch(Exception $e) {
        echo "Something went wrong with the query.\n<br>".
            "Error: \n<br>" . $e->getMessage() . "\n<br>" . 
            "StackTrace: \n<br>"  . $e->getTraceAsString();
        return null;
    }

}

$res = query_database('Steve');
print_r($res);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM