简体   繁体   English

使用带有 PDO::query() 的字符串查询数据库时遇到问题

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

I'm using a PDO driver to connect to a mySQL database.我正在使用 PDO 驱动程序连接到 mySQL 数据库。 I have had luck querying this database when I search by ID;当我按 ID 搜索时,我很幸运地查询了这个数据库; however, when I try to change the query from ID to first_name, I just get an error.但是,当我尝试将查询从 ID 更改为 first_name 时,我只是收到一个错误。 Below is my code:下面是我的代码:

This code works此代码有效

//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);

This returns:这将返回:

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

So now, instead of searching by ID, I just want to search by first name.所以现在,我只想按名字搜索,而不是按 ID 搜索。 Here is the slightly altered code:这是稍微改变的代码:

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);

This returns the following error:这将返回以下错误:

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

Any insight into why this might be happening?关于为什么会发生这种情况的任何见解?

You're open for SQL injections!您可以接受 SQL 注入! The error happens because you initialize the variable result inside the try block.发生错误是因为您在try块内初始化了变量result The variable isn't accessible outside the try-catch block if a error occurs, which is fact because strings need to be wrapped with single quotes in a SQL query!.如果发生错误,则在try-catch块之外无法访问该变量,这是事实,因为在 SQL 查询中字符串需要用单引号括起来!。

A better way to do it is:一个更好的方法是:

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