Rows Sorting properly but not items in those rows? - php

$sql = "SELECT counter, title FROM items WHERE ORDER BY counter DESC LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$count = $row['counter'];
$i++;
if($i==1){
echo '<div class="row">';
}
echo '<div class="col-sm-3">';
echo '<p><a href="index.php>'.$row[$title].'<br />'.$count.'</a></p>';
echo '</div>';
if($i==4){
echo '</div>';
$i=0;
}
}
}
The code above displays 3 items per row using bootstrap.
The problem I am have is that the ROWS are sorting properly, BUT the 3 items in each row are NOT sorting properly,(by counter DESC).
As an example, I am getting:
<p>1500 -- 1345 -- 1675</p>
<p>1233 -- 1267 -- 1331</p>
<p>1232 -- 1209 -- 1222</p>
As you can see, ALL the items in row 1 are DESC when compared to rows 2 and 3, but the individual items in row one are not sorting properly.
Any thoughts?

Try Using below code
<?php
$sql = "SELECT counter, title FROM items WHERE ORDER BY counter DESC LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$i++;
if($i==1){
echo '<div class="row">';
}
echo '<div class="col-sm-3">';
echo '<p><a href="index.php>'.$row['title'].'<br />'.$row['counter'].'</p>';
echo '</div>';
if($i==4){
echo '</div>';
$i=0;
}
}
}

The PROBLEM was actually in the CSS - the "class="col-sm-3" was set to float-right, therefore reversing the flow of the output. Sorry for the confusion, as the CSS was not present.
This is very interesting that the style dictated the output flow - hmmm.
Thank you for your help Naishant.

Related

Displaying all items from mysql database

I have table product and table category in my database. I want to display all category dynamically in a table and inside the table of each category I am displaying all item belonged to that category too.
Those categories and items should be displayed like this :
And here is my coding to do the work :
$fetch_cat = "SELECT * FROM tblcat"; //fetch from table category
$result = $conn->query($fetch_cat);
if ($result->num_rows > 0)
{
while($cat_row = mysqli_fetch_assoc($result))
{
$cat_title = $cat_row['catName'];
echo '<table>';
echo '<tr>';
echo '<td><img src="category/'.$cat_row['catImg'].'" /></td>';
echo '<td>';
echo '<ul class="content_init">';
$stmt = "SELECT * FROM tblproduct WHERE prodCat = '".addslashes($cat_title)."' LIMIT 4"; //fetch from table product
$result = $conn->query($stmt);
if ($result->num_rows > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo '<li>';
echo '<a href="#"><img style="height: 188px; width: 188px;" src="user_images/'.$row['prodImg'].'" />';
echo '<br /><br />';
echo '<h4>'.$row['prodName'].'</h4>';
echo '<label><span>RM </span>'.$row['prodPrice'].'</label></a>';
echo '</li>';
}
}
echo '</ul>';
echo '</td>';
echo '</tr>';
echo '</table>';
}
}
Problem :
So the problem with my coding is, it can only display Category 1 with items belonged to it. The rest categories unable to be displayed. I guess my coding might not loop properly because of bad programming as it unable to display the expected output.
The $result variable was reused by the inner query thus the first result override.
Change the variable name either of the $result variable.
$result1 = $conn->query($stmt);
if ($result1->num_rows > 0)
{
while($row = mysqli_fetch_assoc($result1))
{
Your approach is not good/optimal. You have query for the categories and then one query per each category,so if you have 10 categories your code would execute 11 queries. You should do it with one query only using INNER JOIN
You can select all the values left joining the category table for the names and group them by their category ID.
See Group array by subarray values
Afterwards, you can traverse each product for each category by accessing the subarrays.

Numbering the array rows

I have selected the whole table with mysql, there are records of sold tickets.
When I am writing them out with foreach, they are showing correctly from the newest sold ticket at the top to the oldest purchase at the bottom.
The problem is that the IDs do not look good. I have done many test purchases before launching it and the id numbers are starting from 50 now.
I would like to keep it as it is now but only number the records with normal numbers from 1. The problem is that the highest number must be at the top since the latest record is there on top. Could somebody advice me on how to do this please?
When you use while loop you have to create one variable before start loop and increatement it by 1 in loop and use it as row number :)
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
echo "<table border='1'>";
$line_counter=mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$line_counter}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$line_counter--;
}
echo "</table>";
}
Usually, when you're fetching from DB, the ID column which is usually on auto-increment is not reliable, so when fetching, you should run your own auto-increment. i.e.
<?php foreach($rows as $index => $row): ?>
<table>
<td><?php echo $index + 1 ?></td>
to display with custom index in descending order using php
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
$index = mysqli_num_rows($result);
echo "<table border='1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$index}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$index--;
}
echo "</table>";
}
for ascending index
$sql ="SELECT * FROM tbl_purchases ORDER BY id DESC";
if ($result = $link->query($sql)) {
$index = 1;
echo "<table border='1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>".
"<td>{$index}</td/>".
"<td>{$row['id']}</td/>".
"<td>{$row['name']}</td>".
"</tr>";
$index++;
}
echo "</table>";
}
==================
To reset the auto incremental column in DB (start again from 1)
For MYISAM
ALTER TABLE tbl_purchases AUTO_INCREMENT = 1;
For INNO DB
SET #num := 0;
UPDATE tbl_purchases SET id = #num := (#num+1);
ALTER TABLE tbl_purchases AUTO_INCREMENT =1;

Every X result different while fetch from mysql database

I have simple php foreach loop which fetch some data from MySQL database
$result = $pdo->prepare( "SELECT * FROM table ORDER BY RAND() LIMIT 30");
$result->execute();
foreach ($result as $row)
{
echo 'data';
}
As you can see there is LIMIT 30. Is it possible to to insert different data on every 10th result.Data which is not from database. It's static data and wont be changeable. What I mean is something like
if ( $row=10 )
{
echo $row['name'];
}
else
{
echo '<div> some static text not from database </div>';
}
$counter=0;
foreach ($result as $row)
{
$counter++;
if($counter %10==0){} //10th result
else{} //not 10th result
}
$counter = 0; //This is the counter which we will use to count row numbers.
$result = $pdo->prepare( "SELECT * FROM table ORDER BY RAND() LIMIT 30");
$result->execute();
foreach ($result as $row)
{
$counter++; //We are incrementing the counter.
echo $row['name'];
//If we are at a row which is multiple of 10, we output a static value.
if($counter % 10 == 0)
echo 'Hello World!';
}

Compare MySQL data with another table

This code below echoes out 8 names from tableOne, but I want to compare those names with 8 names in another table. I want to compare the rows echoed in $row['weight'] with tableTwo, and if the results don't match, then add a <span class="strike"> </span> to the result echoed in $row['weight'].
How do I go about adding an if/else to $row['weight'] compare each name with the names in another table?
$result = mysqli_query($con,"SELECT * FROM tableOne LIMIT 0, 8");
$i = 1;
while($row = mysqli_fetch_array($result)) {
echo $i. " - " . $row['weight'] . '<br>';
$i++;
}
Here is some simple code to get you started:
$result = mysqli_query($con,"SELECT * FROM tableOne LIMIT 0, 8");
$result2 = mysqli_query($con,"SELECT * FROM tableTwo LIMIT 0, 8");
$i = 1;
while($row = mysqli_fetch_array($result)) {
$value1 = $row['weight'];
$row2 = mysqli_fetch_array($result2);
$value2 = $row2['weight'];
echo $i . " - table 1: ";
echo $value1;
echo ", table 2: - ";
if ($value2 != $value1) {
echo '<span class="strike">$value2</span>';
} else {
echo $value2;
}
echo '<br>';
$i++;
}
You can make the code smarter, to handle cases where there aren't 8 values to compare, and to display the values in an HTML table too, but hopefully this can get you started.
Try this:
$sql="select * from tableone to left join tabletwo tw on to.weight=tw.weight ";
This query will return all the rows in tableone which matches and empty rows for the ones where the weight dont match.
So in your php code:
while($row = mysqli_fetch_array($result)) {
if(empty($row['weight'])){
echo '<span class="strike">$row[weight]</span>';
}
}
This would work with any dynamic number of records in the tables.
How about keeping the values ($row[]) in one array($tableOne) and doing the same thing for table two ($tableTwo) and then perform your comparison in foreach()? (For the sake of simplicity, if you don't want any joins)

Same query, different results in php vs phpmyadmin- Why?

I am trying to get the total actions from each employee in a MySQL database. My script is giving me a significantly lower total than the number in the database for all employees. I am using a SUM function in the query. The query works fine in phpmyadmin, but not in my script. Any ideas why this is happening.
$query = "SELECT user_id, SUM(num_actions) as action FROM pro_actions GROUP BY user_id ORDER BY action DESC";
if ($result = $db->query($query)) {
$count = 0; // this is the total of all employee actions. which adds up correctly!
while ($row = mysqli_fetch_array($result)) {
$count += $row['action'];
echo '<tr><td>';
echo $row['user_id'];
echo '</td><td>';
echo $row['action'];
echo '</td></tr>';
}
$result->free();
}
When I run this script, employee 1005 has 63 actions. However, when I run this query in phpmyadmin, employee 1005 has 194 actions (which is correct). All employees have fewer actions in the output of the script. The interesting thing is that the $count variable outputs the correct amount, which is the total of all actions... Please help with this glitch.
$query = "SELECT user_id, SUM(num_actions) as action FROM pro_actions GROUP BY user_id ORDER BY action DESC";
if ($result = $db->query($query)) {
$count = 0; // this is the total of all employee actions. which adds up correctly!
while ($row = mysqli_fetch_array($result)) {
$count += $row['action'];
echo '<tr><td>';
echo $row['user_id'];
echo '</td><td>';
echo $row['action'];
echo '</td></tr>'; //tag mismatch
}
$result->free();
}

Categories