For each customer, I want to return: id, name, address, city, cap, country and total of orders. Table names are: customers (10 records) and orders (20 records)
I've tried this code, but it doesn't works
<?php
$conn = mysqli_connect('127.0.0.1','...','...','...') or die("Connection failed: " . $conn->connect_error);
$select = mysqli_query($conn,"SELECT customers.id,customers.name,customers.address,customers.city,customers.cap,customers.country COUNT(customerid) as TotalOrders FROM customers LEFT JOIN orders GROUP BY customer.id");
while($row = mysqli_fetch_array($select,MYSQLI_ASSOC))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}
mysqli_free_result($select);
echo $num_record = mysqli_affected_rows($conn);
$conn->close();
?>
So something like...
<?php
include('../path/to/connection/stateme.nts');
$query =
"
SELECT c.id
, c.name
, c.address
, c.city
, c.cap
, c.country
COUNT(o.customerid) TotalOrders
FROM customers c
LEFT
JOIN orders o
ON o.customerid = c.id
GROUP
BY c.id;
";
$result = mysqli_query($db,$query); ** where $db is something like mysqli_connect("myhost", "myusername", "mypassword");
while($row = mysqli_fetch_assoc($result))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}
mysqli_free_result($result);
echo $num_record = mysqli_affected_rows($db);
$db->close();
?>
(I'm no php coder)
You have a comma missing -
customers.country COUNT(customerid)
-----------------^
and you have left out an ON condition -
FROM customers LEFT JOIN orders //ON would be here
One thing you should always do is to create and run your queries against your database before you put those queries in your code. And always, always include error checking.
Related
I'm trying to build a basic prestashop (1.7.8.6) module that collects 'id_customer' and 'firstname' from the ps_customer table then checks to see what date the last order was by that customer by checking the 'invoice_date' on the ps_orders table WHERE id_customer = 'id_customer'. If the order was over 732 days it then flags that account to be deleted
I can do this using something like the below:
<?php
$con=mysqli_connect("localhost","****","****","****");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT id_customer, date_add FROM ps_customer ORDER BY id_customer DESC";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_assoc($result))
{
$id_customer = $row['id_customer'];
$date_add = $row['date_add'];
$sqldelete="SELECT invoice_date FROM ps_orders WHERE (id_customer = '$id_customer') ORDER BY invoice_date ASC";
$resultdelete = mysqli_query($con,$sqldelete);
while ($rowdelete = mysqli_fetch_assoc($resultdelete))
{
$invoice_delete = $rowdelete['invoice_date'];
if(strtotime($invoice_delete) < strtotime('-732 days')) {
$shouldbedeleted = "Y";
} else {
$shouldbedeleted = "N";
}
}
However, I'm trying to do this by building a module instead of in a stand alone php page.
So far, I have got the below:
$db = \Db::getInstance();
$request = 'SELECT `id_customer`,`date_add`,`firstname` FROM `' . _DB_PREFIX_ . 'customer` LIMIT 20';
/** #var array $result */
$results = $db->executeS($request);
$this->context->smarty->assign('customerdata', $results);
which I can then echo out in the tpl using
<table>
{foreach $customerdata as $userone}
<tbody>
<td style="padding-right:10px;">{$userone.id_customer}</td>
<td style="padding-right:10px;">{$userone.date_add}</td>
<td style="padding-right:10px;">{$userone.firstname}</td>
</tbody>
{/foreach}
</table>
However, I am unsure how to compare this data with the ps_orders table. Ideally, I want to show the last order date next to each customer. e.g. so the admin can see when the customer last placed an order.
Any help with this would be greatly appreciated
You can edit your query in something like :
SELECT c.id_customer, c.firstname,
(SELECT datediff(CURDATE(), o.date_add) AS number_of_days_from_last_order
FROM ps_orders o WHERE
c.id_customer = o.id_customer
ORDER BY o.date_add DESC limit 1) as last_order_date
FROM ps_customer c
JOIN ps_orders o2 ON c.id_customer = o2.id_customer
GROUP BY c.id_customer
to get all the required data and display it in your TPL,
of course you can add a clause on number_of_days_from_last_order value
to display only orders older than xxx
i have made a query to select only the last date for each user. It works in phpmyadmin but when i want to execute it in a mysqli_query() in PHP it doesnt give anything back, not even an error.
the code is:
select * from table t inner join ( select User_ID, max(Date) as MaxDate from table group by User_ID ) tm on t.User_ID = tm.User_ID and t.Date = tm.MaxDate
If you have any idea why please let me know :)
EDIT
the PHP code is :
$id = $_SESSION["ID"];
$SqlQuery = "SELECT * from 'tablename' t inner join ( select 'User_ID', max('Date') as 'MaxDate' from 'tablename' group by 'User_ID' ) tm on 't.User_ID' = 'tm.User_ID' and 't.Date' = 'tm.MaxDate'";
$Result = mysqli_query($link, $SqlQuery) or die ("not possible to execute query: $sql on $link");
if ($Result->num_rows > 0) {
while($row = $Result->fetch_assoc()) {
echo "<br> id: ". $row['Sick_ID']. " - UserID: ". $row['User_ID']. "- Reason " . $row['Reason'] . "<br>";
}
} else {
echo "0 results";
}
Add the schema owner prefix to the select query. It usually happens when executing mysql queries on PHP.
Select * from data.table_name as t1 inner join data.table_name_2 as t2 .....
Better if:
Select data.t1.id, data.t2.name from data_table_name as t1 .....
Need help getting a sum for quantity and accessory_price in my current query to display in my table.
Here is my query:
$query = ('SELECT accessories.accessory_name,accessory_only_solds.transaction_id,accessory_only_solds.quantity,accessory_only_solds.accessory_price,transactions.date_purchased, FROM accessory_only_solds
left join accessories on accessory_only_solds.accessory_id = accessories.id
left join transactions on transactions.id = accessory_only_solds.transaction_id
ORDER BY transactions.date_purchased DESC');
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['date_purchased']), htmlspecialchars($myrow['accessory_name']), htmlspecialchars($myrow['accessory_price']), htmlspecialchars($myrow['quantity']), number_format($myrow['**sumhere**'], 2));
}
I tried adding this to my query but keep getting server error
TO_CHAR(CAST(accessory_only_solds.accessory_price AS NUMERIC)* accessory_only_solds.quantity),'999,999.99') AS atotal
!!!was able to solve my problem though i still need to convert the value to euro currency format.
$query = ('SELECT accessories.accessory_name,accessory_only_solds.transaction_id,accessory_only_solds.quantity,accessory_only_solds.accessory_price,transactions.date_purchased,CAST(accessory_only_solds.accessory_price AS NUMERIC)*accessory_only_solds.quantity AS atotal FROM accessory_only_solds
left join accessories on accessory_only_solds.accessory_id = accessories.id
left join transactions on transactions.id = accessory_only_solds.transaction_id
ORDER BY transactions.date_purchased DESC');
How can I achieve the following using only one database query?
$query = "SELECT `email`, `name` FROM `customers`";
$result = mysqli_query($link,$customer_query);
while($row = mysqli_fetch_array($result)){
echo "<p>".$row['name']."</p>";
echo "<ul>";
$query2 = "SELECT `sku` FROM `orders` WHERE `email` = '".$row['email']."'";
$result2 = mysqli_query($link,$query2);
while($row2 = mysqli_fetch_array($result2)){
echo "<li>".$row2['sku']."</li>";
echo "<li>".$row2['cost']."</li>";
}
echo "</ul>"
}
Use INNER JOIN on email field for this:
SELECT c.name, o.sku, o.cost FROM customers c INNER JOIN orders o ON o.email = c.email
Don't forget to add MySQL INDEX on email field for performance.
But this only select customers which have orders.
If you need to select all customers (even which does not have orders) use LEFT JOIN instead. In this case sku and cost fields for users without orders will be null.
Use this picture as hint for this.
I have managed to create a JOIN query for three tables and can successfully echo out the results in a echoed table, here is my code:
<?php
$sql="SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
ORDER BY product_name DESC";
$result = mysql_query($sql);
if (!$result)
{
echo "An error occurred ".mysql_error();
exit;
}
echo "<table border=1>\n<tr><th></th><th bgcolor=\"#DFE8EC\">Name</th><th>Flavors & Size</th><th bgcolor=\"#DFE8EC\">Price</th><th>Price Difference</th><th bgcolor=\"#DFE8EC\"></th></tr>\n";
while ($line = mysql_fetch_array($result)) {
$name = $line["product_name"];
$price = $line["product_price"];
$options=$line["Options_name"];
$difference=$line["Price_diff"];
echo "<tr><td></td><td bgcolor=\"#DFE8EC\">$name</td><td>$options</td> <td bgcolor=\"#DFE8EC\">£$price</td><td>£$difference</td><td bgcolor=\"#DFE8EC\"></td></tr>\n";
}
echo "</table>\n";
?>
My table works but it shows duplicate entries for product_name and I do not know how to remove them.
You have to use a GROUP BY clause in your query like this:
$sql = "SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
GROUP BY product_name
ORDER BY product_name DESC";