Reputation: 738
I am comfortable with using mysqli style php queries but am trying to use more PDO. I think I understand most of how to use it but every now and again something comes up which throws me.
So I am doing a basic SELECT query to a mysql database and I cant get any results from the query
PHP
try {
$dbhandle = new PDO("mysql:dbname = {$dbname}; host = {$dbhost}; port = {$dbport}", $dbuser, $dbpass);
} catch (PDOException $e)
{
echo "Error when creating Database Handle. Error: " .$e;
}
$sql = $dbhandle->prepare("SELECT projectName FROM `__projects`");
$sql->execute();
$projectList = $sql->fetch(PDO::FETCH_BOTH);
$size = sizeof($projectList);
echo $size;
I don't understand why The array returned is empty. Am I making a mistake. I know the user/pass are ok as I can return results using the same query when using mysqli methods.
What am I doing wrong?
Upvotes: 1
Views: 2188
Reputation: 1137
Try adjusting your connection statement. I'm not certain if the order will affect it, but from the documentation, it should be similar to:
mysql:host=localhost;port=3307;dbname=testdb
http://php.net/manual/en/ref.pdo-mysql.connection.php
Thanks,
Andrew
Upvotes: 1
Reputation: 204
When you want to execute a query, first make sure it will run by making it not equal or equal to false. That way you can debug your script. Try to prepare the Query alone instead of executing it right away.
The following example selects the rows in which the 'id' is 1 or 3.
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `sites` WHERE `id` IN(1, 3)";
$result = $conn->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
$cols = $result->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($result as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Upvotes: 0