I am new when It comes to PHP. I've been having issues displaying my table from mysql in my site. I found this code that doesn't seem to work. Can someone please tell me what's wrong the code? Or suggest a better way to output mysql to an html table.
<?php $username="user";$password="password";$database="database";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM tablename";$result=mysql_query($query);
$num=mysql_numrows($result);mysql_close();?>
<div class="panel-body">
<table class="table table-bordered table-striped mb-none" id="datatable-tabletools" data-swf-path="assets/vendor/jquery-datatables/extras/TableTools/swf/copy_csv_xls_pdf.swf">
<thead>
<tr>
<th>id</th>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Value4</th>
<th>Value5</th>
<th>Value6</th>
<th>Value7</th>
<th>Value8</th>
</tr>
</thead>
<?php$i=0;while ($i < $num)
$f1=mysql_result($result,$i,"id");
$f2=mysql_result($result,$i,"v1");
$f3=mysql_result($result,$i,"v2");
$f4=mysql_result($result,$i,"v3");
$f5=mysql_result($result,$i,"v4");
$f6=mysql_result($result,$i,"v5");
$f7=mysql_result($result,$i,"v6");
$f8=mysql_result($result,$i,"v7");
$f9=mysql_result($result,$i,"v8"); ?>
<tbody>
<tr class="gradeX">
<td><?php echo $f1; ?></td>
<td><?php echo $f2; ?></td>
<td><?php echo $f3; ?></td>
<td><?php echo $f4; ?></td>
<td><?php echo $f5; ?></td>
<td><?php echo $f6; ?></td>
<td><?php echo $f7; ?></td>
<td><?php echo $f8; ?></td>
<td><?php echo $f9; ?></td>
</tr>
</tbody>
</table>
<?php$i++;}?>
</div>
You do this:
$num=mysql_numrows($result);mysql_close();?>
^^^^^^^^^^^^^
Before you do this:
<?php$i=0;while ($i < $num)
$f1=mysql_result($result,$i,"id");
^^^^^^^^^^^^^^^^^
Can't fetch anything from your query result, since you killed the connection that the results would be coming from.
And note that the mysql_*() functions are obsolete and deprecated. You should NOT be using them in any new code.
In case u're ok with a fresh start using, here's the code to connect to the DB :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
try
{
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
echo "Connected successfully" . "<br /> \n";
}
catch (PDOException $e)
{
echo "Can't connect to the server !: " . $e->getMessage() . "<br />";
die();
}
try
{
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "";
$stmt = $db->query($sql);
$array_res = $stmt->fetchAll();
}
catch (Exception $e)
{
echo "Failed: " . $e->getMessage();
}
?>
U'll just have to edit ur personnal infos on top & $sql. Then ure free to display it, all explained in the link below
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.