How do I define the $db variable? I tried using the '$dsn' variable I have in the connection_pdo.php file because just seems right and that removes the undefined variable notice. However, the fatal error for the prepare() call is still there. I've read PDO::prepare and the '$dbh' variable in $dbh->prepare(); isn't explained at all. Here are my errors:
*Notice: Undefined variable: db in C:\xampp\htdocs\kami715\A10\customers.php on line 14
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\kami715\A10\customers.php:14 Stack trace: #0 {main} thrown in C:\xampp\htdocs\kami715\A10\customers.php on line 14*
<!--query to pull in data-->
<?php
include('connection_pdo.php');
$query = "SELECT id, first_name, last_name FROM customers ORDER BY last_name asc";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
?>
Here is 'connection_pdo.php':
<?php
// set up for using PDO
$user = 'root';
$pass = 'admin';
$host = 'localhost';
$db_name = 'grangerinc';
// set up DSN
$dsn = "mysql:host= $host; dbname= $db_name";
?>
CodePudding user response:
The definition of your connection variable $dsn is not correct. In addition "store_result()" is a mysqli function and the "include" expression is not used properly.
<?php
include 'connection_pdo.php';
$query = "SELECT id, first_name, last_name FROM customers ORDER BY last_name asc";
$stmt = $dsn->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$stmt = null;
print_r($result);
?>
connection_pdo.php:
<?php
// set up for using PDO
$user = 'root';
$pass = 'admin';
$host = 'localhost';
$db_name = 'grangerinc';
// set up DSN
$dsn = new PDO('mysql:host='.$host.';dbname='.$db_name, $user, $pass);
?>