How To Fix While Loop output results - php

I just want to get the results of while loop which is within a php in different lines
if($count == 0){
$output = 'THERE WAS NO RESULTS';
}
else{
while($row = mysqli_fetch_array($query)){
$des = $row['description'];
$file = $row['name'];
$output ='<div>'.$des. '</div>';
echo "<td>";
echo "$output";
echo "<a href='".$file."'>Download</a></td>";
}
}
}
echo "</table>";
?>
I am getting all the results in the same line itself.

Are you missing the table row tag? <tr>
if($count == 0){
$output = 'THERE WAS NO RESULTS';
}
else{
echo '<table>';
while($row = mysqli_fetch_array($query)){
$des = $row['description'];
$file = $row['name'];
echo '<tr>';
echo '<td><div>'. $des .'</div></td>';
echo '<td><a href='".$file."'>Download</a></td>';
echo '</tr>';
}
echo '</table>';
}

Related

How can I arrange this code so I can get different entry from database for each table row

I want every different record of database to be display on each table rows, but I'm unable to retrieve different record for each row and column. Please give me suggestion where I can paste than while block so it will give different result for each row and column.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$company=$row['company'];
$model=$row['model'];
$available=$row['availability'];
$price=$row['price'];
}
echo "<table border='2'>";
$j = 0;
for($j = 0; $j<5; $j++)
{
echo "<tr>";
for($i = 0; $i<3; $i++)
{
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><img src='abc.jpg' height='250' width='250'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><b>Brand : </b></td>";
echo '<td>'.$company.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Model : </b></td>";
echo '<td>'.$model.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Availability : </b></td>";
echo '<td>'.$available.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Price : </b></td>";
echo '<td>'.$price.'</td>';
echo "</tr>";
echo "</table>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
You need to move the table rows inside the fetch loop or store the row in an array. I have simplified your tables to make the example clearer:
$result = mysql_query($sql);
if (!$result) {
/* Error */
}
echo '<table>';
while ($row = mysql_fetch_array($result)) {
echo '<tr><td><img src="', htmlspecialchars ($row['image']), '">';
echo '<tr><td><table>';
echo ' <tr><th>Brand<td>', htmlspecialchars ($row['company']);
echo ' <tr><th>Model<td>', htmlspecialchars ($row['model']);
echo ' <tr><th>Availability<td>', htmlspecialchars ($row['availability']);
echo ' <tr><th>Price<td>', htmlspecialchars ($row['price']);
echo ' </table>';
}
echo "</table>\n";
Some notes about the code:
Test the return value of mysql_query(). The query might fail.
Escape your output using htmlspecialchars().
You should use <th> elements for your headings and style those, instead of using inline <b> elements.
I added output of $row['image'] which might not do what you want.
And do not use the deprecated mysql extension. Use PDO or mysqli instead.
In your while loop you always rewrite the same variables, after loop you have only last record saved.
In the loop, you have to save records into array.
In your code you have nested tables, but in the first one, there is only one row and one table cell which contains another table. I use just nested table.
<?php
...
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_array($result)) {
$data[] = $row;
}
if (count($data) > 0) {
echo '<table>';
foreach ($data as $row) {
echo '<tr>';
echo '<td>Brand: ' . $row['company'];
echo '<td>Model: ' . $row['model'];
echo '<td>Availability: ' . $row['availability'];
echo '<td>Price: ' . $row['price'];
}
echo '</table>';
} else {
echo 'no records';
}
?>
Not sure I fully understand what you are trying to accomplish but try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
echo "<table border='2'>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['company']."</td>";
echo "<td>".$row['model']."</td>";
echo "<td>".$row['availability']."</td>";
echo "<td>".$row['price']."</td>";
echo "</tr>";
}
echo "</table>";
?>

mysqli fetch_assoc with conditional statement

I am trying to display multiple parts of a query on my page using fetch_assoc and some conditional statements. My first while loop is displaying the correct information, but loops 2 and 3 are not displaying any information. What would be the correct way to filter my results?
require_once('inc/connection.inc.php');
//create database connection
$conn = dbConnect();
//create SQL
$sql = 'SELECT * FROM menu';
$result = $conn->query($sql) or die(mysqli_error());
while($row = $result->fetch_assoc()){
if($row['category'] == 'appetizers'){
echo $row['title'];
echo $row['price'];
}
}
while($row = $result->fetch_assoc()){
if($row['category'] == 'salads'){
echo $row['title'];
echo $row['price'];
}
}
while($row = $result->fetch_assoc()){
if($row['category'] == 'desserts'){
echo $row['title'];
echo $row['price'];
}
}
Why not do it like this:
while($row = $result->fetch_assoc()){
if($row['category'] == 'appetizers'){
echo '<h1>Appetizers</h1>';
echo $row['title'];
echo $row['price'];
}
if($row['category'] == 'salads'){
echo '<h1>Salads</h1>';
echo $row['title'];
echo $row['price'];
}
if($row['category'] == 'desserts'){
echo '<h1>Desserts</h1>';
echo $row['title'];
echo $row['price'];
}
}
i.e., use the conditions in a single while loop.
OR
You can use mysqli_data_seek to reset the pointer to the first record and re-use the same resource multiple times
while($row = $result->fetch_assoc()){
if($row['category'] == 'appetizers'){
echo $row['title'];
echo $row['price'];
}
}
mysqli_data_seek($result,0);
while($row = $result->fetch_assoc()){
if($row['category'] == 'salads'){
echo $row['title'];
echo $row['price'];
}
}
mysqli_data_seek($result,0);
while($row = $result->fetch_assoc()){
if($row['category'] == 'desserts'){
echo $row['title'];
echo $row['price'];
}
}
you are running query result one time and fetching it three time so need to query result three time
$result = $conn->query($sql) or die(mysqli_error());
$result1 = $conn->query($sql) or die(mysqli_error());
$result2 = $conn->query($sql) or die(mysqli_error());
then loop
while($row = $result->fetch_assoc()){
while($row1 = $result1->fetch_assoc()){
while($row2 = $result2->fetch_assoc()){
Also you can use mutiple if() in loop like:-
while($row = $result->fetch_assoc()){
if($row['category'] == 'appetizers'){
echo $row['title'];
echo $row['price'];
}
if($row['category'] == 'salads'){
echo $row['title'];
echo $row['price'];
}
if($row['category'] == 'desserts'){
echo $row['title'];
echo $row['price'];
}
}
while($row = $result->fetch_assoc())
{
if($row['category'] == 'appetizers'){
echo $row['title'];
echo $row['price'];
}
if($row['category'] == 'salads'){
echo $row['title'];
echo $row['price'];
}
if($row['category'] == 'desserts'){
echo $row['title'];
echo $row['price'];
}
}
I think what you're after is something like this...
$categories = ['appetizers', 'salads', 'desserts'];
if (!$stmt = $conn->prepare('SELECT title, price FROM menu WHERE category = ?')) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('s', $category);
foreach ($categories as $category) {
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->bind_result($title, $price);
while($stmt->fetch()) {
echo $title, $price;
}
}
What I've done is execute a prepared statement for each category in the $categories array. This will group your menu rows together under each category in the order you want.

PHP/SQL - Query not showing all data

Here's the code:
<?php
if(isset($_POST['results']) && $_POST['results'] != -1) {
$db = new PDO('mysql:host=localhost;dbname=;charset=utf8', '', '');
echo "<table border='1'>
<tr>
<th>Courses</th>
</tr>";
$stmt = $db->prepare("SELECT title FROM course WHERE `subject_id`=?");
$stmt->execute(array($_POST['results']));
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>", $row['title'], "</td>";
echo "</tr>";
}
} else {
echo "No results found";
} echo "</table>";
}
?>
This is just returning one result into the table, when there are more results to show.
Where am I going wrong?
remove the if, because it's change the pointer of array(fetch)
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // get the first record, remove this if
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {// get the second record and reset $row
you can change to:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total_rows = $stmt->rowCount();
if($total_rows > 0){
foreach($row as $item){
echo '<td>'. $item['title'] .'</td>';
}
}else{
echo 'no results';
}

PHP - Adding a separator in a Loop

I asked this question yesterday but no one replied after I tried to get further help. I've been trying to figure out the problem in the code I was given in my previous post but it's not giving me the results I want. Right now what it does is it writes a separator after each row but what I really want is if the name of the manager from the previous row is different then write a separator and keep going on with loop.
while ($row = mysqli_fetch_array($results)) {
$team = $row[0]['Manager'];
foreach($row as $rows){
if($rows['Manager'] !== $team){
echo "<tr><td colspan=\"3\">Separator</td></tr>";
}
echo "<tr>";
echo "<td>".$row['Manager']."</td>";
echo "<td>".$row['Employee_ID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "</tr>";
}
}
You're mixing $row and $rows, you would be okay doing this:
$team = "";
while ($row = mysqli_fetch_array($results)) {
if($team && ($row['Manager'] != $team)){ // skip first separator
echo "<tr><td colspan=\"3\">Separator</td></tr>";
}
$team = $row['Manager'];
echo "<tr>";
echo "<td>".$row['Manager']."</td>";
echo "<td>".$row['Employee_ID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "</tr>";
}
Am I missing something, or can you simply display the data, then assign it to the variable further in the loop?
while ($row = mysqli_fetch_array($results)) {
$team = $row[0]['Manager'];
foreach($row as $rows){
if($row['Manager'] !== $team){
echo "<tr><td colspan=\"3\">".$team."</td></tr>";
}
echo "<tr>";
echo "<td>".$row['Manager']."</td>";
echo "<td>".$row['Employee_ID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "</tr>";
$team = $row[0]['Manager'];
}
}
What is $rowS['Manager'] ? $rowS is unknown. use $row['Manager'] like:
if($row['Manager'] !== $team){
echo "<tr><td colspan=\"3\">Separator</td></tr>";
}
while ($row = mysqli_fetch_array($results)) {
$team = $row[0]['Manager'];
foreach($row as $rows){
if($rows['Manager'] !== $team) {
$team = $row['Manager'];
echo "<tr><td colspan=\"3\">Separator</td></tr>";
}
echo "<tr>";
echo "<td>".$row['Manager']."</td>";
echo "<td>".$row['Employee_ID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "</tr>";
}
}
Just move the value allocation $team = $rows['Manager']; in the if condition.
while ($row = mysqli_fetch_array($results)) {
$team = "";
foreach($row as $rows){
if($rows['Manager'] != $team){
echo "<tr><td colspan=\"3\">Separator</td></tr>";
$team = $rows['Manager'];
}
echo "<tr>";
echo "<td>".$rows['Manager']."</td>";
echo "<td>".$rows['Employee_ID']."</td>";
echo "<td>".$rows['Name']."</td>";
echo "</tr>";
}
}

How do I display two rows from sql side-by-side using php?

My code below displays 10 entries, but it displays it in 10 rows and 1 column. I would like for it to display 10 entries, but in 2 columns and 5 rows. Can anyone help? Thanks in advance.
< ?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo '<tr>';
}
}
echo '</table>'
?>
<?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10") or die(mysql_error());
$i = 1; //The following logic only works if $i starts at '1'.
$numofcols = 2; //Represents the number of columns you want in the table.
echo '<table>'; //Open table.
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No'){
continue;
}
else{
//If it's the beginning of a row...
if( $i % $numofcols == 1 ){
echo '<tr>'; //Open row
}
//Table Cell.
echo '<td>'; //Open Cell
echo 'ID Number: '.$row['id'];
echo '<br/> <img src="'.$row['Pic'].'"> <br/>';
echo '</td>'; //Close Cell
//If we have already placed enough cells, close this row.
if( $i % $numofcols == 0) {
echo '</tr>'; //Close Row.
}
//Now that we've made a table-cell, lets increment our counter.
$i = $i + 1;
}
}
//So we make sure to close our rows if there are any orphaned cells
if( ($i % $numofcols) > 0){
echo '</tr>';
}
echo '</table>' //Close Table
?>
Please note that the mod logic will only work if the starting value of $i is '1'.
This code will create a table with 2 columns.
Not tested, but basically you can call $row = mysql_fetch_array() in the loop as well to grab another row.
while($row = mysql_fetch_array( $result ))
{
echo "<tr>";
echo "<td>";
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo "</td>";
$row = mysql_fetch_array( $result );
if($row)
{
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
}
else
{
// Empty cell
echo "<td> </td>";
}
echo "</tr>";
}
Use modulo for echo "< tr>"
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
$i = 0;
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
if ($i % 5)
echo '</tr>';
$i++;
}
echo '</table>'

Categories