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();
}
Related
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.
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;
It calculates, but starting from the second row.
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
}
?>
Your code has many issues:
Your code starts to calculate from the second row because of the line:
$row = mysql_fetch_array($result);
which obtains the first result from the opened recordset before the while loop.
$sold = array();Why is that an array?
If you want to sum to $sold, threat the variable as an integer and initialize it with a 0.
$sold = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$sold += $row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
It seems to me also that you may want to print the table only once. If this is true, consider to query the database with an aggregation function like SUM():
SELECT SUM(contract + iva) AS contractIva FROM users GROUP BY <some column in your table>;
The above allows to remove the while loop.
Since you already extracted a row from the result, with $row = mysql_fetch_array($result);, the script starts adding only with the next row. Th correct code would be:
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr>
<td>" . $sold. "</td>
</tr></table>";
}
?>
you can do that via query as well so that you don't need to perform calculation on the application level, database level can do this job for you.
select sum(col1+col2) as total from users
And you want one table instead of multiple tables I guess, if yes then do it like this:
echo "<table>
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo <tr><td>" . $sold. "</td></tr>";
}
echo "</table>";
I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.
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)