show PHP PDO data

2

I'm trying to show some results using PDO. Until now I used mysqli_conect() for the connection to the database. I guess the error is found by showing the results in the 'foreach ()' Someone would know how to correct the fault? 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;

?>
    
asked by gmarsi 09.05.2017 в 21:15
source

2 answers

3

You must use PDOStatement :: fetch or PDOStatement::fetchAll to retrieve the results.

<?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
    $stmt->setFetchMode(PDO::FETCH_ASSOC); 

    /* creamos un while para optener fila a fila los refultados devueltos mediante fetch() */
    while ($row = $stmt->fetch()) {
        echo $row['Prod_Usu'] . " - " . $row['Prod_Tit'] . " - " .$row['Prod_Fec'] . "<br>";
    }

}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

?>
    
answered by 10.05.2017 / 00:30
source
0

There is just one line of your code that is wrong.

Changing this:

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

for this:

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

should work.     

    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->fetchAll(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;

    ?>

Then, the result set can be read using a foreach loop or using while .

    
answered by 10.05.2017 в 04:06