简体   繁体   中英

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

I'm using a PDO driver to connect to a mySQL database. I have had luck querying this database when I search by ID; however, when I try to change the query from ID to first_name, I just get an error. 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. 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! The error happens because you initialize the variable result inside the try block. 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!.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM