php - PDO Read From Database -
i have made code using pdo read table database. try echo result blank page without error.
my code is:
<?php include 'config.php'; id = "264540733647332"; try { $conn = new pdo("mysql:host=$hostname;dbname=mydata", $username, $password); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); } catch(pdoexception $e) { echo "connection failed: " . $e->getmessage(); } $result = $conn->query("select * mytable id='".$id."';"); if ($result->fetchcolumn() != 0) { foreach ( $result->fetchall(pdo::fetch_both) $row ) { $data1 = $row['data1']; $data2 = $row['data2']; echo $data2; } } ?>
but echo empty without error. doing wrong?
thank all!
few things change:
- dont forget
$
- if going catch error, catch whole pdo code
- you can use
rowcount()
count rows - echo if record count 0
include 'config.php'; $id = "264540733647332"; try { $conn = new pdo("mysql:host=$hostname;dbname=mydata", $username, $password); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $result = $conn->query("select * mytable id='".$id."';"); if ($result->rowcount() != 0) { $row = $result->fetch(pdo::fetch_both); echo $row['data1']; echo $row['data2']; }else{ echo 'no row found'; } }catch(pdoexception $e){ echo "error " . $e->getmessage(); }
also use prepared statements example:
$result = $conn->prepare("select * mytable id=:id"); $result->execute(array(':id'=>$id));
Comments
Post a Comment