Canttouchit
Canttouchit

Reputation: 3159

Cannot query MySQL DB using PDO

My code is very simple:

 $con1 = new PDO("mysql:host=localhost;port=3306;dbname=users_db", "root", "");
 $resp = $con1 -> query('SELECT * FROM records');

The response I get inside $resp is the query string 'SELECT * FROM records' no clue why. The same query is working using mysqli.

I tried debugging and I see a strange value {POD}[0] in $con1 after creating the PDO instance. What am I doing wrong here I followed this phpro.org.

Upvotes: 0

Views: 61

Answers (1)

Perry
Perry

Reputation: 11710

Try this code:

<?php

// Connect to MySQL via PDO
try {
$con1 = new PDO("mysql:host=localhost;port=3306;dbname=users_db", "root", "");
$con1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

try {
$resp = $con1 -> query('SELECT * FROM records');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

You will get a Exception when the connection fails or when the query fails.

Upvotes: 2

Related Questions