-1

I want to select data (at all) with PDO (always used mysqli) from an external database. It connects, and the query works on the server directly with mysql. With php, it doesn't. Here's my code:

<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';

function testdb_connect ($hostname, $username, $password){
    $dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
    return $dbh;
}

try {
    $dbh = testdb_connect ($hostname, $username, $password);
    echo 'Connected to database';
} catch(PDOException $e) {
    echo $e->getMessage();
}

$sql= "select * from table limit 10;"; 
echo "<br/>";
echo $sql;
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
echo $row->id;

It shows "connected to database", and the "echo $sql" part, but doesn't display any information.

Newwt
  • 491
  • 1
  • 5
  • 22

1 Answers1

2

Your first part of the question have been solved.

now this

I now want to print the 10 rows instead of just the first one. How do I do it?

The are many ways you can do that, but you need to loop through your results and display the desired Rows

Option 1

 $sql = $dbh->query("SELECT * from table limit 10")->fetchall(PDO::FETCH_ASSOC);

     foreach($sql as $row){

        // print_r($row); // see them all

        echo $row['desiredRow']; //print them one by one
     }

Option 2

 $sql = $dbh->query("SELECT * from table limit 10");

     while($row=$sql->fetch()){

        // print_r($row);
        echo $row['desiredRow'];
     }

Option 3

<?php

    $sql = "SELECT * from table limit 10";

    $stmt = $dbh->prepare($sql);
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

    if(count($results) > 0){//check results

        foreach($results as $row){

            print_r($row);
        }
    }else{

        echo "no results found";
    }
?>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34