Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch data from database using this prepare statement

Tags:

php

mysql

pdo

//this is my connection function. It is connecting databse successfully when I check.
$conn = connection($config['servername'],$config['username'],$config['password']);

after this I Used following code to fetch data from Database

$id = 2;
if($conn) {

    try {

        $stmt = $conn->prepare('SELECT * FROM customer_tbl WHERE cus_id = :id');
        $stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt->bindParam(':id', $id);

        $results = $stmt->execute();

    }catch (PDOException $e){

        echo 'Error: ' . $e->getMessage();
    }

}

this code showing following error message on the browser

Error: SQLSTATE[IM001]: Driver does not support this function: This driver doesn't support setting attributes

what's wrong with my code?. Why I could not fetch data's from database?

if I want to fetch this specified data from databese using prepare statement how to code?

like image 622
Haither Ali Avatar asked Mar 13 '23 21:03

Haither Ali


1 Answers

Add the following

$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

after the connection string with $conn Object

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

To fetch data use

$stmt->execute();    
$rows= $stmt->fetch(PDO::FETCH_ASSOC);
print_r($rows); // to print an array

it will return data in associative array format. PDO provides various fetch options look here

like image 80
guri Avatar answered Mar 15 '23 09:03

guri