This question already has answers here:
Display query result in a table
(5 answers)
Closed 5 years ago.
I have a problem for setting field in htlm5 with results query.
{
$query = "SELECT nome,cognome FROM utente";
$result = $mysqli->query($query);
while($rows = $result->fetch_all(MYSQLI_ASSOC)){
print_r($rows);
};
}
How can I take this result in this structure?
<tr>
<td>??? field 1</td>
<td>??? field 2</td>
</tr>
Well, $rows is just an array that contains the fields you request in your query, so you can access its fields by using the index.
<?php
$rows = mysqli_query($conn,$query);
mysqli_fetch_all($rows,MYSQLI_ASSOC);
$html_string = "<table> <thead>....whatever optional... </thead> <tbody>";
foreach( $rows as $r){
$html_string .= "<tr> <td>" . $r[0] . "</td><td>" . $r[1] . "</td></tr>";
}
$html_string .= "</tbody></table>";
echo $html_string;
?>
Should be enough for the rows of your table.
Related
I'm creating a webpage that lists ten characters in a game based on their experience levels and displays them with a picture associated each character. My code works, but the output is in a column when I'd like it to be in a row. I did see where something very similar had been asked here: MySQL data from database align horizontally and I tried to follow that example but either ended up with errors or the faces didn't appear. I'm a hobbyist, I'm just doing this for friends, so my knowledge is pretty basic.
Relevant code:
<table border="3" width="90%">
<tr>
<th width="25%">XP</th>
<td>
<?php
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<left>";
echo "<table border='1'>";
echo "<tr><td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td></tr>";
echo "</table>";
echo "<br>";
}
?>
</td>
</tr>
</table>
Anyone got any suggestions? Thanks!
So after following Bombelman's suggestion below, I got it to work. In case anyone else runs into this problem, here is the working code:
<tr>
<th width="25%">Goody Two Shoes</th>
<td><?php
echo "<table border='1'><tr>";
echo "<left>";
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
?></td>
</tr>
place the "table" and "row" tag out of the loop, and have the results in between the "td" tags looped only.
Looking at your script, you have several tables.
Make sure only the < td > and < /td > tags are within the while-loop.
The output should be similar to my example.
Hope it helps !
<table style="width:100%">
<tr>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
<td>Character 4</td>
<td>Character 5</td>
</tr>
</table>
Looking at the sql queries makes me think you ought to be able to do a basic join upon the two tables rather than having nested queries within a loop. The generation of the html table should be fairly straightforward - iterate through the recordset results for rows in the table and iterate through the fields returned by the query for individual cells within the table row.
$sql='select l.*, d.face from `life` l
join `description` d on d.`charname`=l.`charname`
where l.`goodxp` > 0
order by l.`goodxp` desc
limit 10';
$res=$con->query( $sql );
/* fetch the column names into an array */
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
$html=array();
$html[]='<table>';
/* add field names as column headers */
$html[]='<tr>';
foreach( $fields as $field )$html[]='<th>'.$field.'</th>';
$html[]='</tr>';
/*
iterate through recordset,
add new row for every record
but table cell for every
field in record
*/
while( $rs=$res->fetch_object() ){
$html[]='<tr>';
foreach( $fields as $field ){/* show image or text */
$data = $field=='face' ? "<img src='pictures/{$rs->$field}' />" : $rs->$field;
$html[]='<td>'.$data.'</td>';
}
$html[]='</tr>';
}
$html[]='</table>';
/* render table */
echo implode( PHP_EOL, $html );
Depending upon the version of PHP you may get nagged at when using the array_walk function and passing the third argument by reference. If that is the case then change
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
for
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key ){
global $fields;
$fields[]=$item->name;
} );
I have a system which looks through a database, creates a table of a specified size and then fills the cells with either full or empty depending if there is data in the database for that specific location.
At the moment it works by doing a SQL query for each cell and then populating, but I have 30,000+ records in the database and even with a LIMIT 1 it's still taking about 5 second to load the table.
I'm wondering if dumping the entire contents into a PHP array and then querying that way would be better, but can't work out the best way to sort it, any tips welcome.
Current (working) code:
echo <<<EOD
<table class="racktable"><tr>
<td colspan ="$colspan">Rack Details </td>
</tr>
<tr>
<td colspan ="$colspan"><center>Edit Rack / Empty Rack / Delete Rack</center> </td>
</tr>
EOD;
//Loop through rows, creating a <tr> for each in the table
for ($row1 = 1; $row1 <= $rows; $row1++) {
echo <<<EOD
<tr><td><a name="$row1"></a>$row1</td>
EOD;
//Loop through columns creating <td> within <tr>
for ($col1 = 1; $col1 <= $columns; $col1++) {
$sql2 = "SELECT ID, sample, rack, srow, col, location FROM samples WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack' LIMIT 1";
if (!$result2 = $db->query($sql2)) {
die('There was an error running the query [' . $db->error . ']');
}
$row3 = $result2->num_rows;
//If location is empty, colout green
if ($row3 == 0) {
echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";
}
else {
//Location is not empty, colour red and link to sample
while ($row2 = $result2->fetch_assoc()) {
$columns1 = $row2['col'];
$ID = $row2['ID'];
$tooltip = $row2['sample'];
$queryStr = $_SERVER['QUERY_STRING'];
$spath = $_SERVER['PHP_SELF'] . "?" . $queryStr . "&sample=" . $ID;
echo <<<EOD
<td style="background-color: #FF0000" title="$tooltip">$col1 <img src="icon.png" style="border: 0" alt=""></td>
EOD;
}
}
}
echo "</tr>";
}
echo "</table>";
You can convert all data from DB directly into a php array with this code:
while(($PHPToPHP[] = mysql_fetch_assoc($SqlResult )) || array_pop($dataToPHP));
may be work for your code:
while(($dataToPHP[] = $result2->fetch_assoc()) || array_pop($dataToPHP))
And to see what it does use print_r($dataToPHP).
To manage the errors die('There was an error running the query [' . $db->error . ']'); and if ($row3 == 0) { echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";} to colorize, you need to make some tests to correctly manage.
You need an array with index like your where
SELECT ID, sample, rack, srow, col, location
FROM samples
WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack'
LIMIT 1";
Your array looks like:
$samples = array(
"$row1:$col1:$location:$rack" => array( 'id' => $id, 'sample' => $sample
)
Or you can use some hash array like:
$samples = array(
md5( "$row1:$col1:$location:$rack" ) => array( 'id' => $id, 'sample' => $sample
)
Insert all values once - than get it like
$val = $samples["$row1:$col1:$location:$rack"];
// or from hash array
$val = $samples[md5( "$row1:$col1:$location:$rack" )];
I am using the below code to make a HTML table. I searched online for PHP get column headings but couldn't find any information (only information on rows). Is it possible to use a while loop and print the column headings from the SQL instead of having them hardcoded as below?
Code
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT orders.order_no, orders.porder_no, orders.date, order_totals.value
FROM orders, order_totals
WHERE orders.order_no = order_totals.order_no
AND orders.account_no = '" . $_SESSION['session_account'] . "'
ORDER BY orders.order_no DESC
)
WHERE ROWNUM <= 15
");
oci_execute($stid);
echo "<table class='table'>
<thread>
<tr>
<th>Order No</th>
<th>Purchase Order No</th>
<th>Date</th>
<th>Value</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td>' . $row[0] . '</td>';
for ( $ii = 1; $ii < count($row); $ii++ ) {
echo "<td>" . $row[$ii] . "</td>";
}
echo "</tr>";
}
echo "</tbody> </table>";
Use this code this may help you, use oci_field_name() to get the column name
echo "<table class='table'>
<thread>
<tr>";
$ncols = oci_num_fields($stid);// to get column number
for ($i = 1; $i <= $ncols; $i++) {// index start from 1
$column_name = oci_field_name($stid, $i);
echo "<th>".$column_name."</th>";
}
echo "</tr>
</thread>
<tbody>";
You are looking for column name property that is already made available by PHP MySQL or MySQLI or PDO APIs.
Here is an example - http://www.php.net/manual/en/function.mysql-field-name.php
Good luck.
This question already has answers here:
PDO returning incorrect, but duplicate, data. Key's not in database.
(3 answers)
Closed 3 years ago.
The code below is producing duplicate <td> elements for each field. I am trying to produce a simple HTML table based on the results of a PDO query. Can anyone tell me why each field is being duplicated?
$data = $conn->query('SELECT * FROM students');
// Print results in a HTML table
echo '<table border="1" cellpadding="5">';
foreach($data as $row) {
echo '<tr>';
foreach ($row as $field) {
echo '<td>' . $field . '</td>';
}
echo '</tr>';
}
echo '</table>';
Thanks
It looks like you are using the PDO::FETCH_BOTH style.
This will produce an array where the entries are duplicated, once for the column name keys, and once for the integer keys.
See the following for details:
http://php.net/manual/en/pdostatement.fetch.php
$data = $conn->query('SELECT * FROM students');
echo "<table border="1" cellpadding="5">
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<td>".$info[column1] . "</td> ";
Print "<td>".$info[column2] . " </td></tr>";
}
echo "</table>
I want to show the query results of mysql query in a table,
There are two tables, and some information has to be retrieved from the second table
I want to retrieve title, borrower name and borrower surname from other tables,
I tried to retrieve title, but I was unsuccessful,
Then I want to retrieve the borrower name and borrower surname from the users table
You may also offer a new way to put the results into a table
Here is the code
for($i=0;$i<999999999;$i++){
$sql="SELECT * FROM products WHERE product_id='$i' LIMIT 1";
//echo $sql;
$moviename="SELECT dbid FROM products WHERE product_id='$i'";
$dbid=mysql_query($moviename);
$movname="SELECT title FROM titles WHERE dbid='$dbid' ";
$name=mysql_query($movname);
$title=mysql_fetch_array($name);
print "<table border=1>
<tr><th>Product_ID</th>
<th>dbid</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th></tr>";
$result=mysql_query($sql);
if($result==NULL){
continue ;
}
while ($row = mysql_fetch_array($result))
{
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td>
<td>{$title[0]}</td>
<td>{$row[12]}</td>
<td>{$row[13]}</td>
<td>{$row[14]}</td>
<td>{$borrowername[0]}</td>
<td>{$borrowesurname[0]}</td></tr>";
}
print "</table>";
}
?>
There are a few things going on here which you should definitely not be doing.
Super insane loop with a query inside
for($i=0;$i<999999999;$i++){
// SELECT STATEMENT HERE!
}
Why are you looping potentially 999,999,999 times? And if you do you are going to hit your database 999,999,999 times? That is going to kill your database and it can be done much more efficiently.
Use joins over individual selects
$sql="SELECT * FROM products WHERE product_id='$i' LIMIT 1";
$moviename="SELECT dbid FROM products WHERE product_id='$i'";
$movname="SELECT title FROM titles WHERE dbid='$dbid' ";
Note:
product_id='$i' LIMIT 1
Usually you want your ids to be unique. Why do you need to LIMIT your query?
The query can be simplified to:
select
*
from
products p
left outer join titles t
on p.dbid = t.dbid
Note: SELECTING * IS BAD PRACTICE, BUT I DON'T KNOW WHAT YOUR STRUCT IS
Illogical logic
if($result==NULL){
continue ;
}
while ($row = mysql_fetch_array($result)) {...}
$result is null at this point, so your while loop will never happen.
So after killing that loop, simplifying the query, and revising logic... we can do:
$result_resource = mysql_query($sql);
echo"
<table border=1>
<tr>
<th>Product_ID</th>
<th>dbid</th>
<th> Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th>
</tr>";
while ($row = mysql_fetch_array($result_resource))
{
echo "
<tr>
<td>{$row['ProductID']}</td>
<td>{$row['dbid']}</td>
<td>{$row['Title']}</td>
<td>{$row['Status']}</td>
<td>{$row['Date']}</td>
<td>{$row['Borrowe_id']}</td>
<td>{$borrowername[0]}</td>
<td>{$borrowesurname[0]}</td>
</tr>";
}
echo "</table>";
Looking at $borrower.... I have a feeling you can also join your borrow table to the query to bring that in too.
I would also look into templating. It would definitely separate your data from your display and make your code a lot easier to read.
First,you should debug your code
one thing that pops up is the following error:
you should change the following from:
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td> ..."
to:
print "<tr><td>{" . $row[1] . "}</td>
<td>{" . $row[2] . "}</td> ..."
Second, when you say " I was unsuccessful" - please add details, did you get an error ? what was the output ?
(Maybe your question is "too localize")
First I don't recommend this :
for($i=0;$i<999999999;$i++)
because it will take long for the server to compute, and generate a lot of mysql query.
Second, most (all?) of your mysql queries could be merge in only one query.
You can about query on more then one table here (dev.mysql.com) There's several way to join multiples tables, you could read about it
Third, in your code the table header will be repeated each time, because it's in your For loop.
here my suggest to improve your code :
//Print the header
print "<table border=1>
<tr><th>Product_ID</th>
<th>dbid</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th></tr>";
//adapt the following sql with your tables name / fields
$sql="SELECT products.product_id, products.dbid, title.tiles, product.status, product.date, borrow.id , borrow.name, borrow.surname FROM products,titles,borrow WHERE product.dbid = titles.dbid && borrow.id = product.prodict_id LIMIT 1";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td>
<td>{$row[3]}</td>
<td>{$row[4]}</td>
<td>{$row[5]}</td>
<td>{$row[6]}</td>
<td>{$row[7]}</td>
<td>{$row[8]}</td></tr>";
}
print "</table>";
?>
I know that the sql query isn't the best one, but I think those suggestions could help you.
Here is a function for you to convert any MySQL select statement to a HTML table with table headings.
function createTable_from_sql_select_query($query) {
$sql_link = Connect_MySQLi_DB(); // Your Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
// Adding Missing Array Column Function for Old PHP Versions (<5.5)
if (!function_exists('array_column')) {
function array_column($array, $column) {
$ret = array();
foreach ($array as $row)
$ret[] = $row[$column];
return $ret;
}
}
$headings = json_decode(json_encode($result->fetch_fields()), true);
$headings = array_column($headings, 'name');
$return = '<table>';
$return .= '<thead><tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<th>' . ucwords(str_replace('_', ' ', (strtolower($headings[$x])))) . '</th>';
}
$return .= '</tr></thead><tbody>';
while ($row = $result->fetch_object()) {
$return .= '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<td>' . $row->$headings[$x] . '</td>';
}
$return .= '</tr>';
}
$return .= '</tbody></table>';
return $return;
}