Try echoing data from a database with PDO but this is just empty
here is my code
categories_view.php
<table width="100%" align="center" border=0 bordercolor="#FFFFFF">
<tr><td colspan=2 align="center" bgcolor="#0000CC"><?php header_web();?></td></tr>
<tr>
<td width="200px" valign="top" bgcolor="white"><?php menu();?></td>
<td valign="top"><p class="judul">CATEGORIES</p>
<?php
try {
$link=connection();
$sql="select * from category order by name";
$result=$link->query($sql);
$record=$result->fetchColumn();
if($record>0){
?>
<div align="center" class="info">Categories found : <b><?php echo $record;?></b> Record</div>
<table border=0 align="center">
<tr class="jtable"><td colspan=4>LIST OF CATEGORIES</td></tr>
<tr class="jtable"><td>ID</td><td>NAME</td><td>DESCRIPTION</td><td>EDIT/DELETE</td></tr>
<?php
$i=0;
while($data=$result->fetch(PDO::FETCH_ASSOC)){
$i++;
?>
<tr class="<?php if($i%2==1) echo "oddtable"; else echo "eventable";?>">
<td align="center"><?php echo $data['id_category'];?></td>
<td><?php echo $data['name'];?></td>
<td align="center"><?php echo $data['desc'];?></td>
<td align="center"><a href="category_edit.php?id_category=<?php echo $data['id_category'];?>"><img src="edit.png"></a>
<a href="category_del.php?id_category=<?php echo $data['id_category'];?>"><img src="delete.png"></a></td>
</tr>
<?php
}
?>
</table>
<?php
}
else {
echo "No data is found ";
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
</td>
</tr>
<tr><td colspan=2 bgcolor="#FFCC00"><?php footer_web();?></td></tr>
</table>
and here's the connect function in con.php
function connection(){
try{
$link= new PDO("mysql:host=localhost;dbname=dbeorder","root","");
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
echo "Error : ".$e->getMessage();
}
return $link;
}
it returns $ record = $ result-> fetchColumn () correctly. but nothing is shown in the list of category categories, just blank. am i doing it wrong?
+3
source to share
1 answer
You do not need to fetchColumn()
fetch(PDO::FETCH_ASSOC)
return an array in which you can usecount()
......
$data=$result->fetch(PDO::FETCH_ASSOC);
if(count($data)>0){
...
foreach ($data as $data){
..............
<td align="center"><?php echo $data['id_category'];?></td>
..............
0
source to share