Numbering the array rows - php

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;

Related

calculations on specific rows in table of database using php

i'm working on a php project that manages teachers in school. but i'm stuck with a problem, i have two tables in my database, first one T1 has on row, second T2 has multiple rows, but they have the same columns number. in a third table T3 i need to fill a column with the total of
(cell1 of T1*cell1 of T2) + (cell2 of T1*cell2 of T2)+ (cell3 of T1*cell3 of T2)....to the last column
i just couldn't find the right way to do this
this is the part that shows the tables from my db
<?php
$host="localhost";
$user="root";
$pass="";
$bdd="test";
$cnx=mysql_connect($host,$user,$pass);
if(!$cnx)
echo"connexion echouee"."</br>";
else
echo"connexion reussie"."</br>";
if (mysql_select_db($bdd))
echo"base de donnees trouvee"."</br>";
else
echo"base de donnees introuvable"."</br>";
$req1="SELECT * FROM `table1`";
$res1=mysql_query("$req1");
// printing table rows
while($row1 = mysql_fetch_row($res1))
{
echo "<tr>";
foreach($row1 as $cell1)
echo "<td>|$cell1|</td>";
echo "</tr>"; echo"</br>";
}
echo "_____</br>";
$req2="SELECT * FROM `table2`";
$res2=mysql_query("$req2");
// printing table rows
while($row2 = mysql_fetch_row($res2))
{
echo "<tr>";
foreach($row2 as $cell2)
echo "<td>|$cell2|</td>";
echo "</tr>";echo"</br>";
}
?>
As long as it is guaranteed that table1 will return 1 row, here is a suggestion:
Instead of using a while loop to fetch the contents, just fetch the row, so the contents of table1 are in $row1
Change foreach($row2 as $cell2) to a foreach($row2 as $key=>$value) format. This way you will have the index of the corresponding element in $row1
Inside the foreach($row2 as $key=>$value) loop, use an accumulator to calculate "Column I". E.G. $tot += $value * $row1[$key]
"echo" the accumulater column before the </tr>
You also probably want to add an empty <td> in the $row1 loop to make sure that all the rows have the same number of columns.
You can traverse second table and calculate total with nested loop:
$res1 = mysql_query("SELECT * FROM `table1`");
$res2 = mysql_query("SELECT * FROM `table2`");
$row1 = mysql_fetch_row($res1);
$row = 0;
// for each row of second table
while ($row2 = mysql_fetch_row($res2)) {
$row++;
$total = 0;
// for each column of first table's row
foreach ($row1 as $index => $table1RowValue) {
// get value of same column in the second table's row
$table2RowValue = $row2[$index];
// calculate aggregated value
$total += $table1RowValue * $table2RowValue;
}
// print result
echo "Line $row: $total</br>";
}

How to show few columns and then rest of other columns in php while loop?

I am showing all rows from mysql database using following php loop :
<tr>
<?php
$get_status = mysqli_query($link, "SELECT * FROM status ORDER BY status_order ASC");
while($status_result = mysqli_fetch_array($get_status) ) {
$status_name = htmlspecialchars($status_result['status_name']);
$status_order = htmlspecialchars($status_result['status_order']);
echo "<td><input type='checkbox' name='$status_name' value='$status_name'>$status_name</td>";
}
?>
</tr>
As a result, It's look like that :
But what I want is following :
I want to show only 5 columns and then 5 columns and then remaining one and so on...in php while loop. How can I do this ?
Add a variable to keep track of the number, then conditionally make a new row, like so:
<?php
$get_status = mysqli_query($link, "SELECT * FROM status ORDER BY status_order ASC");
$n = 0; //Keep track
while($status_result = mysqli_fetch_array($get_status) ) {
$status_name = htmlspecialchars($status_result['status_name']);
$status_order = htmlspecialchars($status_result['status_order']);
echo "<td><input type='checkbox' name='$status_name' value='$status_name'>$status_name</td>";
$n++; //Increase $n
if($n%5===0) echo "</tr><tr>"; //Make a new row every 5 iterations of loop
}

Display count of unique values in MySQL db table using PHP

So I have a table named pins that has 3 columns that need to be taken into consideration. These columns are plan and order_id.
I need to get a count for all of the pins that have an order_id=0 and plan=9.
This is what I have so far:
$qT="SELECT plan, COUNT(*) as cnt FROM pins WHERE order_id=0 and plan=9";
$res=mysql_query($qT);<br/>
mysql_free_result($res);
while($row = mysql_fetch_array($res)) {<br/>
echo $row['plan'];<br/>
}
Any help in displaying the results would be a great help.
Try to group your pin using GROUP BY, So
$result = mysql_query("SELECT plan, COUNT(pin) as cnt FROM pins WHERE (order_id=0 and plan=9) GROUP BY plan");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Plan</th><th>Count</th>";
while ($row = mysql_fetch_array($result))
{
echo "<tr><td>".$row['plan']."</td><td>".$row['cnt']."</td></tr>";
}
echo "</table>";
mysql_free_result($result);
?>

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