for ($q = 1 ; $q < 7 ; $q++ )
{
echo $q ; echo $row;
}
now this code works fine but i want to echo 2 rows like in the image below:
I don't want use other for loop,
Can i do it with table html tags ?
You can achieve this using variables that you will echo later just like this:
$tableHeader = "";
$tableRow = "";
for ($q = 1 ; $q < 7 ; $q++ )
{
$tableHeader .= "<th>" . $q . "</th>";
$tableRow .= "<td>". $row ."</td>";
}
echo "<table> <tr>$tableHeader</tr> <tr>$tableRow</tr> </table>";
Related
Wanted to get 2 values id and name but im confuse how get it, i wanted to show the id in the link. heres the sample code.
echo "<table width=\"100%\" border=\"1\" cellpadding=\"5\" cellspacing=\"2\" bordercolor=\"#FFFFFF\">";
$count = 1;
$id=$_GET['id'];
$col1 = $col2 = array();
$rowcount = round(mysqli_num_rows($nquery) / 2);
while($crow = mysqli_fetch_assoc($nquery)) {
if($count > $rowcount) $col2[] = $crow['title'];
else $col1[] = $crow['title'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $crow) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td><a href='index.php?page=".$id."'>" . $crow . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";
?>`
id wont show up on the link. Hope someone can help. Thanks
You're trying to get $id values from the query string (that's what the $_GET superglobal is) and not from the database.
If both elements (ID and name) are coming from the same database query, you may try something like this:
$crow = mysqli_fetch_assoc($nquery);
foreach ($crow as $row)
{
echo $row['id'].' is the ID and '.$row['title'].' is the title';
}
if you remain within the foreach loop, you can use $row['id'] and $row['title'] to build the table element and link you're trying to obtain.
I am trying to pull data from a table in PHPmyadmin and convert it to an HTML table based on some customer form input which filters out unneeded rows. The code below does that fine. The issue is that two of my columns need to contain links.
It would be easy enough to use PHP to change the table data into the link using a strtolower() and str_replace() to remove spaces, then concatinating the "www.website.com/" and the ".html". But I'm using a foreach loop to get all of the rows that I need and I don't know how to only alter one value per row.
I have tried using "Broswer Display Transformations" and "Input Transformations" in PHPmyadmin, but that only seems to affect the data in PHPmyadmin and not when I access the data via PHP.
My current code:
//* Code for Table
$query = "SELECT $searchFields FROM `hose_reels` $searchPhrase ORDER BY `model` ASC";
$result = mysqli_query($cxn,$query);
if ($row[$key] != "0") {
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
echo "<th>" . $key . "</th>";
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
echo "<td>$row[$key]</td>";
}
echo "</tr>";
}
echo "</table>";
}
else {
echo "<p>No results match your selection. Please broaden your search.</p>";
}
Just add <a> tag in your php code. Below is the code. One more thing you have error in echo "<td>$row[$key]</td>"; line . it prints <td>$row[$key]</td> not the result you are fetching from DB.
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
$i = 1;
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
if($i == 1 || $i ==3){
echo "<th><a href='".key ."'" . $key . "</a></th>";
}else{
echo "<th>" . $key . "</th>";
}
$i++;
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
$j =1;
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
if($i == 1 || $i ==3){
echo "<td><a href='".$row[$key]."'".$row[$key]."</a></td>";
}else{
echo "<td>$row[$key]</td>";
}
}
echo "</tr>";
}
echo "</table>";
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to dynamically build a table using PHP?
I am using code such as the below to build tables etc. but as there are multiple I was wondering in this case is it possible for the table to be built dynamically based on the SQL query?
For example if I need to build another table then I can copy the below code and just edit the SQL rather than also editing the column headers etc. in the HTML.
Basically some method to simplify the below code so that it is more compact\tidier if being used multiple times on the same page.
Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('core/connection.php');
if($conn){
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT c1, c2, c3, c4
FROM t1
ORDER BY c1
)
WHERE ROWNUM <= 10
");
oci_execute($stid);
echo "<table class='table table-hover '>
<thread>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo "<td>" . $row['0'] . "</td>";
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "</tr>";
unset($row);
}
echo "</tbody>
</table>";
oci_free_statement($stid);
oci_close($conn);
}
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
First example on: http://www.php.net/manual/en/function.oci-execute.php
You could use something like jQuery DataTables, http://datatables.net/ - it will allow you build the table from a JSON-object that you have made with PHP (i.e. by using json_encode() on your SQL result).
Here's my 2 cents on it:
function DisplayRawDataset( $dataset, $connection) {
$res = !is_resource($dataset) ? mysqli_quert($dataset) : $dataset;
if ( !is_resource($res) ) return '';
$i = 0;
$retstr = "";
$retstr .= "<table" border=\"1\" style=\"border-collapse:collapse;\" cellspacing=\"0\" cellpadding=\"2\" >";
while($row = $res->fetch_assoc()){
if($i == 0){
reset($row);
$retstr .= "<tr>";
while(list($key, $val) = each($row)){
$retstr .= "<th><b>".htmlspecialchars($key)."</b></th>";
}
$retstr .= "</tr>";
}
$retstr .= "<tr>";
reset($row);
while(list($key, $val) = each($row)){
$retstr .= "<td>".htmlspecialchars($val)."</td>";
}
$retstr .= "</tr>";
$i++;
}
$retstr .= "</table>";
return $retstr;
}
U could probably do this
$return = "<table class='table table-hover '>
<thread>
<tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key){
$return .= "
<th>".$key."</th>
";
}
$return .= "
</tr>
</thread>
<tbody>
<tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key => $value) {
$return .= "<td>" . $value . "</td>";
}
$return .= "</tr>
</tbody>
</table>";
}
echo $return;
or something along this line...
I use this....
<?php
/**
#file: tableFunctions.php
#version: 1.0
*/
//Initialize $headersPrinted boolean
$headersPrinted = false;
function obj2Table($obj, $id, $loop)//Passed arguments should include the object, the id for the created table, and '1' for the default first loop
{
global $headersPrinted;
$print = false;
if ($loop == 1)
{
//Setup a table to output the object
echo "<table id=\"$id\" border='.5'>\r\n";
}
//Loop through the object
foreach ($obj as $name => $value)
{
//Check for nested objects
if (is_object($value))
{
//If it is a nested object, feed the child back through
obj2Table($value, $id, 0);
}//end if(is_object)
//Check for nested arrays
elseif (is_array($value))
{
//If it is a nested array, try to feed each array back through
foreach ($value as $arrayKey => $arrayValue)
{
obj2Table($arrayValue, $id, 0);
}
}//end elseif(is_array)
else
{
//Set the $print boolean to true to print the rows once the foreach ends
$print = true;
if (!$headersPrinted)
{
$keys[] = $name;
}
$cells[] = $value;
}//end else
}//end foreach
if ($print)
{
if (!$headersPrinted)
{
echo "<tr>\r\n";
foreach ($keys as $key)
{
echo "<th>$key</th>\r\n";
}
echo "</tr>\r\n";
$headersPrinted = true;
}
foreach ($cells as $cell)
{
echo "<td>$cell</td>\r\n";
}
echo "</tr>\r\n";
}
if ($loop == 1)
{
//Close the table
echo "</table>\r\n";
//Set the $headersPrinted boolean back to false
$headersPrinted = false;
}//end if(initialLoop)
}//end function obj2Table()
?>
The just include that file in your php. In your while statement for the query results, just add each row to an array like this.. $results[] = $row;. After the while loop, then send the results to the function like this... obj2Table($results, 'queryTable', 1);. NOTE: you would need to change your oci_fetch_array to oci_fetch_object.
You can do something like this...
$sql = "SELECT field1 as 'Colunm 1', field2 as 'Colunm 2', fieldn as 'Colunm n' FROM table;";
function buildTable($sql){
$tab = "";
$head = "";
$body = "";
if (is_string($sql) && $sql !== "") {
$qry = mysql_query($sql);
while ($fet = mysql_fetch_assoc($qry)) {
if ($head == "") {
$head = "<tr>";
foreach ($fet as $key => $val) {
$head .= "<th>{$key}</th>";
}
$head .= "<tr>";
}
$body .= "<tr>";
foreach ($fet as $key => $val) {
$body .= "<td>{$val}</td>";
}
$body .= "</tr>";
}
return "<table><thead>{$head}</thead><tbody>{$body}</tbody></table>";
}
}
echo buildTable($sql);
Yes , it is possible , but you are doing it wrong. HTML that you echo is not valid (some HTML elements have a required closing tag like <table></table> so you should output <table> and </table> in one echo). One of the options for you is to assign your dynamic HTML to a value and then echo the valid HTML.
$buffer = "<table class='table table-hover '>
<thread>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
$buffer .= "<tr>
<td>" . $row['0'] . "</td>
<td>" . $row['1'] . "</td>
<td>" . $row['2'] . "</td>
<td>" . $row['3'] . "</td>
</tr>";
unset($row);
}
$buffer .= "</tbody>
</table>";
echo $buffer;
I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>
i have script as follows
$output="<table class='products'><tr>";
while($info = mysql_fetch_array( $data )) {
//Outputs the image and other data
$output.= "<td>
<img src=http://localhost/zack/sqlphotostore/images/" .$info['photo'] ." width=323px ></img>
<b>Name:</b> ".$info['name'] . "
<b>Email:</b> ".$info['email'] . "
<b>Phone:</b> ".$info['phone'] . "</td> ";
}
$output.="<tr></table>";
print $output;
?>
it shows all results in long horizontal line how do i break the results so that they show
in new row after 3 count.
Keep a counter, and output a new table row every 3 images
$output="<table class='products'>";
$counter = 0;
while($info = mysql_fetch_array( $data ))
{
if( $counter % 3 == 0 )
$output .= '<tr>';
$output .= "<td>";
$output .= "<img src=http://localhost/zack/sqlphotostore/images/".$info['photo'] ." width=323px ></img>";
$output .= "<b>Name:</b> ".$info['name'];
$output .= "<b>Email:</b> ".$info['email'];
$output .= "<b>Phone:</b> ".$info['phone']."</td> ";
if( $counter % 3 == 0)
$output .= "</tr>";
$counter++;
}
$output.="</table>";
print $output;
?>
Add a counter and start a new row every time it reaches a multiple of 3.
$counter = 0;
while($info = mysql_fetch_array($data)) {
if ($counter++ % 3 == 0) {
if ($counter > 0) {
$output .= "</tr>";
}
$output .= "<tr>";
}
// stuff
}
if ($counter > 0) {
$output .= "</tr>";
}
$output .= "</table>";
Please note: It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.