I have several MySQL tables that are dynamically generated into a html table one table at a time through the code below. However, the tables don't have the same columns. i.e. One table has a description column, whereas the other does not.
Is the following code the best way to have all the possible MySQL columns among the various tables in the script but only show the MySQL columns that exist for the selected table? I feel like I'm redundant by writing "isset" for every column. Thanks!
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
?>
<table>
<tr>
<?php if(isset($row['name'])){ ?>
<td><?php echo $row['name'];?></td>
<?php } ?>
<?php if(isset($row['description'])){ ?>
<td><?php echo $row['description']?></td>
<?php } ?>
</tr>
</table>
You might want to make your code adapt to the fields in the result set:
<?php
$result = mysqli_query($con,$query);
$fields = mysqli_fetch_fields($result);
$myaliases = array(
'column_id' => 'id'
);
?>
<table>
<tr>
<?php foreach ($fields as $field): ?>
<th><?php echo $myaliases[$field->name] ?: $field->name; ?></th>
<?php endforeach; ?>
</tr>
<?php while($row = mysqli_fetch_array($result)): ?>
<tr>
<?php foreach ($fields as $field): ?>
<td><?php echo $row[$field->name]; ?></td>
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
Re comments:
I've added code above to print a table row for column headings.
I've also included an example of mapping a field name column_id to a table heading id in the output. If I define no alias for a given column, it defaults to the original field name by using the PHP 5.3 operator ?:
You could alternatively define column aliases in your SQL query like SELECT column_id AS id ...
See http://www.php.net/manual/en/mysqli-result.fetch-fields.php
You can foreach the array instead.
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
If you need to print labels you can also use an associative array and an additional iteration to do that as well.
<?php
$query = " SELECT * FROM $tablename ";
$keys = array('name' => 'Name Label', 'description' => 'Description Label');
$query_select = mysqli_query($con,$query);
$i = 0;
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<?php if($i == 0) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><b><?=$keys[$key]?></b></td>
<?php } //Endforeach ?>
</tr>
<?php } $i++; //Endif ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
You could just loop through the results. However, that would not perform any checks. Most likely, you'll have to do something like this, depending on what you're actually getting from the database.
<?php foreach ($row as $field): ?>
<?php if ($field): ?>
<td><?php echo $field; ?></td>
<?php endif; ?>
<?php endforeach; ?>
Edit: In keeping in line with the comment you added above, you could simply remove the if clause.
not sure if this is what you need,
but you can use indexes instead for the column instead of names:
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
echo $row[0] ." ".$row[1]." ".$row[2]
}
?>
mysql_fetch_array
possible formating:
<table>
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) { ?>
<tr>
<?php for(var $i=0; $i < count($row); $i++){
echo "<td>". $row[i] ."</td>";
} ?>
</tr>
<?php } ?>
</table>
Related
I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script
<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Height</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Age"] . "</td><td>"
. $row["Height"]. "</td></tr>";
}
echo "</table>";
} else //{ echo "0 results"; }//
$conn->close();
?>
</table>
but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .
Like everyone else said, you should convert your horizontal array into a vertical one.
Of course it should be a universal function to convert any query result, as opposed to hardcoding the row headings. The idea is to get each row's array keys and use them as the keys for the new array and then add each corresponding value to the new array item.
Here is how it's done in mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('127.0.0.1','root','','test');
$mysqli->query("set names 'UTF8'");
$data = [];
$res = $mysqli->query("SELECT Name, Age, Height FROM student order by Name desc");
while ($row = $res->fetch_assoc()) {
foreach(array_keys($row) as $key) {
$data[$key][] = $row[$key];
}
}
and then you get an array with desired structure which you can output using the code from ROOT's answer:
<table border="1">
<?php foreach($data as $key => $val): ?>
<tr>
<td><?= $key ?></td>
<?php foreach($val as $field): ?>
<td><?= $field ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
I mocked your data into normal array, I used a while loop to create a new Array and create the format that we need to be able to flip the columns into rows, here is what I think you want:
<?php
$users = [
[
'name'=> 'James',
'height'=> 1.75,
'age'=> 18,
],
[
'name'=> 'Bill',
'height'=> 170,
'age'=> 16,
]
];
$newArr = [];
foreach($users as $key => $val) {
$newArr['name'][$i] = $val['name'];
$newArr['age'][$i] = $val['age'];
$newArr['height'][$i] = $val['height'];
$i++;
}
?>
<table border="1">
<?php foreach($newArr as $key => $val): ?>
<tr>
<td><?php echo $key; ?></td>
<?php foreach($val as $field): ?>
<td><?php echo $field; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach ?>
</table>
It's not a good idea ! if you have a lot of ROW you will generate a long table not visible for user in screen.
if you want to do it after all you can change table structure but you will not respect html table structure.
I will give you a
Dirty code
<table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Age"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Height"]; ?></td>
<?php } ?>
</tr>
</table>
I recommand to USE CSS instead a table
I create a code to display from a table
$sql = "SELECT * FROM table";
$stmt = $dbcon->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
to display the result, I use the following ode:
<?php foreach($result as $readrow){ ?>
<div class="table-row">
<td><?php echo $readrow['id'];?></td>
<td><?php echo $readrow['area'];?></td>
<td><?php echo $readrow['color'];?></td>
<?php } ?>
Is there any way, the table can be displayed with the header?
There are many duplicated questions but all answers are beyond any reason, offering complicated solutions involving running extra queries etc.
While the solution is right here: when using fetchAll(), you already have all the column headers in the $result variable
$headerNames = $result ? array_keys($result[0]) : [];
now you can foreach over $coulmnNames to get the table header and the foreach over $result to display the results.
<table class='table'>
<tr>
<?php foreach($coulmnNames as $name): ?>
<th><?= $name ?></th>
<?php endforeach ?>
</tr>
<?php foreach($result as $row){ ?>
<tr class="table-row">
<?php foreach($result as $value){ ?>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</table>
I have a record like this in database:
section_id description level_id
1 Amethyst 1
2 Betelguise 1
3 Daisy 2
4 Rose 2
I want it to display in my php table just like this:
Level 1
Amethyst
Betelguise
Level 2
Daisy
Rose
Can anyone please help me? I am new at this.
Here's my code:
<table>
<thead>
<tr>
<th>Descriptions</th>
<th>Level</th>
</tr>
</thead>
<?php $sql = "SELECT * FROM tbl_sectiontaken"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while($row = $result->fetch_assoc()) { ?>
<?php $id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id']; ?>
<tbody>
<tr>
<td style="text-transform:capitalized;">
<?php echo $desc; ?>
</td>
<td style="text-transform:capitalized;">
<?php echo $gr; ?>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
But it gives me this result in table:
Descriptions Level
Amethyst 1
Betelguise 1
Daisy 2
Rose 2
You can use group_concat function for this. Use below code if suits your requirements
<?php $sql = "SELECT level_id,GROUP_CONCAT(description) AS description FROM series group by level_id"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while ($row = $result->fetch_assoc()) { ?>
<?php
$id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id'];
$leveArr[$gr][] = $desc;// Create an array with level and description
} } ?>
</tbody>
<table>
<tr><!-- header-->
<?php foreach ($leveArr as $key => $value) { ?>
<td><?php echo "LEVEL " . $key ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($leveArr as $key => $value) {
foreach ($value as $key_1 => $data) { ?>
<td><?php
$data = explode(",", $data);
foreach ($data as $key_2 => $final) {
echo $final . "<br>";
}
?></td>
<?php }
} ?>
</tr>
</table>
Updated
Check the sandbox example
Change query with GROUP_CONCAT
SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id
And After.They return array like this
$arr=[['description'=>'a,b,c,d','level_id'=>'1','heigher'=>'4'],['description'=>'a,b,c,d','level_id'=>'2','heigher'=>'4']]; ?>
Then Finally Create Table as like this
$sql="SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id";
$result = $conn->query($sql);
$arr =[];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$arr[]=$row;
}
}
<table>
<thead>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?='level'.$value['level_id']?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
$arr = array_filter($arr,function($a=[]){
return $a['level_id'] != 0
}) //filter level not a zero
$h = max(array_map(function($a=[]){
return $a['heigher']; //filter array['heigher only']
},$arr)); // its get the heighest length of description value like [10,15,100]=>100
foreach ($arr as $key => $value){
$value['description'] = !empty($value['description']) ?explode(',',$value['description']):'';
$arr[$key]=$value;
}
?>
<?php for ($i=0; $i < $h[0]; $i++) {?>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?=isset($value['description'][$i])? $value['description'][$i] :''?></th>
<?php endforeach; ?>
</tr>
<?php }?>
</tbody>
</table>
foreach($ligne as $value){
$result = $bdd->query('SELECT count(d.DNUMERO) as nbr, SUM(d.DINIPPL) as total FROM dossier d, cliregroup c, doinfsup i WHERE i.DSNUMERO = d.DNUMERO AND d.DNUMCLI = c.NUMCLI AND i.INFOSUPPLM REGEXP "([1][4-6][0-9a-zA-Z]{6}[0-9]{4})" AND INFOSUPPLM NOT REGEXP "([0-1][0-4][0-9a-zA-Z]{6}[0-9]{4})" AND i.DSNUMERO LIKE "16%" AND c.CODEREGROUP LIKE "'.$value.'"');
$table = $result->fetchAll();
print_r($table);
}
<?php include_once('header.html'); ?>
My $table return one row not the full table (the last row). In the php file it's good:
<?php print_r($table); ?>
<table class="table">
<?php foreach ($table as $key => $q): ?>
<?php foreach ($secteur as $key => $s): ?>
<tr>
<th><?php echo $key; ?></th>
<td><?php echo $q['nbr']; ?></td>
<td><?php echo $q['total']; ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</table>
</body>
</html>
You are overwriting $table each time through the loop. Try an array:
$table[] = $result->fetchAll();
Other issues:
<?php foreach ($table as $key => $q): ?>
<?php foreach ($secteur as $key => $s): ?>
You overwrite $key with the second loop.
Where does $secteur come from? It's not defined. Maybe you meant $q?
I have a script that creates a basic table layout structure and I'm trying to use AJAX with jQuery to input the output of that script into a TinyMCE textarea. I wrote the script in PHP and it works perfectly well if I open up the script directly.
What I'm trying to do is let the user choose something from a dropdown (in this case, a product) and it return a table filled with the relevant data for that product. I use the following script to insert it into the textarea:
$('#product_id').change(function(e) {
product_id = $(this).val();
$.ajax({
url: 'http://<? echo $_SERVER['HTTP_HOST']; ?>/includes/ajax.php',
type: 'POST',
data: { product_choice: true, product_id: product_id },
success: function(data) {
$('#mce_1').val(data);
}
});
});
'data' does return but when it's placed in the tinyMCE textarea, it shows the following error(the script carries on and outputs the table):
Warning: Invalid argument supplied for foreach() in /home/sites/very-dev.co.uk/public_html/cms/includes/ajax.php on line 71Warning: Invalid argument supplied for foreach() in /home/sites/very-dev.co.uk/public_html/cms/includes/ajax.php on line 100
Those two foreachs which error are:
foreach($product_data as $key=>$product): and foreach($product_data as $product):
// Connect to database
$link = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
// check connection //
if (mysqli_connect_errno()):
return printf("Connect failed: %s\n", mysqli_connect_error());
endif;
$col_qry = mysqli_query($link,"
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'cms_plugins_products_models'
AND column_name != 'id'
AND column_name != 'product_id';")
or die(mysqli_error($link)
);
while($col_row = mysqli_fetch_object($col_qry)):
$col_names_array[] = $col_row->column_name;
endwhile;
$qry = "SELECT product.name AS product_name, product.id, model.*, image.src AS thumb
FROM cms_plugins_products AS product
LEFT JOIN cms_plugins_products_models AS model
ON (product.id=model.product_id)
LEFT JOIN cms_plugins_products_images AS image
ON (product.id=image.product_id)
AND (image.is_thumb=1)
WHERE product.id='" . $_GET['product_id'] . "'";
$result = mysqli_query($link, $qry) or die(mysqli_error($link));
while($row = mysqli_fetch_object($result)):
foreach($col_names_array as $column):
$columns = explode('_', $column);
if($column != 'name' && $column != 'description'):
$components_qry = "SELECT name
FROM cms_plugins_products_components_" . $columns[0] . "
WHERE id='" . $row->$column . "'";
$components_result = mysqli_query($link, $components_qry) or die(mysqli_error($link));
$components_row = mysqli_fetch_object($components_result);
endif;
if($columns[0] == 'name'):
$product_data[$row->product_name][$row->name][$columns[0]] = $row->name;
elseif($columns[0] == 'description'):
$product_data[$row->product_name][$row->name][$columns[0]] = $row->description;
else:
$product_data[$row->product_name][$row->name][$columns[0]] = $components_row->name;
endif;
endforeach;
$thumb = $row->thumb;
endwhile; ?>
<table>
<thead>
<tr>
<th></th> <?
$i = 0;
foreach($product_data as $key=>$product):
foreach($product_data[$key] as $key2=>$model): ?>
<th <? if($i == 1): echo 'id="recommended"'; endif; ?>> <?
switch($i):
case 0:
echo 'Basic';
break;
case 1:
echo 'Mid';
break;
case 2:
echo 'Pro';
break;
endswitch; ?>
<div>
<img alt="<? echo $key; ?>" src="http://cms.very-dev.co.uk<? echo $thumb; ?>">
</div>
<h5><? echo $key2; ?></h5>
<p><? echo $product_data[$key][$key2]['description']; ?></p>
<a>Customise?</a>
</th> <?
$i++;
endforeach;
endforeach; ?>
</tr>
</thead>
<tbody> <?
foreach($product_data as $product):
$i = 0;
foreach($product as $model):
foreach($model as $key2=>$component): ?>
<tr> <?
if($key2 != 'name' && $key2 != 'description'): ?>
<td><? echo $key2; ?></td> <?
foreach($product as $key=>$model): ?>
<td><? echo $product[$key][$key2]; ?></td> <?
endforeach;
endif; ?>
</tr> <?
endforeach;
if($i == 0): exit(); endif;
$i++;
endforeach;
endforeach; ?>
</tbody>
</table>
It's probably quite a simple problem that I'm not seeing, any help on this one?
After looking at the code more carefully, it was a simple error. I was using a GET for the product_id but upon include that of course isn't set so it's breaking down but doesn't error out because of it being an include. Fixed simply by sending the GET variable along.