php - Can't select data with PDO -
i want select data (at all) pdo (always used mysqli) external database. connects, , query works on server directly mysql. php, doesn't. here's 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 database'; } catch(pdoexception $e) { echo $e->getmessage(); } $sql= "select * table limit 10;"; echo "<br/>"; echo $sql; $stmt = $pdo->prepare($sql); $stmt->execute(); $row = $stmt->fetchobject(); echo $row->id;
it shows "connected database", , "echo $sql" part, doesn't display information.
your first part of question have been solved.
now
i want print 10 rows instead of first one. how it?
the many ways can that, need loop through results , display desired rows
option 1
$sql = $dbh->query("select * table limit 10")->fetchall(pdo::fetch_assoc); foreach($sql $row){ // print_r($row); // see them echo $row['desiredrow']; //print them 1 one }
option 2
$sql = $dbh->query("select * table limit 10"); while($row=$sql->fetch()){ // print_r($row); echo $row['desiredrow']; }
option 3
<?php $sql = "select * table limit 10"; $stmt = $dbh->prepare($sql); $results = $stmt->fetchall(pdo::fetch_assoc); if(count($results) > 0){//check results foreach($results $row){ print_r($row); } }else{ echo "no results found"; } ?>
Comments
Post a Comment