php - Page will not echo results with PDO statement -



php - Page will not echo results with PDO statement -

my function not want load. trying echo out id, name, , age. doing wrong?

class="lang-php prettyprint-override"><?php $db_host = "localhost"; $db_username = "root"; $db_pass = ""; $db_name = "testdb"; $dbh = new pdo('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_warning); function getmanger () { global $con; $sql= $dbh->prepare("select * test_tbl"); $stmt = $db->prepare($sql); $stmt->execute(); while( $row = $stmt->fetch(pdo::fetch_assoc) ) { $id= $row['id']; $name = $row['name']; $age - $row['age']; echo "<li>$id</li>"; echo "<li>$name</li>"; echo "<li>$age</li>"; } } ?>

to outline errors in code, , offer tested , working solution:

you're calling prepare() function twice. using wrong variable select. ...using $sql should $stmt not possibly calling getmanger() function. using hyphen instead of equal sign $age - $row['age']; => $age = $row['age'];

rewrite:

<?php $db_host = "localhost"; $db_username = "root"; $db_pass = ""; $db_name = "testdb"; $dbh = new pdo('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_warning); function getmanger($dbh) { $stmt= $dbh->prepare("select * test_tbl"); $stmt->execute(); while( $row = $stmt->fetch(pdo::fetch_assoc) ) { $id = $row['id']; $name = $row['name']; $age = $row['age']; echo "<li>$id</li>"; echo "<li>$name</li>"; echo "<li>$age</li>"; } } // phone call function getmanger($dbh);

footnotes:

it's best pass db connection variable within function, rather making global.

here few articles on stack global:

http://stackoverflow.com/a/5166527/ http://stackoverflow.com/a/5166276/

the selection yours.

php mysql pdo

Comments

Popular posts from this blog

javascript - I need to update the text of a paragraph by inline edit -

javascript - THREE.js reposition vertices for RingGeometry -

assembly - What is the addressing mode for ld, add, and rjmp instructions? -