I have a table in database like this:
ID, features, Values : ID will be 1, 2, 3....
features will be color, size, material....
values will be red, 13inch, silicon...
I stored it like this:
ID
1
1
1
Features
color sizematerial
valuesred13insilicon
and it continues for product 2... . I am trying to display it in tabular form which i am not getting.
Actually it has to go to next row when id -2 comes... but it keeps on displaying in the same row....
can somebody tell me how to do it?
I tried like this
echo "<table width='100%'>";
echo "<tr><th>color</th>
<th>size</th>
<th>material</th></tr>";
echo "<tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<td>".$row['values']."</td>";
}
echo "</tr>";
echo "</table>";
EDITED **
This is my complete code
if(isset($_POST['submit']))
{
$id = $_POST['id'];
$test = "SELECT id, features, values FROM mytable WHERE features IN ('color', 'size', 'material') AND id IN (" . implode(',',$id) .")";
$result = mysql_query($test) or die (mysql_error());
echo "<table width='100%'>";
echo "<tr><th>color</th>
<th>size</th>
<th>material</th></tr>";
echo "<tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<td>".$row['values']."</td>";
}
echo "</tr>";
echo "</table>";
}
and the output for print_r(mysql_fetch_assoc($result));
Array ([id] => 1 [features] => color [values] => red )
I think this should solve the problem:
$table_markup = '<tr>';
$current_row = null;
while ( $row = mysql_fetch_assoc($result) ) {
if ( $current_row === null ) {
$current_row = $row['id'];
}
if ( $current_row != $row['id'] ) {
$current_row = $row['id'];
$table_markup .= '</tr><tr>';
}
$table_markup .= '<td>' . $row['values'] . '</td>';
}
/* cutting off the last opened-TR tage */
$table_markup .= substr($table_markup, 0, -4);
echo $table_markup;
Related
This question already has answers here:
How do I get the first level category to display only once?
(3 answers)
Closed 3 years ago.
I'm trying to get a list of items in a region.
I'd like the Region Name as a Heading
Then all the items in that region in a table below
i.e.
HEADING - Region1
Table - Region1 Items
HEADING - Region2
Table - Region2 Items
HEADING - Region3
Table - Region3 Items
HEADING - Region4
Table - Region4 Items
I can output:
HEADING
HEADING
HEADING
I can output the region details in a table if I use LIKE 'Actual Region Name'
I would like to output using LIKE $region so I don't need to write a new statement for each 'Actual Region Name'.
The 2 SELECT Queries:
$region = mysqli_query($conn,"SELECT DISTINCT region FROM country") or die($conn->error);
$result = mysqli_query($conn,"SELECT * FROM country WHERE region LIKE '$region'") or die($conn->error);
OUTPUT 1
This outputs each region as Region Name
$i = 0;
while($row = $region->fetch_assoc())
{
if ($i == 0) {
foreach ($row as $value) {
echo "<p>" . $value . "</p>";
}
}
}
OUTPUT 2
This outputs all the region data and puts it in a table.
echo "This is table Build";
echo "<table border='1'>";
$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
OUTPUT 1 and OUTPUT 2 both work separately.
I can't get them to work together
You can get all region names from query and then passed it to your next query and print all the record related to that query i.e :
<?php
$region = mysqli_query($conn,"SELECT DISTINCT region FROM country") or die($conn->error);
if($region->num_rows > 0)
{ {
while($row = $region->fetch_assoc())
{
//printing region name
echo "<p>" . $row['region'] . "</p>";
//only those row will be retrieve which belong to current region name
$result = mysqli_query($conn,"SELECT * FROM country WHERE region LIKE '$row['region']'") or die($conn->error);
//printing table
echo "This is table Build";
echo "<table border='1'>";
$i = 0;
while($row1 = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row1 as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row1 as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
mysqli_close($conn);
?>
I want to read out data from an sql-database an show them in a table. This works well. Now, I would like to show only those columns with at least one value in it and not the empty ones (containing NULL, 0, empty string). This works with the following example:
enter code here
<TABLE width="500" border="1" cellpadding="1" cellspacing="1">
<?php
$query = mysql_query("SELECT * FROM guestbook", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Home = array_column($results, 'Home');
$Date = array_column($results, 'Date');
$Emptycolumn = array_column($results, 'Emptycolumn');
$Comment = array_column($results, 'Comment');
$City = array_column($results, 'City');
}
echo "<TR>";
if(array_filter($Name)) {echo "<TH>Name</TH>";}
if(array_filter($Home)){echo "<TH>Home</TH>";}
if(array_filter($Date)){echo "<TH>Date</TH>";}
if(array_filter($Emptycolumn)){echo "<TH>Emptycolumn</TH>";}
if(array_filter($Comment)){echo "<TH>Comment</TH>";}
if(array_filter($City)){echo "<TH>City</TH>";}
echo "</TR>";
$query = mysql_query("SELECT * FROM guestbook", $db);
while($line = mysql_fetch_assoc($query)){
echo "<TR>";
if(array_filter($Name)) {echo "<TD>".$line['Name']."</TD>";}
if(array_filter($Home)) {echo "<TD>".$line['Home']."</TD>";}
if(array_filter($Date)) {echo "<TD>".$line['Date']."</TD>";}
if(array_filter($Emptycolumn)) {echo "<TD>".$line['Emptycolumn']."</TD>";}
if(array_filter($Comment)) {echo "<TD>".$line['Comment']."</TD>";}
if(array_filter($City)) {echo "<TD>".$line['City']."</TD>";}
echo "</TR>";
}
?>
</TABLE>
Since the column-names of my table are highly variable (depending on the query), the table is generated by looping through the result-array, first the column-names, then the values in the rows:
enter code here
$sql = "SELECT DISTINCT $selection FROM $tabelle WHERE
$whereclause"; //will be changed to PDO
$result = mysqli_query($db, $sql) or die("<b>No result</b>"); //Running
the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
if ($numrows > 0) {
echo "<table id='myTable' >";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== false){
echo "<th>" . $key . "</th>";
}else{
echo "<th>" . $field[$x]->name . "</th>";
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
Now, I tried to integrate the array_column() and array_filter()-blocks of the example above into the loops, but unfortunately, it didn´t work. I´m sure, this is easy for a professional and I would be very grateful, if someone could help me with this problem!
Thank you very much in advance!!
I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";
$result = mysqli_query($db, $sql) or die("Invalid query");
$numrows = mysqli_num_rows($result);
$numcols = mysqli_num_fields($result);
$field = mysqli_fetch_fields($result);
if ($numrows > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) {
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($db);
Now, I want to remove specific columns (e.g. those, which are empty or those, which are not that interesting for the user, who makes the request).
I tried it with unset($field[$variable]), however, it didn't work. In addition, the values (if there are any), should be removed, too.
can let mysql filter them out for you,
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.
You can check against the $field[$x]->name variable and use continue to skip the column.
<?php
// DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';
try { // try to connect in database.
$pdo = new PDO($dsn, $usr, $pwd);
} catch (PDOException $e) { // if there is error in the connection.
die('Connection failed: ' . $e->getMessage());
}
// Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();
// Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);
// Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';
// Check $row;
if (count($rows)) {
// Order and Display Cols.
$colsDisplay = [
'id' => 'ID Product',
'name' => 'Name',
'weight' => 'Weigth'
];
// Table.
$html = '<table border="1">';
$html .= "\n <thead>";
$html .= "\n <tr>";
$html .= "\n <th bgcolor='#eee'>Row</th>";
$html .= "\n <th>". implode("</th>\n <th>", $colsDisplay) ."</th>";
$html .= "\n </tr>";
$html .= "\n </thead>";
$html .= "\n <tbody>";
// Loop ROWS.
foreach ($rows as $key => $val) {
$html .= "\n <tr>";
$html .= "\n <td bgcolor='#eee'>". $key ."</td>";
// Loop COLS to display.
foreach ($colsDisplay as $thKey => $thVal) {
$html .= "\n <td>". $val->$thKey ."</td>";
}
$html .= "\n </tr>";
}
$html .= "\n".' </tbody>';
$html .= "\n".'</table>';
echo $html;
}
In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:
<?php
// ...
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";
// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
if ($row[$columnIndex] > 0) {
$nonEmpty[] = $columnIndex;
}
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $len; ++$i) {
$rowHTML = '';
if (!in_array($i, $nonEmpty)) {
$rowHTML .= '<td>' . $row[$i] . '</td>';
}
$rowHTML .= "</tr>\n";
}
}
// ...
This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.
The code isn't optimized - it's just a rough idea. But it's a starting point.
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])