Need Help to Fetch MYSQLi rows to create a table - php

I need a help in a query rows creating a table through php. Here below is the rows in my mysql table named "routine".
Now i want to fetch through week days in a single loop creating a table like below:
Is it possible with a single loop? Here i want to separate the rows through week and auto columns through time.

Yes! It is possible with single loop but we use php array...
Try this...
Data insertion php coding - insert.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$week = "Friday";
$subject = "Physics";
$time = 3;
$sql = "INSERT INTO routine (Week, Subject, Time)VALUES ('".$week."', '".$subject."', '".$time."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Php code for displaying rows through week and auto columns through time - view.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
//Initial Declarations
$data = [];
$data[0][0] = "<tr><td>Week</td>";
$data[0][1] = "<tr><td>Monday</td>";
$data[0][2] = 0;
$data[1][0] = "<tr><td>Week</td>";
$data[1][1] = "<tr><td>Tuesday</td>";
$data[1][2] = 0;
$data[2][0] = "<tr><td>Week</td>";
$data[2][1] = "<tr><td>Wednesday</td>";
$data[2][2] = 0;
$data[3][0] = "<tr><td>Week</td>";
$data[3][1] = "<tr><td>Thursday</td>";
$data[3][2] = 0;
$data[4][0] = "<tr><td>Week</td>";
$data[4][1] = "<tr><td>Friday</td>";
$data[4][2] = 0;
$sql = "SELECT * FROM routine";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) // Table Fields - Week ($row[0]), Subject($row[1]), Time($row[2])
{
if($row[0] == "Monday")
{
$data[0][0] = $data[0][0] . "<td>" . $row[2] . "</td>";
$data[0][1] = $data[0][1] . "<td>" . $row[1] . "</td>";
$data[0][2] = intval($data[0][2]) + 1;
}
else if($row[0] == "Tuesday")
{
$data[1][0] = $data[1][0] . "<td>" . $row[2] . "</td>";
$data[1][1] = $data[1][1] . "<td>" . $row[1] . "</td>";
$data[1][2] = intval($data[1][2]) + 1;
}
else if($row[0] == "Wednesday")
{
$data[2][0] = $data[2][0] . "<td>" . $row[2] . "</td>";
$data[2][1] = $data[2][1] . "<td>" . $row[1] . "</td>";
$data[2][2] = intval($data[2][2]) + 1;
}
else if($row[0] == "Thursday")
{
$data[3][0] = $data[3][0] . "<td>" . $row[2] . "</td>";
$data[3][1] = $data[3][1] . "<td>" . $row[1] . "</td>";
$data[3][2] = intval($data[3][2]) + 1;
}
else if($row[0] == "Friday")
{
$data[4][0] = $data[4][0] . "<td>" . $row[2] . "</td>";
$data[4][1] = $data[4][1] . "<td>" . $row[1] . "</td>";
$data[4][2] = intval($data[4][2]) + 1;
}
}
//Final Assigning
$data[0][0] = $data[0][0] . "</tr>";
$data[0][1] = $data[0][1] . "</tr>";
$data[1][0] = $data[1][0] . "</tr>";
$data[1][1] = $data[1][1] . "</tr>";
$data[2][0] = $data[2][0] . "</tr>";
$data[2][1] = $data[2][1] . "</tr>";
$data[3][0] = $data[3][0] . "</tr>";
$data[3][1] = $data[3][1] . "</tr>";
$data[4][0] = $data[4][0] . "</tr>";
$data[4][1] = $data[4][1] . "</tr>";
// Display Result
if($data[0][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[0][0] . $data[0][1] . "</table><br>";
if($data[1][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[1][0] . $data[1][1] . "</table><br>";
if($data[2][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[2][0] . $data[2][1] . "</table><br>";
if($data[3][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[3][0] . $data[3][1] . "</table><br>";
if($data[4][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[4][0] . $data[4][1] . "</table><br>";
?>

Related

PHP Simple Pagination

the below code is getting some values from DB by "select option form" , i recently added Pagination snip to limit the results, when i run the code it fetch 5 recorders as defined,but didn't show the remaining number of pages.
what im doing wrong here ?
<?php
$per_page = 5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $per_page;
if (!empty($_POST['form_val']) && isset($_POST['form_val'])) {
$_POST['form_val'] = 0;
$sql = "SELECT u.log_id , u.user_name, s.site, u.date ,u.comment , l.location, e.picture FROM `pool` u, `location_all` l , `site_all` s JOIN db2.user e
where l.location_id = u.location and s.site_id = u.site and e.user_id = u.user_id";
if (!empty($_POST['Location']) && isset($_POST['Location'])) {
$sql = $sql . " AND location =" . $_POST['Location'];
}
$strtdate = $_POST['Sday'];
$enddate = $_POST['Eday'];
if (!empty($_POST['Sday']) && isset($_POST['Sday']) && !empty($_POST['Eday']) && isset($_POST['Eday'])) {
$sql = $sql . " AND date between '" . $strtdate . "' and '" . $enddate . "'";
} elseif (!empty($_POST['Sday']) && isset($_POST['Sday'])) {
$sql = $sql . " AND date>='" . $strtdate . "'";
} elseif (!empty($_POST['Eday']) && isset($_POST['Eday']))
$sql = $sql . " AND date<='" . $enddate . "'";
}
if (!empty($_POST['Site']) && isset($_POST['Site'])) {
$sql = $sql . " AND u.site=" . $_POST['Site'];
}
$sql = $sql . " LIMIT $start_from, $per_page";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) >= 1) {
$rowcount = mysqli_num_rows($result);
echo '<legend> ' . $rowcount . ' Records Found !!!</legend>';
echo '<br><br>';
echo "<table class='srchtable'>
<tr>
<th>Picture</th>
<th>Date</th>
<th>User Name</th>
<th>country</th>
<th>Location</th>
<th>Site</th>
<th>Comment</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td> <img src='" . $row['picture'] . "' alt='' style='width:70%; height:auto; border-radius: 50%;'> </td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['site'] . "</td>";
echo "<td>" . $row['comment'] . "</td>";
echo "</tr>";
}
echo "</table>";
$total_pages = ceil($rowcount / $per_page);
echo "<center><a href='?page=1'>" . 'First Page' . "</a> ";
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=" . $i . "'>" . $i . "</a> ";
}
echo "<a href='?page=$total_pages'>" . 'Last Page' . "</a></center> ";
} else {
echo '<p>No Results Found !!!</p>';
}
}
}
?>
As I said in my comments, for displaying pagination links:
You're counting total number of rows but incorporating LIMIT and OFFSET clauses in your SELECT query, this won't give the correct number of row count. Your SELECT query should not contain this part, ... LIMIT $start_from, $per_page.
Since you're filtering the results based on several $_POST data, you should incorporate those conditions in your pagination links as well, otherwise when you visit a different page(through pagination link), you won't get the desired result, and that's because $_POST data will not be retained when you hop from page to page. Better that you change the method of your <form> from POST to GET, because in this way it'd be easier for you to catch and manipulate things when you hop from one page to another using pagination links.
So based on the above points, your code should be like this:
$per_page = 5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $per_page;
if (!empty($_GET['form_val']) && isset($_GET['form_val'])) {
$_GET['form_val'] = 0;
$sql = "SELECT u.log_id , u.user_name, s.site, u.date ,u.comment , l.location, e.picture FROM `pool` u, `location_all` l , `site_all` s JOIN db2.user e
where l.location_id = u.location and s.site_id = u.site and e.user_id = u.user_id";
if (!empty($_GET['Location']) && isset($_GET['Location'])) {
$sql = $sql . " AND location =" . $_GET['Location'];
}
$strtdate = $_GET['Sday'];
$enddate = $_GET['Eday'];
if (!empty($_GET['Sday']) && isset($_GET['Sday']) && !empty($_GET['Eday']) && isset($_GET['Eday'])) {
$sql = $sql . " AND date between '" . $strtdate . "' and '" . $enddate . "'";
} elseif (!empty($_GET['Sday']) && isset($_GET['Sday'])) {
$sql = $sql . " AND date>='" . $strtdate . "'";
} elseif (!empty($_GET['Eday']) && isset($_GET['Eday'])) {
$sql = $sql . " AND date<='" . $enddate . "'";
}
if (!empty($_GET['Site']) && isset($_GET['Site'])) {
$sql = $sql . " AND u.site=" . $_GET['Site'];
}
$data_query = $sql . " LIMIT $start_from, $per_page";
$result = mysqli_query($conn, $data_query);
if (mysqli_num_rows($result) >= 1) {
$rowcount = mysqli_num_rows($result);
echo '<legend> ' . $rowcount . ' Records Found !!!</legend>';
echo '<br><br>';
echo "<table class='srchtable'>
<tr>
<th>Picture</th>
<th>Date</th>
<th>User Name</th>
<th>country</th>
<th>Location</th>
<th>Site</th>
<th>Comment</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td> <img src='" . $row['picture'] . "' alt='' style='width:70%; height:auto; border-radius: 50%;'> </td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['site'] . "</td>";
echo "<td>" . $row['comment'] . "</td>";
echo "</tr>";
}
echo "</table>";
$query_result = mysqli_query($conn, $sql);
$total_rows = mysqli_num_rows($query_result);
$total_pages = ceil($total_rows / $per_page);
parse_str($_SERVER["QUERY_STRING"], $url_array);
unset($url_array['page']);
$url = http_build_query($url_array);
?>
<center>First Page
<?php
for ($i = 1; $i <= $total_pages; $i++) {
?>
<?php echo $i; ?>
<?php
}
?>
Last Page</center>
<?php
} else {
echo '<p>No Results Found !!!</p>';
}
}

How do I hide entire row if a certain cell in that row is empty?

I've been stuck with this for a while now. How do I hide a row if the second columns (svar) cell is empty on all rows where the cells under svar is not filled in?
Here is my code so far:
PHP
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password)or
die("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$result = mysqli_query($connect,"SELECT * FROM question");
echo "<table border='1'>
<tr>
<th>Fråga</th>
<th>Svar</th>
<th>Poäng</th>
<th>Redigera</th>
<th>Radera</th>
<th>AID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['qid'] . "</td>";
echo "<td>" . $row['answer'] . "</td>";
echo "<td>" . $row['Point'] . "</td>";
echo "<td>Redigera</td>";
echo "<td>Ta bort</td>";
echo "<td>" . $row['aid'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
JQuery
var t = $('table').parent().children().find("td:nth-child(2):empty").parent().hide();
I would update the query so you only return the records you want displayed. So change:
$result = mysqli_query($connect,"SELECT * FROM question");
to
$result = mysqli_query($connect,"SELECT * FROM question where answer <> '' && answer IS NOT NULL");
You can try this:
$('td:nth-child(2):empty').closest('tr').hide();
Here is the FIDDLE.

PHP - MySQL to PDO

So I decided to finally move over to PDO instead of using the old mysql_
But I noticed my site is loading slower. It's a table with 500 lines, and with my mysql_ queries it loaded slightly faster (0.5-1 second faster).
I wonder if it's just the way PDO works or if I've made some mistake somewhere. I did not change much from MySQL to PDO.
Here is my original mysql_ code:
<?php
$sql = mysql_query("SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500");
$id = 1;
$last_player_lvl = '';
while($row = mysql_fetch_array($sql)){
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$country = $row['country'];
$lastlogindate = $row['lastlogin'];
$lastlogin2 = utf8_decode($lastlogindate);
$lastlogin = str_replace("?", " ", $lastlogin2);
$onrow = '';
$typeServ = '';
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'activer';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td align='right'>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td align='center'><img src='../img/flags/" . $country . ".gif'></td>";
echo "<td><div class='". $onrow ."'></div></td>";
echo "<td><a href='../char/" . $player_name . "' class='playerlink'>" . $name . "</a></td>";
echo "<td>" . $level . "</td>";
echo "<td><a href='../world/" . $world ."' class='worldlink'>" . $world . "</a></td>";
echo "<td>"; if ($difference == 0){ echo "Today"; } elseif($difference == 1) { echo "Yesterday"; } else { echo $difference; } echo "</td>";
echo "<td>" . $account . "</td>";
echo "</tr>";
// Check if there are duplicate levels, if so, give them the same rank
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
}
echo "</tbody>";
echo "</table>";
?>
and here is my PDO code
<?php
$sql = 'SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500';
$id = 1;
$last_player_lvl = '';
foreach ($db->query($sql) as $row) {
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$country = $row['country'];
$lastlogindate = $row['lastlogin'];
$lastlogin2 = utf8_decode($lastlogindate);
$lastlogin = str_replace("?", " ", $lastlogin2);
$onrow = '';
$typeServ = '';
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'activer';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td align='right'>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td align='center'><img src='../img/flags/" . $country . ".gif'></td>";
echo "<td><div class='". $onrow ."'></div></td>";
echo "<td><a href='../char/" . $player_name . "' class='playerlink'>" . $name . "</a></td>";
echo "<td>" . $level . "</td>";
echo "<td><a href='../world/" . $world ."' class='worldlink'>" . $world . "</a></td>";
echo "<td>"; if ($difference == 0){ echo "Today"; } elseif($difference == 1) { echo "Yesterday"; } else { echo $difference; } echo "</td>";
echo "<td>" . $account . "</td>";
echo "</tr>";
// Check if there are duplicate levels, if so, give them the same rank
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
}
echo "</tbody>";
echo "</table>";
?>
maybe something to improve when it comes to the PDO part?
You are executing the query on every iteration of your foreach loop. See update.
Try replacing
foreach ($db->query($sql) as $row) { ...
with
$result = $db->query($sql);
foreach ($result as $row) {
Update: #mario is right. The foreach does't evaluate the expression on each iteration. I can't seem to find a conclusive answer as to why this would have solved the OPs issue; I still think there is something to it, but even in my own tests it seems that using the variable doesn't seem to have any significant effect on performance. If anyone has any more details to add, please do. :)

MySQL 'fatal error'

I've got an error in my code, I've been googling it and trying to find out what the problem is. As far as I know it's been a problem executing my sql code (around variable $so). Could anyone help me out?
Fatal error: Call to a member function execute() on a non-object in ... on line 15
<?php
$dbhost = "";
$dbuser = "";
$dbpass = "";
$dbname = "";
$con = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$so = $con->prepare("SELECT * FROM besteloverzicht");
$so->execute();
$result = $so->get_result();
echo "<form name='overzicht' method='post'>";
echo "<table align='center' border='2'>
<tr>
<th>Ordernr</th>
<th>Klantnaam</th>
<th>Productnaam</th>
<th>ProductID</th>
<th>Status</th>
<th>Verwijderen</th>
</tr>";
while($row = $result->fetch_assoc()) {
$ordernr = $row['ordernr'];
$klantnaam = $row['klantnaam'];
$productnaam = $row['productnaam'];
$productid = $row['productid'];
$status = $row['status'];
echo "<tr>";
echo "<td width='150px'>" . $ordernr . "</td>";
echo "<td width='150px'>" . $klantnaam . "</td>";
echo "<td width='300px'>" . $productnaam . "</td>";
echo "<td width='100px'>" . $productid . "</td>";
echo "<td width='200px'><select name='status[$ordernr]'>
<option>" . $status . "</option>";
if($row['status'] != "Niet besteld")
echo "<option>Niet besteld</option>";
if($row['status'] != "Besteld")
echo "<option>Besteld</option>";
if($row['status'] != "Onderweg naar hoofdlocatie")
echo "<option>Onderweg naar hoofdlocatie</option>";
if($row['status'] != "Onderweg naar vestiging")
echo "<option>Onderweg naar vestiging</option>";
if($row['status'] != "Ontvangen")
echo "<option>Ontvangen</option>";
echo "</select></td>";
echo "<td align='center' width='50px'><input name='checkbox[]' id='checkbox[]' type='checkbox' value='$ordernr'></td>";
echo "</tr>";
}
echo "<tr>";
echo "<td></td><td></td><td></td><td></td>";
echo "<td><input type='submit' name='wijzigen' value='Wijzigingen Opslaan'/></td>";
echo "<td><input type='submit' name='verwijderen' value='Verwijderen'/></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
$statuses = $_POST['status'];
$delete = $_POST['delete'];
$del_id = $_POST['checkbox'];
if (isset($_POST['wijzigen'])) {
foreach($statuses as $ordernr => $status)
{
if($status != "")
$dbupdate = "UPDATE overzicht SET status='$status' WHERE ordernr='$ordernr'";
$query = mysqli_query($con,$dbupdate);
header("refresh: 0;");
}
}
if (isset($_POST['verwijderen'])) {
foreach($del_id as $value){
$dbdelete = "DELETE FROM overzicht WHERE ordernr='".$value."'";
$query = mysqli_query($con,$dbdelete);
}
header("refresh: 0;");
}
mysqli_close($con);
?>
Maybe the table besteloverzicht doesn't exist?
Please replace
$so = $con->prepare("SELECT * FROM besteloverzicht");
with
$so = $con->prepare("SELECT * FROM besteloverzicht") OR die(mysqli_error());
That should give you a better idea of what's going wrong.
Wrap your prepare statement to produce an error in case it fails
if (!($so = $con->prepare("SELECT * FROM besteloverzicht"))) {
echo "Prepare failed: (" . $con->errno . ") " . $con->error;
}
This may give you a better insight
You can use mysqli_prepare($con, 'SELECT * FROM besteloverzicht');

printing [mysql_query] result in a table

I want to print mysql_query result in a table. I know how to do it but I am just confused. I tried this.
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$i = 1;
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($i<=2 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=4 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=6 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=8 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
echo "</tr></table>";
}
?>
As you can see it is written again and again with a slight change of 2,4,6,8 in the while loop. It works but the problem is I cant rewrite it again and again as when the website will go live it will have more than 1000 entries. Could You guys help me out by suggesting another way to do this?
""** I need it to be like these dots (dots represent records in the database) **"""
. . . .
. . . .
. . . .
THANKS in Advance.
Ramzy
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
echo "</tr></table>";
}
?>
while($row = mysql_fetch_array($sql)) {
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
I don't really see what's the problem here.
By the way you should never call you're array like this $row[id] but you should quote the key instead $row['id']; Because if a constant id exists it will screw up your code and also for performance reason.
Just use
$limit = 1000;//place any value you need here to limit the number of rows displayed
while ($i<=$limit && $row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
++$i;
}
Also, that limit is unnecessary if all you want is to flush every record to the output. You could just do
while ($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
And it will stop as soon as there are no more records.
To print all database rows into an HTML-table, use:
echo '<table>';
$i = 0; // $i is just for numbering the output, not really useful
while($row = mysql_fetch_array($sql))
{
echo '<tr><td>' . $i . ' - ' . $row['id'] . ' : ' . $row['name'] . '</td></tr>';
$i++;
}
echo '</tr></table>';
here is a general function I use:
function query_result_to_html_table($res, $table_id = NULL, $table_class = NULL, $display_null = true)
{
$table = array();
while ($tmp = mysql_fetch_assoc($res))
array_push($table, $tmp);
if (!count($table))
return false;
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" "
. ($table_id ? "id=\"$table_id\" " : "")
. ($table_class ? "class=\"$table_class\" " : "") . ">";
echo "<tr>";
foreach (array_keys($table[0]) as $field_name) {
echo "<th>$field_name";
}
foreach ($table as $row) {
echo "<tr>";
foreach ($row as $col => $value) {
echo "<td>";
if ($value === NULL)
echo "NULL";
else
echo $value;
}
echo "\n";
}
echo "</table>\n";
return true;
}
I Got The Answer.. I wanted it to be like this. I made this and It Actually Works.
<?php
$i = 1;
mysql_connect("localhost" , "root" , "") or die('Could not Connect.');
mysql_select_db("db") or die('Could not select DB.');
$query = "select * from `check`";
$sql = mysql_query($query) or die(mysql_error());
echo "<table border='5' width='50%'><tr><th>Name</th><th>Gender</th></tr></table><table border='5' width='50%'><tr>";
if($i<3){
echo "<td align='center'>".$row['name']."</td>";
echo "<td align='center'>".$row['gender']."</td>";
++$i;
} else {
echo "<td align='center'>".$row['name']."</td><td align='center'>".$row['gender']."</td>";
echo "</tr>";
$i = 1;
echo "<tr>";
}
}
echo "</table>";
?>
</div>
Thank You Guys For Your Support

Categories