I am not sure how to get the result of a Mysql SUM into your while loop THEN into a variable for displaying in an HTML table.
Firstly I pass a list of codes ie ("1111", "33311", "43433") to a HTML form textarea then implode those codes into a variable called $in. I then pass the list of codes (represented by $in) to my SQL Query.
Mysql Query
SELECT tbl1.code, tbl1.name, tbl1.cost, tble.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH')
AND tbl1.code IN ($in)
NOTE The query works if I do this instead (without the SUM and brackets) BUT it still shows an empty table cell for $stock:
tbl1.vat, tbl2.onhand AS onhand
I am then attempting to pass the value of the Mysql SUM function to a variable, then display that value within a table with php echo.
PHP
$result = $mysqli->query($sql);
if ($result = mysqli_query($mysqli, $sql)) {
while($row = $result->fetch_array()) {
$code = $row['code'];
$name = $row['name'];
$cost = $row['cost'];
$price = $row['price'];
$vat = $row['vat'];
$stock = $row['onhand']; **Result from the Mysql SUM**
...........}
HTML TABLE
echo "<td>" . $name . " </td>";
echo "<td>" . $cost . " </td>";
echo "<td>" . $price . " </td>";
echo "<td>" . $vat . " </td>";
echo "<td>" . $stock . " </td>";
The Mysql query does work as I've tested it in Mac Terminal Mysql but when I attempt to replicate that in php, the $stock is not getting echoed to the table cell??
Cheers
I'm pretty sure your missing a group by in your sql. Maybe changing it to
SELECT tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH') AND tbl1.code IN ($in)
GROUP BY tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat
might work.
Also notice how I changed tble.price to tbl1.price since it looks like a typo
just wanna point out a fact...
hope you are aware that sum is an aggregate function...so using it without a group by clause will cause it to return a just a single row containing the sum total of all the records
SELECT tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat, sum(tbl2.onhand) as onhand
FROM tbl1
INNER JOIN tbl2 ON tbl1.code=tbl2.code
WHERE (tbl2.name='AC' OR tbl2.name='WH') AND tbl1.code IN ($in)
GROUP BY tbl1.code, tbl1.name, tbl1.cost, tbl1.price, tbl1.vat
Related
I have a while loop that iterates through the rows returned from a DB query.
Query
$sql = "SELECT t.barcode AS barcode, t.code, t.brand, t.name, t.cost, t.price, t.vat, SUM(n.stock) AS stock
FROM t
INNER JOIN c.am ON t.code=am.code
INNER JOIN n ON t.code=n.code WHERE (n.name='X' OR n.name='Y')
AND t.code IN ($in)
GROUP BY t.code, t.name, t.cost, t.salesprice, t.vat";
$result = $mysqli->query($sql);
echo "<table id='maintable'><tr><th>Barcode</th><th>Name</th><th>Brand</th></tr>";
while($row = $result->fetch_array()) {
if(empty($row['barcode'])){
$barcode = "none";
}
$barcode = $row['barcode'];
$name = $row['name'];
$brand = $row['brand'];
echo "<td>" . $barcode . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $brand . "</td>";
}
echo "</table>";
The problem is if barcode is empty (not in the DB table), no rows get displayed. However if there is a barcode, the row DOES display. In my example I have tried to check if $row['barcode'] is empty to assign a string so that the row will still display but its unsuccessful.
In the Table itself in the database, the Barcode has a Null field set to YES and Default Field set to NULL so I have also tried:
if(is_null($row['barcode'])) { ..... };
But unsuccessful.
Somewhere I read that empty can equate to: '', 0 and NULL so I'm thinking it's failing because checking if "empty" is the wrong approach?
Any help appreciated.
if(empty($row['barcode'])){
$barcode = "none";
} else {
$barcode = $row['barcode'];
}
or even better:
$barcode = empty($row['barcode'])?"none":$row['barcode'];
So your code would be:
while($row = $result->fetch_array()) {
$barcode = empty($row['barcode'])?"none":$row['barcode'];
$name = $row['name'];
$brand = $row['brand'];
echo "<td>" . $barcode . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $brand . "</td>";
}
UPDATE Not sure about your database structure, but if you need some empty t.barcode values your query could be like:
$sql = "SELECT
t.barcode AS barcode,
n.code,
t.brand, t.name, t.cost, t.price, t.vat,
SUM(n.stock) AS stock
FROM n
LEFT JOIN t
ON t.code=n.code
AND t.code IN ($in)
WHERE (n.name='X' OR n.name='Y')
GROUP BY n.code, t.name, t.cost, t.salesprice, t.vat";
And I don't understand what is INNER JOIN c.am ON t.code=am.code stands for, maybe you should delete it.
Your conditional logic is being followed by this line:
$barcode = $row['barcode'];
Whatever was assigned to $barcode previously is being overwritten.
Looks like you wanted that to be else, or you wanted that line before the conditional test.
As an alternative, you could just modify your query to return the string "none" in place of NULL with an IFNULL function, assuming that barcode is character type.
SELECT IFNULL(t.barcode,'none') AS barcode
, ...
FROM t
EDIT
The question has been edited (after I posted my answer), to add a SQL query to the question.
I thought the problem was that an empty (zero length) string was being assigned to a variable, and the intent was to replace the empty string with a literal.
i currently have a table i need displayed like this:
but as you can see, its not sorted on "amount dropped" (named $amount and amount in the code)
i first need to gather the names and drop_id's from a table. which is done like this:
//----------------FETCH ALL CONTENTS FROM DROPTABLE TO DISPLAY DROPS------------\\
$query = "SELECT * FROM droptable
WHERE boss_id = ". $boss ."";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row){
$drop_id = $row['drop_id'];
$drop = $row['dropname'];
$boss_id = $row['boss_id'];
$picture = $row['picture'];
this fetches the name of the drop(dropname). the id for it (drop_id), the boss id (boss_id) and the picture for it (picture).
it then goes on to check if ive ever logged a drop from the boss from another table:
//----------------FETCH ALL LOGGED DROPS FOR DISPLAYING AMOUNT------------\\
$query1 = "SELECT * FROM dropcounter
WHERE boss_id = ". $boss ." AND userid = ". $user ." AND drop_id = ". $drop_id ."";
$stmt1 = $pdo->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
echo "<tr>";
echo "<td><img src='../images/". $picture ."'</td>";
echo "<td>". $drop . "</td>";
echo "<td>". $amount ."</td>";
echo "<td>". $percent ."</td>";
echo "<form action='logger.php' method='post'>";
echo "<td><input type='hidden' value=". $drop_id ." name='drop_id'>";
echo "<input type='hidden' value=". $boss_id ." name='boss_id'>";
echo "<input type='hidden' value=". $user ." name='user'>";
echo "<input type='submit' value='Add'></td>";
echo "</tr>";
echo "</form>";
this does everything i want exept sort on amount dropped or drop percentage (since they will sort the same). ive tried adding "ORDER BY amount DESC" in the 2nd query but it didnt sort.
ive also tried using JOIN, but it didnt come close to the result i wanted and i got stuck for 3 days on the query so went with the above code instead. but im willing to use join again if my wished result can be done.
here's the JOIN code that doesnt work:
$query = "SELECT dropcounter.drop_id, dropcounter.boss_id, dropcounter.add_date, dropcounter.username, dropcounter.amount, droptable.drop_id, droptable.dropname, droptable.boss_id, droptable.wiki_link, droptable.picture
FROM droptable
JOIN dropcounter
ON droptable.boss_id = dropcounter.boss_id
WHERE dropcounter.drop_id = droptable.drop_id AND droptable.boss_id = ". $boss ." AND dropcounter.username = ". $user ."
ORDER BY dropcounter.amount";
here's the structure i have on my tables:
DROPCOUNTER TABLE:
and here's DROPTABLE table:
if anyone would be able to help me with either one if them i would be very glad for your kindness!
here's a fiddle if anyone wanna try it out. ive imported some sample data: http://sqlfiddle.com/#!2/d66846/1/0
You need to use LEFT JOIN if you want to get rows from droptable that don't have a match in dropcounter. All the tests that refer to dropcounter have to be in the ON clause, otherwise the null matches will cause the tests to fail and those rows will be filtered out.
SELECT dc.add_date, dc.username, IFNULL(dc.amount, 0) amount, dt.drop_id, dt.dropname, dt.boss_id, dt.wiki_link, dt.picture
FROM droptable dt
LEFT JOIN dropcounter dc
ON dt.boss_id = dc.boss_id AND dc.drop_id = dt.drop_id AND dc.userid = $user
WHERE dt.boss_id = $boss
ORDER BY amount
DEMO
You're trying to use in joined statement:
dropcounter.username = ". $user ."
which contains 2 errors:
1. there isn't field username in that table
2. you haven't enclosed string in ''
Change it to dropcounter.userid
Also you don't need to select droptable.drop_id and droptable.boss_id as it's already selected from dropcounter table.
EDIT: Based on your fiddle:
SELECT dropcounter.drop_id, dropcounter.boss_id, dropcounter.userid, dropcounter.amount, droptable.dropname
FROM droptable
JOIN dropcounter
ON droptable.boss_id = dropcounter.boss_id
WHERE dropcounter.drop_id = droptable.drop_id AND droptable.boss_id = 1 AND dropcounter.userid = 1
ORDER BY dropcounter.amount DESC;
It works and sorts without problem.
I have 2 tables called 0_vrs_american and 0_vrs_europe, and I need to display the rows of these tables in a single html table. So I wrote this code:
<?php
$con=mysqli_connect("localhost","aaa","bbb","my_mk7vrlist");
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['playername'] . "</td>";
echo "<td>" . $row['contactable'] . "</td>";
echo "<td>" . $row['vrs'] . "</td>";
echo "</tr>";
$x = $x+1;
}
mysqli_close($con);
?>
I am pretty new with MySQL and so I googled about this topic and I found a syntax like the one you can see above. By the way I have no results in my page because the table is empty.
So: I must display in a HTML table the content of both sql tables, and the rows must be sorted according with the vrs (number that goes from 50000 to 99000). How could I solve my problem?
An alternative to the above is to select all the rows from those two tables as an inner select, and then order by vrs in the returned result set.
SELECT *
FROM
(
SELECT * FROM 0_vrs_american
UNION
SELECT * FROM 0_vrs_europe
) AS a
ORDER BY vrs
at first U need to define $x before the loop
then use the query like this
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200") or die (__LINE__." ".mysqli_error($con));
so you will see the error and the line of the query
i just add or die (__LINE__." ".mysqli_error($con))
Separate the 2 queries and their results
merge both results into an array
sort the array as needed
output the array (generate table rows)
I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks
Have 3 different mysql tables, my script queries the DB using JOINS to output the most recent results from each of the 3 tables. All works like it is supposed to but the way mysql databases allow for JOINS, the ORDER BY will order the results as you list the tables, resulting in the finished output not being ordered by date correctly, since the results are from 3 different MYSQL tables.
The results instead are ordered by date correctly only next to the other results form the same table. See the script and results below: (I am limit 1 for the output for simplicity)
$username = $_SESSION['username'];
$result = $mysqli->query("
SELECT
accounts.account_name,
cases.case_subject,
tasks.task_title,
accounts.accounts_date_last_edited,
cases.cases_date_last_edited,
tasks.tasks_date_last_edited
FROM
accounts,
cases,
tasks
WHERE
accounts.username = cases.username
AND cases.username = tasks.username
ORDER BY
accounts.accounts_date_last_edited DESC,
cases.cases_date_last_edited DESC,
tasks.tasks_date_last_edited DESC
LIMIT 1
");
if (!$result) { echo "Error Result5: " . $mysqli->error; } else {
echo "<table>";
echo "<tr><th>Item</th><th>Date</th></tr>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['account_name'] . "</td><br>";
echo "<td>" . $row['accounts_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['case_subject'] . "</td><br>";
echo "<td>" . $row['cases_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['task_title'] . "</td><br>";
echo "<td>" . $row['tasks_date_last_edited'] . "</td><br>";
echo "</tr>";
}
echo "</table>";
The Results are below: they will list 1 item from each table listed above. Again I am trying to sort by the date_last_edited regardless of which table the values are from.
Item Date
Shorley Homes 2013-11-02 04:02:34
Techical Testing Case Open 2013-11-03 07:17:36
Icons 2013-11-03 07:28:02
If I read correctly (and I'm not sure of that) your
...sort by the date_last_edited regardless of which table the values are from...
then you might want to use UNION instead of JOIN
SELECT account_name item, accounts_date_last_edited date
FROM accounts
UNION ALL
SELECT case_subject, cases_date_last_edited
FROM cases
UNION ALL
SELECT task_title, tasks_date_last_edited
FROM tasks
ORDER BY date DESC
Here is SQLFiddle demo