Loop through multiple arrays and list the result dynamically - php

I'm struggeling with this one. How can list all devices, their model and supplier from my database? The data is stored comma-separated in the fields device, model and supplier.
<?php
while ($row = mysqli_fetch_array($result)) {
$device_explode = explode(',', $row['device']);
$model_explode = explode(',', $row['model']);
$supplier_explode = explode(',', $row['supplier']);
$device = array(array($device_explode[0]), //count function? How would I do that?
array($model_explode[0]),
array($supplier_explode[0])
);
echo "<table border='1'>
<tr>
<th>Møterom</th>
<th>Romnummer</th>
<th>Lokasjon</th>
<th>Antall sitteplasser</th>
<th>Tilgjengelig utstyr</th>
<th>Bilde av rommet</th>
<th>Endre</th>
<th>Slett</th>
</tr>
<tr>
<td>".$row['name']."</td>
<td>".$row['roomnbr']."</td>
<td>".$row['location']."</td>
<td>".$row['seats']."</td>
<td>".$device[0][0]."<br>".$device[1][0]."<br>".$device[2][0]."<br></td> //also count?
<td><img src='../img/uploads/".$row['img']."' width='150px' ></td>
<td><a href='?p=editconfroomv2&id=".$row['id']."'>Endre</a></td>
<td><a href='./index.php?p=deleteconfroomdb&id=".$row['id']."' class='delete'>Slett</a></td>
</tr>
</table>";
}
?>

It can be done this way (if I understand correct your table structure). I assume, that $device_explode, $model_explode and $supplier_explode have equal number of elements:
<?php
// Table Header
echo "<table border='1'>
<tr>
<th>Møterom</th>
<th>Romnummer</th>
<th>Lokasjon</th>
<th>Antall sitteplasser</th>
<th>Tilgjengelig utstyr</th>
<th>Bilde av rommet</th>
<th>Endre</th>
<th>Slett</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
$device_explode = explode(',', $row['device']);
$model_explode = explode(',', $row['model']);
$supplier_explode = explode(',', $row['supplier']);
// Table rows
$td = '';
$td .=
"<tr>
<td>".$row['name']."</td>
<td>".$row['roomnbr']."</td>
<td>".$row['location']."</td>
<td>".$row['seats']."</td>
<td>";
for ($i = 0; $i < count($device_explode); $i++) {
$td .=$device_explode[$i]." ".$model_explode[$i]." ".$supplier_explode[$i]."<br>";
}
$td .=
"</td>
<td><img src='../img/uploads/".$row['img']."' width='150px' ></td>
<td><a href='?p=editconfroomv2&id=".$row['id']."'>Endre</a></td>
<td><a href='./index.php?p=deleteconfroomdb&id=".$row['id']."' class='delete'>Slett</a></td>
</tr>";
echo $td;
}
echo "</table>";
?>

I would suggest looping trough the arrays in the markup and generating the output using the html templating syntax and alternative control structures.
Some things i have done[not related directly to the question]:
switched the array() syntax for the shorthand [can be done since version 5.4]
switched from using a single echo to utilizing the html templating syntax [by expluding non dynamic parts from php and echoing the dynamic parts in]
Switched from using the echo statement to using the shorthand
Switched to alternative control structures
PHP documentation for strings
<?php
while ($row = mysqli_fetch_array($result)) {
$device_explode = explode(',', $row['device']);
$model_explode = explode(',', $row['model']);
$supplier_explode = explode(',', $row['supplier']);
//I am assuming you want to loop trough all exploded fields related to each row
$devices = [
$device_explode,
$model_explode,
$supplier_explode
];
?>
<?php while(($row = mysqli_fetch_array($result))) : ?>
<table border='1'>
<tr>
<th>Møterom</th>
<th>Romnummer</th>
<th>Lokasjon</th>
<th>Antall sitteplasser</th>
<th>Tilgjengelig utstyr</th>
<th>Bilde av rommet</th>
<th>Endre</th>
<th>Slett</th>
</tr>
<tr>
<td><?= $row['name'] ?></td>
<td><?= $row['roomnbr'] ?></td>
<td><?= $row['location'] ?></td>
<td><?= $row['seats'] ?></td>
<td>
<?php foreach ($devices as $deviceSpecs) : //Here we loop trough the first dimension fo the array ?>
<?php foreach ($deviceSpecs as $deviceSpec): //Here we loop trough the second dimension ?>
<?= $deviceSpec ?><br>
<?php endforeach; ?>
<?php endforeach; ?>
</td>
<td><img src='../img/uploads/<?= $row['img'] ?>' width='150px' ></td>
<td><a href='?p=editconfroomv2&id=<?= $row['id'] ?>>Endre</a></td>
<td><a href='./index.php?p=deleteconfroomdb&id=<?= $row['id'] ?>' class='delete'>Slett</a></td>
</tr>
</table>
<?php endwhile; ?>

Related

PHP returns incorrect HTML code ignoring some tags

I have the below code to display content from a database. The while loop is supposed to display data in a table row. The output is different: the data from the database are displayed before the table. The while seems to run and ignore the html tags, and then run again and ignore the variables.
PHP Code:
// Instantiate database
$database = new Database();
$db = $database->getConnection();
// List transactions without bundles
$query = "SELECT * FROM stock_trx WHERE bundleId IS NULL";
$statement = $db->prepare($query);
$statement->execute();
$n = $statement->rowCount();
if($n > 0){
echo "<table>
<thead>
<tr>
<th>Select</th>
<th>Date</th>
<th>Type</th>
<th>Quantity</th>
<th>Ticker</th>
<th>Amount</th>
<th>Currency</th>
</tr>
</thead>
<tbody>";
// Retrieve table content
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
// Extract row
extract($row);
echo "<tr>".$id."</tr>";
echo "<tr>".$date."</tr>";
echo "<tr>".$type."</tr>";
echo "<tr>".$qty."</tr>";
echo "<tr>".$ticker."</tr>";
echo "<tr>".$amount."</tr>";
echo "<tr>".$currency."</tr>";
}
echo "</tbody></table>";
} else {
echo "No transaction";
}
HTML output:
<html>
<body>
12020-05-13 00:00:00BUYTEST1000022020-05-19 00:00:00SELTEST1200032020-05-24 00:00:00DIVTEST250<table>
<thead>
<tr>
<th>Select</th>
<th>Date</th>
<th>Type</th>
<th>Quantity</th>
<th>Ticker</th>
<th>Amount</th>
<th>Currency</th>
</tr>
</thead>
<tbody><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
</tbody>
</table>
</body></html>
Thank you
You need rows <tr> and cells <td> inside the row:
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
// Extract row
extract($row);
echo "<tr>"; // start row
echo "<td>".$id."</td>";
echo "<td>".$date."</td>";
echo "<td>".$type."</td>";
echo "<td>".$qty."</td>";
echo "<td>".$ticker."</td>";
echo "<td>".$amount."</td>";
echo "<td>".$currency."</td>";
echo "</tr>"; // end row
}
echo "</tbody></table>";
Contrary to the other answer I would either do this, since you're using double-quotes:
echo "<tr>"; // start row
echo "<td>$id</td>";
// etc...
Or combine into one, maybe even one line:
echo "
<tr>
<td>$id</td>
<td>$date</td>
<td>$type</td>
<td>$qty</td>
<td>$ticker</td>
<td>$amount</td>
<td>$currency</td>
</tr>";
While some others have mentioned that you need TD tags, I'd just like to point out some weirder PHP-type things that may or may not help you now / in the future.
Your statement can be rewritten
<?php
while($row = $statement->fetch(PDO::FETCH_ASSOC)):
// Extract row
extract($row);?>
<tr>
<td><?php echo $id; ?>?</td>
<td><?php echo $date; ?>?</td>
<td><?php echo $type; ?>?</td>
<td><?php echo $qty; ?>?</td>
<td><?php echo $ticker; ?>?</td>
<td><?php echo $amount; ?>?</td>
<td><?php echo $currency; ?>?</td>
</tr>
<?php endwhile; ?>
This uses some lesser seen formats for using HTML in PHP files, but it should work never-the-less (tested locally with the PHP 7.4 CLI). Some people prefer it to having to use echo to output all of the HTML, but you do still have to have a bunch of echo statements to print the variables.
To reiterate, there's nothing wrong with any of the other answers, I just feel that in cases like this where you are using a bunch of HTML with PHP that this sort of notation can be a bit easier to work with.
As some people replied, the below tag is missing:
<td>

Quantity of every product outputs like 123. How can i put this in a table row table data

I am having a problem to convert my $quantity_total which is as example (113) from 3 different products.
I want it to be in a table like below.
I have been trying to use chunk_split and explode but if i was able to succeed in that. I wouldn't be able to make it dynamic.
<table>
<tr>
<th>Quantity</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>3</td>
</tr>
</table>
$total=0;
$item_count=0;
$arr = array();
$quantity_all = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$quantity_all .=$quantity;
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4></div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;
$_SESSION['total'] = $total;
$_SESSION['item-count'] = $item_count;
}
$_SESSION['quantity-all'] = $quantity_all;
Is this possible? And i need it to be dynamic. So if it were 10 different quantities. It would make 10 table rows.
I hope someone can help me, would really appreciate it a lot! It's the last thing to finish my e-commerce webshop.
As mentioned in my comment, I don't think this is good solution... but the function you're looking for is str_split. https://stackoverflow.com/a/9814389/296555
http://sandbox.onlinephpfunctions.com/code/0bbee53cafafc0d5e8954e07d0abc2c86c6c89a8
<?php
$rows = '156165165489465131';
echo '<table>';
echo '<tr><th>Quantity</th></tr>';
foreach (str_split($rows) as $row) {
echo "<tr><td>$row</td></tr>";
}
echo '</table>';
I dont know if this Is what you want, but you can try something like:
<table>
<tr>
<td>Quantity</td>
</tr>
<?php
$characters = str_split( (string) $quantity_total);
foreach($characters as $char){
echo "
<tr>
<td> $char </td>
</tr>
";
}
?>
</table>

Display data from SQL query in an HTML table in PHP

I retrieved a list of data from an SQL database and now I would like to display it in a neat table rather than in a list. I managed to find a way to do this (probably not very elegant, though), but the column headers seem to be offset and I have not idea how to fix this.
I'm completely new to PHP, so any hints on how to solve this will be much appreciated!
echo '<table>';
echo '<tr>';
echo '<th>';
echo '<td>Word</td>';
echo '<td>Frequency</td>';
echo '</th>';
echo '</tr>';
$response = $db->query("SELECT * FROM frequencies WHERE freq BETWEEN 900 AND 910 ORDER BY freq");
while ($row = $response->fetch())
{
echo '<tr>';
echo '<td>'.$row['word'].'</td>';
echo '<td>'.$row['freq'].'</td>';
echo '</tr>';
}
echo '</table>';
$response->closeCursor();
A <th> element is a table header element and should be used instead of <td> (table data) element in your header row - it should never be a wrapper around <td> elements.
echo '<table>';
echo '<tr>';
echo '<th>Word</th>';
echo '<th>Frequency</th>';
echo '</tr>';
I prefer combining php and html
<table >
<thead>
<tr>
<th >Word</th>
<th >Frequency</th>
</tr>
</thead>
<?php
$response = $db->query("SELECT * FROM frequencies WHERE freq
BETWEEN 900 AND 910 ORDER BY freq");
?>
<tbody>
<?php
while ( $row = $response->fetch()) {
?>
<tr>
<td><?php echo $row['word']; ?></td>
<td><?php echo $row['freq']; ?></td>
</tr>
<?php }
$response->closeCursor();
?>
</tbody>
</table>

How do I make a MySQL infinite array table?

I am using this code to create an infinite table for my mysql queries:
<table cellspacing='0'> <!-- cellspacing='0' is important, must stay -->
<!-- Table Header -->
<thead>
<tr>
<th>User</th>
<th>SteamID</th>
<th>Banned by</th>
<th>Admin SteamID</th>
<th>Time Banned (min)</th>
<th>Reason</th>
</tr>
</thead>
<!-- Table Header -->
<!-- Table Body -->
<tbody>
<?php
echo '<tr>';
for($i = 0; $bans = mysqli_fetch_array($query2); $i = ($i+1)%3){
echo '<td>'.$bans['name'].'</td>';
echo '<td>'.$bans['steamid'].'</td>';
echo '<td>'.$bans['nameAdmin'].'</td>';
echo '<td>'.$bans['steamidAdmin'].'</td>';
echo '<td>'.$bans['time'].'</td>';
echo '<td>'.$bans['reason'].'</td>';
if($i == 2)
echo '</tr><tr>';
}
echo '</tr>';
?>
</tbody>
I got that code from Mysql fetch array, table results
It works fine, except it doesn't CORRECTLY go further down than 6 rows. The other rows for whatever reason are placed to the right of my last column as shown in this screenshot:
http://puu.sh/h0qZF/a12de1dd87.png
How can I fix this? Is there something wrong with my code? Why is it happening?
Well, your looping makes no sense. Using $i to inject new rows, like is done here, is not necessary; you can just loop over each row and then output it as a row:
<table>
<!-- <thead>...</thead> -->
<tbody>
<?php while ($bans = mysqli_fetch_array($query2)): ?>
<tr>
<td><?php echo $bans['name'] ?></td>
<td><?php echo $bans['steamid'] ?></td>
<td><?php echo $bans['nameAdmin'] ?></td>
<td><?php echo $bans['steamidAdmin'] ?></td>
<td><?php echo $bans['time'] ?></td>
<td><?php echo $bans['reason'] ?></td>
</tr>
<?php endwhile ?>
</tbody>
</table>
You are making two columns.
You have code that will print out the end of the table row every two sets of data:
if($i == 2)
echo '</tr><tr>';
It should just be echo '</tr><tr>';
Use a while loop as instructed here . So something like this:
$result = $conn->query($sql);
while($bans = $result->fetch_assoc()) {
echo '<td>'.$bans['name'].'</td>';
echo '<td>'.$bans['steamid'].'</td>';
echo '<td>'.$bans['nameAdmin'].'</td>';
}

Display query result in a table

I have a MySQL query with over 50 return results. Now I need to display the results in a table with 3 rows and 3 columns.
Something like this:
<table>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
I tried it with PHP like this:
$q = "SELECT name, address, content FROM mytable";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$name = $row['name'];
$address = $row['address'];
$content = $row['content'];
//Create new output
$output = "<p>$name</p>";
$output .= "<p>$address</p>";
$output .= "<p>$content</p>";
//Add output to array
$mycontent[] = $output;
}
Then I am printing the content array in my table like this:
<tr>
<td><?php echo $mycontent[0]; ?></td>
<td><?php echo $mycontent[1]; ?></td>
<td><?php echo $mycontent[2]; ?></td>
</tr>
<tr>
<td><?php echo $mycontent[3]; ?></td>
<td><?php echo $mycontent[4]; ?></td>
<td><?php echo $mycontent[5]; ?></td>
</tr>
<tr>
<td><?php echo $mycontent[6]; ?></td>
<td><?php echo $mycontent[7]; ?></td>
<td><?php echo $mycontent[8]; ?></td>
</tr>
Using this code, I can only display 9 contents. My problem is that I want to display more content. I'm going to use pagination to display contents; something like 0-9, 10-18, 19-27 etc.
NOTE: I can do the pagination part.
I hope someone will give me the right direction for this.
Thank you.
try something like:
echo "<table>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$name = $row['name'];
$address = $row['address'];
$content = $row['content'];
echo "<tr><td>".$name."</td><td>".$address."</td><td>".$content."</td></tr>";
}
echo "</table>";
this example will print in table all the result of the query.
if you want to limit only to some results, so limit the sql query.
for example:
$q = "SELECT name, address, content FROM mytable limit 50";
to get each content,name, address in TD, and 3 of mycontent(content, name, address) in a TR try this:
$c= mysql_query("select COUNT(name) from mytable");
$n=mysql_fetch_array($c);
$maxname= $n[0];
$i=0;
$tr=0;
echo "<table>";
while ($tr < $maxname)
{
echo "<tr>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC) and $i<$tr) {
$name = $row['name'];
$address = $row['address'];
$content = $row['content'];
echo "<td>".$name." | ".$address." | ".$content."</td>";
$i++;
}
echo "</tr>";
$tr= $tr+3;
}
echo "</table>";
Try something like this. It places your values in an easy to use associative array. Then you just loop through.
<?php
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$values[] = array(
'name' => $row['name'],
'address' => $row['address'],
'content' => $row['content']
);
}
?>
<table>
<?php
foreach($values as $v){
echo '
<tr>
<td>'.$v['name'].'</td>
<td>'.$v['address'].'</td>
<td>'.$v['content'].'</td>
</tr>
';
}
?>
</table>
You can store in a variable if u r planning to use it in a function or you can just print it. Either way...
$q = "SELECT name, address, content FROM mytable";
$r = mysqli_query($dbc, $q);
$str = "<table>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$str .= "<tr>";
$str .= "<td>" . $row['name'] . "</td>";
$str .= "<td>" . $row['address'] . "</td>";
$str .= "<td>" . $row['content'] . "</td>";
$str .= "</tr>";
}
$str .= "</table>"
echo $str;
There you go!
use a for-loop to iterate your $mycontent-array:
EDIT: I was made aware that $mycontent is built differently than I first assumed:
$h = "<table>"; // we are going to build the table in $h
$maxcount = count($mycontent); // get the number of values within the array
for ($i = 0;$i < $maxcount;$i++) { // counting $i up from 0 to $maxcount -1 ...
$h.= "<tr><td>{$mycontent[$i]}</td></tr>"; // build row
}
$h.= "</table>"; // close the table
echo $h; // echo it
---> live demo: http://3v4l.org/g1E1T
YOU CAN REFERENCE THIS CODE
<tbody>
<!-- <tr>
<td>Technology</td>
<td>Professor Abiola</td>
<td>wetech#school.com</td>
<td> Plot 2, Oriola road,</td>
<td>
<button type="button" class="btn btn-primary"> Edit</button>
<button type="button" class="btn btn-success">Update</button>
<button type="button" class="btn btn-danger">Delete</button>
</td>
</tr> -->
<?php
while($rows = mysqli_fetch_array($response)){
$faculty = $rows['faculty'];
$hod = $rows['hod'];
$email = $rows['email'];
// $location = $rows['location'];
echo "<tr>
<td>$faculty</td>
<td>$hod</td>
<td>$email</td>
<td>".$rows["location"]."</td>
<td>
<button type='button' class='btn btn-primary'>Edit</button>
<button type='button' class='btn btn-success'>Update</button>
<button type='button' class='btn btn-danger'>Delete</button>
</td>
</tr>";
}
?>
</tbody>
</table>

Categories