We help IT Professionals succeed at work.

Error in connection string

mustish1
mustish1 asked
on
Can you please help me in that error.
screenshot2.JPGscreenshot.JPG
<?php
$user = "root";
$passwd = "";
$dsn      = 'mysql:host=localhost;dbname=coffeedb;charset=utf8mb4'; 
$options  = [
    PDO::ATTR_EMULATE_PREPARES   => false,
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
];

$db = new \PDO($dsn, $username, $passwd, $options);
?>

Open in new window


<?php
require 'Credentials/credentials.php';
$coffee = new CoffeeModel($db);

var_dump( $coffee->GetCoffeeTypes() );
var_dump( $coffee->GetCoffeeByType('sometype') );
require ("Entities/CoffeeEntity.php");

//Contains database related code for the Coffee page.
class CoffeeModel {

    private $db;

    public function __construct(\PDO $db) {
        $this->db = $db;
    }

    public function GetCoffeeTypes() {
        $stmt = $this->db->query("SELECT DISTINCT type FROM coffee");
		
        return $stmt->fetchAll();
    }

    public function GetCoffeeByType($type) {
        $stmt = $this->db->prepare("SELECT name, type, price, roast, country, image, review FROM coffee WHERE type LIKE :type");
        $stmt->execute(['%' . $type . '%']);
		
        return $stmt->fetchAll(PDO::FETCH_CLASS, 'CoffeeEntity');
    }

}
?>

Open in new window


<?php

class CoffeeEntity
{
    public $id;
    public $name;
    public $type;
    public $price;
    public $roast;
    public $country;
    public $image;
    public $review;
    
    function __construct($id, $name, $type, $price, $roast, $country, $image, $review) {
        $this->id = $id;
        $this->name = $name;
        $this->type = $type;
        $this->price = $price;
        $this->roast = $roast;
        $this->country = $country;
        $this->image = $image;
        $this->review = $review;
    }

}


?>

Open in new window

Comment
Watch Question

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:

Hi,


In your connection code, you've stored the username in a variable called $user, but then in the connection you've tried to use a variable called $username:


$user = "root";...
$db = new \PDO($dsn, $username, $passwd, $options);


Make sure they match.


When developing, always turn on error reporting by adding this at the very start of your script:


error_reporting(E_ALL);
ini_set('display_errors', 1);


That would have shown you that you're using an undefined variable ($username)


Don't forget to turn it off again before going into production!



Most Valuable Expert 2018
Distinguished Expert 2018
Commented:

One other thing. In the code I posted in your previous question, there is a slight typo in the query. Change the :type bit to a question mark:


$stmt = $this->db->prepare("SELECT name, type, price, roast, country, image, review FROM coffee WHERE type LIKE ?");         


Author

Commented:
Thank You.