user12004501
user12004501

Reputation:

How to connect to mysql using pdo

I am working on my php as I want to connect to the mysql database using PDO. I have stored the username, password and database in the config file, but I have got a problem with connecting to the mysql database because I keep getting an error.

When I try this:

<?php

//Connect to the database
include('config.php');

$smtps = $link->query('SELECT * FROM sent');
$smtps->execute();
$db = $smtps->get_result();

print($db);
?>

I am getting an error:

Fatal error: Uncaught Error: Call to undefined method PDOStatement::get_result() in /home/username/public_html/test_pdo.php:17 Stack trace: #0 {main} thrown in /home/username/public_html/test_pdo.php on line 17

Here is the line 17:

$db = $smtps->get_result();

Here is the config:

<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'dbtablename');
//$errflag = false;
$link = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);

?>

Can you please show me an example how do you connect to mysql database using PDO when you stored the username, password and database name in config.php?

Thank you.

Upvotes: 0

Views: 164

Answers (3)

SilasKenneth
SilasKenneth

Reputation: 21

get_results is not a method of the PDO class. If you want to fetch data from the database in this case, use fetchAll() method of the query object.


<?php

//Connect to the database
include('config.php');

$smtps = $link->query('SELECT * FROM sent');
$smtps->execute();
$db = $smtps->fetchAll();

print($db);
?>

Hope that helps.

Upvotes: 0

Oli Girling
Oli Girling

Reputation: 773

This is happening because get_result() is not a PDO method.

In this situation you should just use fetch() (link) if you just want the first result or fetchAll() (link) if you want an array of the results

Try this:

$smtps = $link->query('SELECT * FROM sent');
$result = $smtps->fetchAll();

print($result);

You only need to use the excute() when using parameters in your select:

SELECT * FROM sent where id = ?

would be

$smtps = $link->prepare('SELECT * FROM sent where id = ?');
$smtps->execute([$id]);
$result = $smtps->fetch();

print($result);

Upvotes: 1

If u use query method u can without execute method get result as as below cod

include('config.php');

$result = $link->query('SELECT * FROM sent')->fetchAll(PDO::FETCH_ASSOC);


print_r($result);

Upvotes: 0

Related Questions