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?