Reputation: 1221
I am unsuccessful when attempting to query a MySQL 5.5.30 server via php5-fpm 5.4.4-14. Here is what we are trying to query:
mysql> select * from cat where cat = 'sc';
+------+------+--------------------+
| ID | cat | name |
+------+------+--------------------+
| 1 | sc | SOLID CARBIDE BITS |
+------+------+--------------------+
1 row in set (0.00 sec)
Here a similar query that first tries getting the category name and then an array which specifies some other fields. The print_r($result);
and echo $result['name'];
are not returning results. Is there something I have overlooked when attempting to query the MySQL database using PDO statements?
<?php
$pdo = new PDO('mysql:host=localhost;dbname=database','username','password');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cat= $_GET["cat"];
/* let try grabbing one of those rows, do not think an array should be here? */
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
/* based on the feedback below, we must execute */
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
echo $result['name'];
?>
Upvotes: 1
Views: 941
Reputation: 6591
You can't parse a single element like $result['name'];
because it is in an subarray.
So you should use something like $result[0]['name'];
instead to access the subarray.
If you have multiple results, use a foreach loop. Example:
foreach ($result as $subarray) {
foreach ($subarray as $key => $value) {
echo "Key: $key \n\n";
echo "Value: $value \n\n";
}
}
Check out my example: http://phpfiddle.org/main/code/z7w-jhk
Upvotes: 1
Reputation: 1343
MySQL native prepare doesn't support named parameters, so you can change :cat
to ?
, or set PDO::ATTR_EMULATE_PREPARES
to true
.
Also, you can add a try
statement to see the exception and error message.
Upvotes: 1
Reputation: 19979
You need to call execute
, try this:
$stmt->bindParam(':cat', $cat);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Upvotes: 1