I am trying to display some results using PDO. Until now used mysqli_conect()
for connection to the database. I suppose that the error is found when displaying the results in the `foreach()´. Could someone tell me how I can correct the error? Thanks in advance"
Code:
<?php
try {
$conn = new PDO("sqlsrv:server = tcp:name.database.windows.net,1344;
Database = my_db_name", "my_user_name", "my_password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Prod_Usu, Prod_Tit, Prod_Fec FROM productos");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($result as $row) {
echo $row['Prod_Usu'] . " - " . $row['Prod_Tit'] . " - " .
$row['Prod_Fec'] . "<br>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
You must use PDOStatement::fetch or PDOStatement::fetchAll to retrieve the results.
There is only one line of your code that is wrong.
Changing this:
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
For this:
it should work.
The result set can then be read using a loop
foreach
or usingwhile
.