i only get one result using this code - php

add new product<br>
<br>
<?php
include("mysql.php");
$result = mysql_query("SELECT * FROM gallery ");
$just = mysql_fetch_array($result);
$num=mysql_num_rows($result);
$table="";
$table.="<td>delete</td>";
$table.="<td>update</td>";
if ($num > 0 ) {
$i=0;
while($just = mysql_fetch_array($result))
{
$num=mysql_num_rows($result);
{
$table .= "<tr>";
$table .= "<td>".$just['title']."</td>";
$table .= "<td>".$just['title']."</td>";
}
$table .= "</tr>";
while ($i < $num) {
$name = stripslashes(mysql_result($result,$i,"name"));
$title = stripslashes(mysql_result($result,$i,"title"));
$description = stripslashes(mysql_result($result,$i,"description"));
++$i; }
}
}
else { $table = '<tr><td colspan="2" align="center">Nothing found</td></tr>'; }
?>
<table border="1" cellpadding="1" cellspacing="2"><? echo $table ?></table>
good morning , in the above code iam trying to create a table of 2 columns delete and update , being able to manage mysql through this page , but i get only 1 row from mysql table although i expect 4 (4 rows are saved in mysql table)
what's the wrong here , thanks in advance

add new product<br>
<br>
<?php
include("mysql.php");
$result = mysql_query("SELECT * FROM `gallery`");
$num = mysql_num_rows($result);
$table = "";
$table .= "<td>delete</td>";
$table.="<td>update</td>";
if ($num > 0 ) {
$i=0;
while($just = mysql_fetch_assoc($result)) {
$num=mysql_num_rows($result);
$table .= "<tr>";
$table .= "<td>".$just['title']."</td>";
$table .= "<td>".$just['title']."</td>";
}
$table .= "</tr>";
while ($i < $num) {
$name = stripslashes(mysql_result($result,$i,"name"));
$title = stripslashes(mysql_result($result,$i,"title"));
$description = stripslashes(mysql_result($result,$i,"description"));
++$i;
}
} else {
$table = '<tr><td colspan="2" align="center">Nothing found</td></tr>';
}
?>
<table border="1" cellpadding="1" cellspacing="2"><? echo $table ?></table>

Your fetching the result and counting the rows in the wrong places, and you have a sub while loop that basically does nothing.
Here Try this:
<?php
include("mysql.php");
$result = mysql_query("SELECT `id`,`name`,`title`,`description` FROM gallery");
$table=null;
if (mysql_num_rows($result) > 0 ) {
while($just = mysql_fetch_assoc($result)){
$table .= "<tr>".PHP_EOL;
$table .= "<td>".$just['title']."</td>".PHP_EOL;
$table .= "<td>".$just['title']."</td>".PHP_EOL;
$table .= "</tr>".PHP_EOL;
}
}else{
$table = '<tr><td colspan="2" align="center">Nothing found</td></tr>';
}
?>
<table border="1" cellpadding="1" cellspacing="2"><? echo $table; ?></table>

Good approach but it really require a better implementation.
First, get yourself a function and put it in mysql.php for the frequent use.
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
then write a code to get the data
<?php
include("mysql.php");
$data = sqlArr("SELECT * FROM tbl_names");
foreach ($data as $k => $value) $data[$k] = htmlspecialchars($value);
include 'template.php';
then write a template to make your approach with HTML template complete:
<table border="1" cellpadding="1" cellspacing="2">
<? if (!$data)): ?>
<tr>
<td colspan="2" align="center">Nothing found</td>
</tr>
<? else: ?>
<? foreach($data as $just): ?>
<tr>
<td><?=$just['title']?></td>
</tr>
<? endforeach ?>
<? endif ?>
</table>
Look: your code become 2 times shorter yet WAY more readable!
Note that you shouldn't pass whole data to the editing scripts. Only id is enough and required! Fetch the data to edit from the DB in the update script.
Also note that you shouldn't use GET method to delete records - only post. So, let me suggest you to have a "Delete" button not in the table but in the update form.

Related

PHP HTML Table showing as blank [duplicate]

This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
Closed 7 years ago.
I've been working on a project that prints sql data into a table. Recently, I've come into a problem with the table. What this code should do is output a table of results from a MySQL query but all it's outputting is something like:
Item1 Item1
For some reason it leaves all the other fields blank. Here's my code:
$table = "<table class='TestTable'><tr class='tr'>";
while($row = mysql_fetch_assoc($result)){
$table .= "<th class='th'>";
$table .= $row['NameOfItem'];
$table .= "</th>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "
<td class='td'>Minimum Bid: <b>";
$table .= $row['MinBid'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Current Bid: <b>";
$table .= $row['CurrentBid'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Sold By: <b>";
$table .= $row['SoldBy'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Time Left: <b>";
$table .= printf('%d days, %d hours, %d minutes left', $diff->d, $diff->h, $diff->i);
$table .= "</b></td>";
}
$table .= "</tr></table>";
echo $table;
When I view source I get:
<table class='TestTable'>
<tr class='tr'>
<th class='th'>Item1</th>
<th class='th'>Item1</th>
</tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
</table>
After while($row = mysql_fetch_assoc($result)) {...} you have reached the end of your result set. You have to rewind the result pointer to the beginning of the result set if you want to read it again. Do this by using
while($row = mysql_fetch_assoc($result)){ ... }
mysql_data_seek($result, 0); // Rewind result pointer
while($row = mysql_fetch_assoc($result)){ ... }
mysql_data_seek($result, 0); // Rewind result pointer
while($row = mysql_fetch_assoc($result)){ ... }
First get your results and safe them in an array:
while($r = mysql_fetch_assoc($result)){
$row[] = $r;
}
Then reuse the array as often as needed to build the table like this:
$table .= "</tr><tr class='tr'>";
foreach ($row as $r){
$table .= "
<td class='td'>Minimum Bid: <b>";
$table .= $r['MinBid'];
$table .= "</b></td>";
}
... and yes, mysql-functions are deprecated. When you move to PHP7 they'll be gone. Use PDO or mysqli instead.

Display SQLITE output in column rather than row

At the moment I have the below script which auto generates the table names and row data automatically by looking at a sqlite table. So regardless of if you have 2 or 10 columns this script works.
At the moment the script outputs the results like this:
Output currently appears as a Row
I have tried altering the script so that it outputs the results like below. Can someone assist or guide me in the right direction to achieve this?
Is it possible to output the results of the query in the below format: going down in a column rather than across as a row ?
Output should appear as a Column
<?
$ED = $_GET['ED'];
$ID = $_GET['ID'];
$table_name = $_GET['table'];
?>
<table border="1">
<tr>
<td>
<table>
<?php // Display all sqlite column names for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
if ($table['name'] == "ID") {
echo "<tr><td>" . $table['name'] . "</td></tr>";
} else {
$table_name_header = ucwords(strtolower(str_replace('_', ' ', $table['name'])));
echo "<tr><td>" . $table_name_header . "</td></tr>";
}
}
?>
</table>
</td>
<td>
<table>
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
</table>
</td>
</tr>
</table>
Modifying the code to the below by putting the data into an combined array and then pulling it back via a loop it will display as required:
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
$column_data[] = $row[$col];
// echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
<?
$array = $columns;
$array2 = $column_data;
$result = array_combine($array, $array2);
//print_r($result);
?><br><br>
<center>
<table border="0" cellpadding="2" cellspacing="2" color="#4B708D">
<thead>
<?
foreach($result as $key => $value) {
echo "<tr><td bgcolor='#c6d5e1'>$key</td><td bgcolor='#FFFFFF'>$value</td></tr>";
}
?>
</thead>
</table>

Create HTML table from sql table

I have a table in a SQL database with the following fields: ID, Name, Email, University, Languages, and Experience. I want to create an html table that fetches data from SQL and outputs the last 10 results? How would I do that?
I'm sorry if this is a very simple question, I have very little knowledge in PHP and SQL.
Here's the code I have right now that just displays the name and not in a table:
<html>
<head>
<title>Last 5 Results</title>
</head>
<body>
<?php
$connect = mysql_connect("localhost","root", "root");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("apploymentdevs");
$results = mysql_query("SELECT * FROM demo");
while($row = mysql_fetch_array($results)) {
echo $row['Name'] . "</br>";
?>
</body>
</html>
Here is something that should help you to create the table and get more knowledge of php and mysql.
Also you should move your connection logic and query to the beginning of your process, thus avoiding errors while loading the page and showing a more accurate error than just the mysql_error.
Edit: If your ids are incrementing, then you could add the ORDER BY clause,
change: SELECT * FROM demo LIMIT 10
to: SELECT * FROM demo LIMIT 10 ORDER BY id
<html>
<head>
<title>Last 10 Results</title>
</head>
<body>
<table>
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
$connect = mysql_connect("localhost","root", "root");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("apploymentdevs");
$results = mysql_query("SELECT * FROM demo LIMIT 10");
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td><?php echo $row['Id']?></td>
<td><?php echo $row['Name']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
I got very annoyed pasting together the same code over and over again to build HTML tables from SQL queries.
So, here we go with a function that takes mysqli results and pastes them together to an plain simple HTML table that has column names according to those in the database:
function sql_to_html_table($sqlresult, $delim="\n") {
// starting table
$htmltable = "<table>" . $delim ;
$counter = 0 ;
// putting in lines
while( $row = $sqlresult->fetch_assoc() ){
if ( $counter===0 ) {
// table header
$htmltable .= "<tr>" . $delim;
foreach ($row as $key => $value ) {
$htmltable .= "<th>" . $key . "</th>" . $delim ;
}
$htmltable .= "</tr>" . $delim ;
$counter = 22;
}
// table body
$htmltable .= "<tr>" . $delim ;
foreach ($row as $key => $value ) {
$htmltable .= "<td>" . $value . "</td>" . $delim ;
}
$htmltable .= "</tr>" . $delim ;
}
// closing table
$htmltable .= "</table>" . $delim ;
// return
return( $htmltable ) ;
}
Example Usage:
$DB = new mysqli("host", "username", "password", "database");
$sqlresult = $DB->query( "SELECT * FROM testtable LIMIT 1 ;" ) ;
echo sql_to_html_table( $sqlresult, $delim="\n" ) ;
Calling table( $result ); on your query results will generate a html based table regardless of the size of the sql array you feed it. I hope this helps :)
<?php
function table( $result ) {
$result->fetch_array( MYSQLI_ASSOC );
echo '<table>';
tableHead( $result );
tableBody( $result );
echo '</table>';
}
function tableHead( $result ) {
echo '<thead>';
foreach ( $result as $x ) {
echo '<tr>';
foreach ( $x as $k => $y ) {
echo '<th>' . ucfirst( $k ) . '</th>';
}
echo '</tr>';
break;
}
echo '</thead>';
}
function tableBody( $result ) {
echo '<tbody>';
foreach ( $result as $x ) {
echo '<tr>';
foreach ( $x as $y ) {
echo '<td>' . $y . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
}
You might be interested in fetching with mysql_fetch_assoc() (so that you get the data in an associative array : keys=>value). In the keys are your column names ; so, for each line, you can loop through each column (with array_keys()) and print its value.
$results = mysql_query("SELECT * FROM demo");
while($row = mysql_fetch_assoc($results)) {
foreach (array_keys($row) as $column) {
echo $row[$key] . "</br>";
}
}
(After that, you can cache array_keys($row) in a variable which is only set once, because its value won't change while you run through the results.)
Even though it's been a while I'm going to put my 2 cents in: use functions (even better - classes). Creating tables from mysql results is a very common task.
<!DOCTYPE html>
<html>
<head><title>Create Tables from MySQL using functions</title></head>
<body>
<?php
db_connect();
// assuming you have an auto increment id as the first column
$result = mysql_query("SELECT * FROM demo ORDER BY 1 DESC LIMIT 10");
print createTable(array_result($result));
?>
</body>
</html>
<?php
/**
* Quick mysql result function
*
* #param $result
* #return array
*/
function array_result($result)
{
$args = array();
while ($row = mysql_fetch_assoc($result)) {
$args[] = $row;
}
return $args;
}
/**
* Connect to db
*
* #param string $db_host
* #param string $db
*/
function db_connect($db_host = "localhost", $db = "apploymentdevs")
{
$connect = mysql_connect($db_host,"root", "root");
if (!$connect) {
die(mysql_error());
}
mysql_select_db($db);
}
/**
* Create a table from a result set
*
* #param array $results
* #return string
*/
function createTable(array $results = array())
{
if (empty($results)) {
return '<table><tr><td>Empty Result Set</td></tr></table>';
}
// dynamically create the header information from the keys
// of the result array from mysql
$table = '<table>';
$keys = array_keys(reset($results));
$table.='<thead><tr>';
foreach ($keys as $key) {
$table.='<th>'.$key.'</th>';
}
$table.='</tr></thead>';
// populate the main table body
$table.='<tbody>';
foreach ($results as $result) {
$table.='<tr>';
foreach ($result as $val) {
$table.='<td>'.$val.'</td>';
}
$table.='</tr>';
}
$table.='</tbody></table>';
return $table;
}
I hope you know how to make a table in HTML, with <table>, <tr> and <td>.
Fix a table with that in your while-loop and use "SELECT * FROM demo LIMIT 10" as SQL-query.

How to print a table in php with a specific format for rows and columns?

I have this table
And my goals is to have a table looking like this
The table has 8 rows and 3 columns
I have already stored the questions but I'm having a hard time printing it in this format.
Wherein after printing 4 questions it will then go to another cell and print 4 questions again and then once there are already 3 columns it will then create a new row and do the same step again.( 8 rows and 3 columns)
The questions are ordered by sequence no. [In the table below the 1st 4 questions are 1,2,3,4 and then the cell on it's right are 6,7,8,9 and so on....]
I'm stuck with this for almost 8 hours already....
Here's my current code:
select = "SELECT q.QuestionID, q.QuestionText, q.m, q.l, q.GroupNo, q.SequenceNo FROM question2 q Order By q.SequenceNo";
$result = mysql_query($select);
$question_id = "";
$question_text = "";
$question_m = "";
$question_l = "";
$question_group = "";
//$table = "<table border='1' cellspacing='1'>";
$count_row = 0;
$array = array();
//$count_column = 0;
while($row = mysql_fetch_array($result))
{
$question_id = $row['QuestionID'];
$question_text = $row['QuestionText'];
$question_m = $row['m'];
$question_l = $row['l'];
$question_group = $row['GroupNo'];
$question_sequence = $row['SequenceNo'];
if($count_row > 2)
{
$array[] .= "</div>";
}
$array[] .= "<div style='border=1px';'>";
$array[] .= $question_text ."<br/>";
$count_row++;
}
$table .= "</table>";
echo $table;
Sir/Ma'am your answers would be of great help. Thank you++
I am not sure I fully understand the question but you could try this. I believe it will give you the output you want.
$row_count = 0;
echo "<table border=1>";
while($row = mysql_fetch_array($result)) {
if($row_count%12 == 0) {
echo "<tr>";
}
if($row_count%4 == 0) {
echo "<td>";
}
echo $row['QuestionText']."<br>";
if($row_count%4 == 3) {
echo "</td>";
}
if($row_count%12 == 11) {
echo "</tr>";
}
$row_count++;
}
echo "</table>";
It should give you an output that looks like this:
<table border=1>
<tr>
<td>0<br>1<br>2<br>3<br></td>
<td>4<br>5<br>6<br>7<br></td>
<td>8<br>9<br>10<br>11<br></td>
</tr>
<tr>
<td>12<br>13<br>14<br>15<br></td>
<td>16<br>17<br>18<br>19<br></td>
<td>20<br>21<br>22<br>23<br></td>
</tr>
<tr>
<td>24<br>25<br>26<br>27<br></td>
<td>28<br>29<br>30<br>31<br></td>
<td>32<br>33<br>34<br>35<br></td>
</tr>
...
</table>
$querstions = array();
$query = "SELECT QuestionID, QuestionText, m, l, GroupNo, SequenceNo FROM question2 ORDER BY SequenceNo";
$resource = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$querstions[$row['QuestionID']] = $row;
}
/* print table head */
echo "<table><thead>....
/* split up question in master_rows with 12 question each */
foreach(array_chunk($querstions, 12) as $master_row)
{
echo ...
foreach(range(0, 3) as $row_nr)
{
echo ... $master_row[$row_nr] ...;
echo ... $master_row[$row_nr + 4] ...;
echo ... $master_row[$row_nr + 8] ...;
}
echo ...
}

Know if the record has been displayed 3 records and if so then put the another 3 records in a new line

Ok I have this code:
<?
$name=$_POST['name'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
$ss = ""
while($row = mysql_fetch_array($result))
{
$ss .= "<div style='border:1px solid red; float:left; width:100px;'><img src="Images/media'.$row['name'].'" />";
$ss .= "<p>".$row['title']."</p>";
$ss .= "<p>".$row['description']."</p>";
$ss .= "<a href='".$row['link']."'>".$row['link']."</a></div>";
}
mysql_close($con);
?>
<? echo $ss; ?>
Now, I want to organize the display, therefore, I want the record to be set by 3 but the only problem where im stuck is I dont know how to make it to display in by set of 3. Im open for a suggestion, please help me. Thank you.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
mysql_connect("localhost","root","");
mysql_select_db("juliver");
$name = mysql_real_escape_string($_POST['name']);
$data = sqlArr("SELECT * FROM items WHERE id='$name'");
$data = array_chunk($data,3);
include 'template.tpl.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $cell): ?>
<td><?=$cell['id']?><?=$cell['title']?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
In while loop you can put the condition to know when it executes 3 times then it would go automatically on other line. have a look
int $a=0;
while($row = mysql_fetch_array($result))
{
if($a%3==0){
this will executes only if when the no of record dividable by 3. means 3,6,9,12..
do this..
}else {
do this..
}
$a++;
}

Categories