I need to know how to use MAX() and COUNT() query to display the "fiser" table entries that contain the primary "codp" key that comes from the "products" table, depending on a previously selected period?
Table products : codp, denp ;
Table orders: codc,codp ;
Table returns : codr, datar, codc, codp
<?php
if(isset($_POST['add'])){
$sql = "SELECT p.denp, a.datar,MAX(p.codp)
FROM ( SELECT COUNT(p.codp) FROM products p ) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d') ";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
echo "
<table border=1 >
<tr>
<td><p> ".$row['codp']." </p></td>
<td><p> ".$row['denp']." </p></td>
<td><p> " .$row['codr']." </p></td>
<td><p> " .$row['datar']." </p></td>
<td><p> " .$row['codc']." </p></td>
</tr> </table> ";
}
} else {
echo " No results!" ;
}
}
?>
You should use group by for codp and the join the related result eg:
$sql = "SELECT p.denp, r.datar,MAX(p.cnt_codp)
FROM (
SELECT codp, COUNT(*) as cnt_codp FROM products
group by codp
) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d')
GROUP BY p.denp, r.datar ";
and you should check for your db driver for param bindig instead of use of php var in sql (you are at risk for sql injection)
and you should also use a group by for not aggreated column or reeval the question if you need the values related to max result (the use of aggregation function without a proper group by columns for not aggreagated is depreacted in sql ai the most recent version of mysql is not allowed)
Related
My aim is to show/display in the right part questions of the survey (from a table of my database) and in the left part answers from customers (from another table in my database) in the right part. So my question is : How to merge this two select query ? I did some research but with php it's kind of tricky to understand and I'm still new on php too.
Any help or advices are welcome .
Best Regards A.V.
<?php
include("bdconnect_Foredeck.php");
$link=mysqli_connect($host,$login,$pass,$dbname);
if(isset($_POST["bouton55"])){
$link = mysqli_connect($host,$login,$pass,$dbname);
$id = $_REQUEST["Zoubi"];
$ClientRef =$_REQUEST["KGB"];
$rechercheq = "SELECT Qref,Ref,Question FROM questionnaire WHERE Qref ='$id' ";
$recherche= "SELECT choix,commentaire FROM reponse WHERE RefQ ='$id' and ref_Client ='$ClientRef'";
mysqli_query($link,$recherche);
mysqli_query($link,$rechercheq);
$result1=mysqli_query($link,$rechercheq);
$result= mysqli_query($link,$recherche);
while($row = mysqli_fetch_assoc($result,$result1)){
$Ref =$row["Ref"];
$Question =$row["Question"];
$Choix =$row["choix"];
$Commentara =$row["commentaire"];
echo" <tr bgcolor=\"white\">
<td> $id </td>
<td> $Ref </td>
<td>$Question </td>
<td>$Choix </td>
<td>$Commentara </td>
</tr>";
}
}
?>
You could use a JOIN
SELECT a.Qref, a.Ref,a.Question , b.choix, b.commentaire
FROM questionnaire as a
LEFT JOIN reponse as b ON a.RefQ = b.RefQ
WHERE a.Qref ='$id'
AND b.ref_Client ='$ClientRef'
if you have duplicated rows .. then you can use distinct
SELECT DISTINCT a.Qref, a.Ref,a.Question , b.choix, b.commentaire
FROM questionnaire as a
LEFT JOIN reponse as b ON a.RefQ = b.RefQ
WHERE a.Qref ='$id'
AND b.ref_Client ='$ClientRef'
otherwise you logic don't permit a single query
I can count number of a table rows by using mysqli_num_rows. I have a table which contains similar rows. How can I count by grouping by similar row?
For instance: I have a table with 2 columns : Student and Option. Let say there are 50 students. 20 are in Economy option, 20 are in Management option and 10 are in Secretary Option. How can display those numbers. I can display only the 50.
my codes
$qry = "select * from table group by option";
$req= #mysqli_query($conn, $qry);
$result = mysqli_query( $conn, "select id from table");
$num_rows = mysqli_num_rows($result);
Students Total (<?php echo $num_rows ?>)
<table >
<tr>
<th>Student</th>
<th>Option</th>
</tr>
<?php
while($row=mysqli_fetch_array($req))
{
?>
<tr>
<td><?php echo $row['student'] ?></td>
<td><?php echo $row['option'] ?></td>
</tr>
<?php
}
?>
</table>
Here is the query you need:
SELECT COUNT(*) AS `option_count`, * -- returns a count aliased as "options_count"
FROM `table`
GROUP BY `option` -- will group the options and show the counts
Now you can echo the count, along with other data:
echo $row['count_options'];
echo $['options'];
The problem that you have here is that you will not be able to display each student in the option because this counts / groups only the three options.
Behold the proper query :
$qry = "select option as opt, COUNT(*) AS option from table group by option";
in the result of sql query, I will check with php which column has record.
example:
if ($column_1) {echo $column_1}
if ($column_2) {echo $column_2}
if ($column_3) {echo $column_3}
I don't use else if there because I need it to continue in checking the record from the sql query.
However with the php code above, I can't union table in order to get another record of column from that table too. First, because the column count doesn't match. Then even though I manipulate the column, it will give me a duplicate row.
What I have been trying so far to achieve this is to use sub query. But before I know the result, it has come with an error.
Well, this is my full code. Have a look, please.
$sql = "SELECT op.reference_no, op.eight_percent, op.ten_percent,
op.date, op.claim, op.orders_history_id,
oh.one_product_price, oh.quantity,
(
SELECT it.type
FROM infimoney_transfer it
),
(
SELECT it.receiveable
FROM infimoney_transfer it
),
(
SELECT oh.id AS ohid
FROM infimoney_transfer it
)
FROM order_promotion op
LEFT JOIN orders_history oh
ON oh.id = op.orders_history_id
WHERE oh.customer_id = $member_id";
$saldo = $mysqli->query($sql);
if(!$saldo){ printf("Errormessage: %s\n", $mysqli->error); die(); }
if ($saldo->num_rows > 0) {
while($objek = $saldo->fetch_object()) {
if ($objek->eight_percent)
{
$sourceCash = $objek->quantity % 10 > 4 ? 1 : 0;
echo "<tr>
<td>".$objek->reference_no . "</td>
<td>Cashback 8%</td>
<td>".$objek->date."</td>
<td>".$sourceCash * 5 * $objek->one_product_price."</td>
<td>".$objek->eight_percent."</td>
<td> - </td>
<td> Not Yet </td>
</tr>";
}
if ($objek->ten_percent)
{
$sourceCash = (int)($objek->quantity / 10);
echo "<tr>
<td>".$objek->reference_no . $objek->orders_history_id."</td>
<td>Cashback 10%</td>
<td>".$objek->date."</td>
<td>".$sourceCash * 10 * $objek->one_product_price."</td>
<td>".$objek->ten_percent."</td>
<td> - </td>
<td> Not </td>
</tr>";
}
if ($objek->claim)
{
$sourceCash = (int)($objek->quantity / 10);
echo "<tr>
<td>".$objek->reference_no . $objek->orders_history_id."</td>
<td>Claimed</td>
<td>".$objek->date."</td>
<td>".$objek->claim."</td>
<td> - </td>
<td>".$objek->claim."</td>
<td> Not </td>
</tr>";
}
Please Help. Thanks in Advance.
If you join your tables all in the same select query, it will not give you duplicate rows:
$sql = "SELECT op.reference_no, op.eight_percent, op.ten_percent,
op.date, op.claim, op.orders_history_id,
oh.id, oh.one_product_price, oh.quantity,
it.type, it.receiveable,
FROM order_promotion op
LEFT JOIN orders_history oh ON oh.id = op.orders_history_id
LEFT JOIN infimoney_transfer it ON it.orders_list_id=oh.order_list_id
WHERE oh.customer_id = $member_id";
i have a question for the experts. I have no idea how to combine all the order ID with the same ID,
like in the picture, all orders with order ID = 1 are in one transaction, how do i combine all order IDs with the same id and display only one total price for all of the proudcts bought. and since all order ID are the same so the deliver and payment option will also be the same just need to display one row.
and a follow up question is how will i also show all the products bought if i combine all the same order IDs, compute the total price and display delivery and payment option in one single row
Here is the picture for my database relationship, i just followed the ones on the internet. the only difference is that "products" are changed to "inventory" and "serial" in products are changed to "prod_id"
here are my codes to display the current picture.
<?php
session_start();
$conn = #mysql_connect("localhost","root","");
$db = #mysql_select_db("");
$qry = "SELECT customers.name,customers.payment,customers.carrier, orders.date, order_detail.productid, order_detail.quantity, order_detail.price, order_detail.orderid, inventory.prod_name
FROM customers
RIGHT JOIN orders on customers.serial=orders.serial
RIGHT JOIN order_detail on orders.serial=order_detail.orderid
LEFT JOIN inventory on order_detail.productid=inventory.prod_id where customers.email='{$_SESSION['email']}'";
mysql_set_charset("UTF8");
$result = #mysql_query($qry);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<center>";
echo "<table class='CSSTableGenerator'>
<tr>
<td>Date of Purchase</td>
<td>First Name</td>
<td>Order ID</td>
<td>Products</td>
<td>Quantity</td>
<td>Total Price</td>
<td>Delivery Option</td>
<td>Payment Option</td>
<tr>";
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['orderid']."</td>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td>".($row['price']*$row['quantity'])."</td>";
echo "<td>".$row['carrier']."</td>";
echo "<td>".$row['payment']."</td>";
echo "</tr>";
}
echo "</table>";
?>
</table>
It seems that what you're needing to learn for this particular question is the SQL Group By clause.
This (untested, might need minor tweaking) should do the trick. Note that you don't get order item quantities out of this, but I would say that it's possible to get them.
SELECT o.date, c.name, o.serial as 'Order Id', GROUP_CONCAT(p.name) as 'Products', SUM(od.price) as 'Total', c.carrier, c.payment
FROM orders o
JOIN customers c on o.customer_id = c.serial
JOIN orderdetail od on o.serial = od.orderid
JOIN products p on od.productid = products.prod_id
GROUP BY o.serial
Of particular note is a handy aggregate function in MySQL called GROUP_CONCAT.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
this is how I should use distinct to download the content again.
Here at pictures VISR it to the download content 3 times, but I only want it 1 time in total
what is the problem is that it does not pick all of them, but I only want it to pick up only one of time, which means that it only need to download one time by title and simultaneously username.
$sql = "SELECT DISTINCT fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.title FROM fms_bruger INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id WHERE fms_opslagpm.til_id = ? ORDER BY fms_opslagpm.datotid DESC";
if ($stmt = $this->mysqli->prepare($sql)) {
$stmt->bind_param('i', $id);
$id = $_SESSION["id"];
$stmt->execute();
$stmt->bind_result($fornavn, $efternavn, $id, $title);
while ($stmt->fetch()) {
?>
<tr class="postbox">
<td class="beskedinfo">
<p><?php echo $fornavn . " " . $efternavn;?></p>
</td>
<td>
<?php echo $title;?>
</td>
<td>
Slet
</td>
</tr>
<?php
}
$stmt->close();
}
You need to use GROUP BY not DISTINCT to get the grouping of the title field.
SELECT fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.title
FROM fms_bruger
INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id
WHERE fms_opslagpm.til_id = ?
GROUP BY fms_opslagpm.title
ORDER BY fms_opslagpm.datotid DESC
SELECT DISTINCT does exactly what it says: it selects distinct rows.
You include id in the columns. I'm pretty sure IDs will be unique, therefore all rows are DISTINCT.
Consider removing the DISTINCT keyword and adding a GROUP BY `fms_bruger`.`title` clause. This is an extension to the SQL standard which will return an arbitrary row for each unique title.