PHP and Postgresql product - php

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');

Related

Prestashop compare data from one table to another then print in tpl

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

SQL query working in phpmyadmin but not in php

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 .....

Select all customers and each customer's total orders

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.

How do I use two mysql tables in one statement

So, I've put in a favourite images table, and I can't figure out how to get it working properly
Basically, this is the setup:
ImageFavs
FavID, UserID, ImgID
ImageList
ImgID, SiteID
I'd like it to select 20 or so images from the favourites table, but only ones that match the siteid in the image list table
This is the code I have at the moment, but it dawned on me it'd select 20 images from favourites, then only display them if the matching site was actually checked.
#select matching sites
for($i=0;$i<count($sites)-1;$i++){
$siteinfo = explode("-",$sites[$i]);
$siteid = $siteinfo[0];
$sitegroup = $siteinfo[1];
$selection[$siteid]="exists";
if($i!=0){
$sqlextra .= " OR ";
}
else{
$sqlextra = "AND (";
}
$sqlextra .= "SiteID='".$siteid."'";
}
if(!empty($sqlextra)){
$sqlextra .= ")";
}
else{
$sqlextra = "AND SiteID='-1'";
}
#show favourites
if($_GET['f']==1){
$sql="SELECT * FROM ImageFavs WHERE UserID='".$_SESSION['User_ID']."' AND Active = '1' ORDER BY RAND() LIMIT 20";
#(rand is just me being lazy, eventually I'll figure out how to separate it onto pages)
$result = mysql_query($sql);
$num = mysql_numrows($result);
if($num>0){
while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
if(empty($sqlextra2)){
$sqlextra2 = " AND (";
}
else{
$sqlextra2 .= " OR ";
}
$sqlextra2 .= "ImgID='".$row['ImgID']."'";
}
$sqlextra2 .= ")";
}
}
#don't show favourites
if(empty($sqlextra2)){
$sqlextra2 = " ORDER BY RAND() LIMIT 20";
}
$sql="SELECT * FROM ImageList WHERE Valid='1' ".$sqlextra.$sqlextra2;
This output $sql from this seems like it could be so much neater though, an example of it is like this
SELECT * FROM ImageList WHERE Valid='1' AND (SiteID='6') AND (ImgID='5634' OR ImgID='8229' OR ImgID='9093' OR ImgID='5727' OR ImgID='7361' OR ImgID='5607' OR ImgID='7131' OR ImgID='5785' OR ImgID='7339' OR ImgID='5849' OR ImgID='7312' OR ImgID='5641' OR ImgID='8921' OR ImgID='7516' OR ImgID='7284' OR ImgID='5873' OR ImgID='8905' OR ImgID='7349' OR ImgID='7392' OR ImgID='8725')
Also, while I'm here, would there be a non resource heavy way to count the number of favourites for a user per website?
It's not for anything big, just messing around on a personal website to see what I can do.
You can INNER JOIN your two tables to get the results you want. INNER is used when you want results from both tables. It's best to use aliases to keep your tables straight.
SELECT l.*
FROM ImageFavs f
INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE l.SiteID = [your site ID]
AND f.UserID='" . $_SESSION['User_ID'] . "'
AND f.Active = '1'
ORDER BY RAND() LIMIT 20
To get a count by site you can use GROUP BY. I think this should get you that count
SELECT COUNT(f.ImgID)
FROM ImageFavs f
INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE f.UserID='" . $_SESSION['User_ID'] . "'
AND f.Active = '1'
GROUP BY l.SiteID
you want to use "JOIN"
SELECT * FROM ImageFavs LEFT JOIN ImageList ON ImageFavs.ImgID = ImageList.ImgID WHERE ImageList.SiteID = <your_site_id>
This works-
//Assuming $site_id contains the site ID/
$query = "select *.IF from ImageFavs as IF, ImageList as IL where IL.ImgId = IF.ImgId and IL.SiteId = $site_id LIMIT 20"

How can i remove duplicate values from an Echoed table?

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";

Categories