I populated mysql database to html table and now what I want to do is multiply price and quantity in order to find total in order to show in another column. These are all about one table.
"SELECT * FROM orders where user_id = '".$_SESSION['userId']."' ORDER BY order_id DESC";
This is my sql statement. And this is my related php code :
foreach( $result as $data )
{
echo "<tr><td>".$data['order_situation']."</td>
<td>".$data['client_name']."</td>
<td>".$data['client_last_name']."</td>
<td>".$data['city']."</td>
<td>".$data['district']."</td>
<td>".$data['area']."</td>
<td>".$data['address']."</td>
<td>".$data['tel_no1']."</td>
<td>".$data['tel_no2']."</td>
<td>".$data['product']."</td>
<td>".$data['quantity']."</td>
<td>".$data['price']."</td>
<td>".$data['down_payment']."</td>
<td>".$data['explanation']."</td>
<td>".$data['username']."</td>
<td>".$data['date']."</td>
<td>Güncelle</td>
</tr>";
}
"SELECT *, price * quantity AS total FROM orders WHERE user_id = '".$_SESSION['userId']."' ORDER BY order_id DESC";
That should work. Then you can reference the total:
$data['total']
Related
I am trying to get the Total Sum of values from a table. Query works without WHERE Clause, but i need to get the total sum per user. Like user ABC has 100USD and user BDC has 200USD. Here is the code
$PWithdrawls = mysqli_query($con, "SELECT * FROM withdraw WHERE status='Pending'");
$S_NO = 0;
while ($row = mysqli_fetch_assoc($PWithdrawls)) {
$S_NO++;
$posted_by = mysqli_query($con,"SELECT * FROM users WHERE userId=".$row['seller_id']);
$user_ad = mysqli_fetch_assoc($posted_by);
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id']);
$sum_amount = mysqli_fetch_assoc($TotalOrders_Amount);
$sum = $sum_amount['total'];
And here is my call
<td>$<?php echo $sum; ?></td>
Here is DB
Think you have error in your SQL Query:
SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id'] GROUP BY userId LIMIT 1
You need to use GROUP BY to get actual SUM. Also you can get all users with Total, there is no need to second query:
SELECT u.*, SUM(o.amount) AS total
FROM users u
LEFT JOIN orders o ON (o.userId = u.id)
GROUP BY u.userId
This should get you entire user row + total of their orders.
I found the issue. I was calling the wrong variable. userId was not in my table, it was seller_id. So correct query was
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE seller_id=".$row['seller_id']);
Thanks to everyone. I really appreciate.
I want to add the product quantity based on customer name.Here I fetch the values based on customer name and store into array ,now I want to add the quantity values.In select query ,the condition customer having 2+2= 4 qty in separate of two rows How can I add the qty values.
$selectproduct = "SELECT * FROM purchase_item WHERE custname = '$customername'";
$resultselectproduct = $conn->query($selectproduct);
if ( $resultselectproduct ->num_rows >0 )
{
while($rowselectproduct = $resultselectproduct->fetch_assoc())
{
$array[] = $rowselectproduct;
}
}
My database structure:
custname product qty
A ProA 2
A ProB 2
When I run the query based on 'A' customer I got the value as qty value 4
Just change your query and use the SUM() function. Like so:
$query = "SELECT
SUM(qty) AS total
FROM `purchase_item`
WHERE `custname` = '$customername'";
$stmt = $conn->query($query);
$result = $stmt->fetch_assoc();
echo $result['total'];
I thought this would be simple but I'm having a tough time figuring out why this won't populate the the data array.
This simple query works fine:
$queryPrice = "SELECT price FROM price_chart ORDER BY id ASC LIMIT 50";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
But instead I want it to choose the last 10 results in Ascending order. I found on other SO questions to use a subquery but every example I try gives no output and no error ??
Tried the below, DOESN'T WORK:
$queryPrice = "SELECT * FROM (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
I also tried specifying the table name again and using the IN, also doesn't work:
$queryPrice = "SELECT price FROM price_chart IN (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
In both examples my array is blank instead of returning the last 10 results and there are no errors, so I must be doing the subquery wrong and it is returning 0 rows.
The subquery doesn't select the id column, so you can't order by it in the outer query. Also, MySQL requires that you assign an alias when you use a subquery in a FROM or JOIN clause.
$queryPrice = "SELECT *
FROM (SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) x ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice) or die (mysqli_error($conn));
$data = array();
while ($row = mysqli_fetch_assoc($resultPrice)) {
$data[] = $row['price'];
}
You would have been notified of these errors if you called mysqli_error() when the query fails.
Your second query is the closest. However you need a table alias. (You would have seen this if you were kicking out errors in your sql. Note you will need to add any field that you wish to order by in your subquery. In this case it is id.
Try this:
SELECT * FROM (SELECT price, id
FROM price_chart ORDER BY id DESC LIMIT 10) as prices
ORDER BY id ASC
You must have errors, because your SQL queries are in fact incorrect.
First, how to tell you have errors:
$resultPrice = mysqli_query (whatever);
if ( !$resultprice ) echo mysqli_error($conn);
Second: subqueries in MySQL need aliases. So you need this:
SELECT * FROM (
SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) AS a
ORDER BY id ASC";
See the ) AS a? That's the table alias.
Thanks for helping, first I will show code:
$dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESSION['user_id']."' and contracts.customer_contract = ".$_SESSION['user_id']." order by COUNT(contracts.customer_contract) DESC limit $limit, $pocetZaznamu ";
I need to get the lists of users (customers table) ordered by count of contracts(contracts table)
I tried to solve this by searching over there, but I can't... if you help me please and explain how it works, thank you! :) $pocetZanamu is Number of records.
I need get users (name, surname etc...) from table customers, ordered by number of contracts in contracts table, where is contract_id, customer_contract (user id)..
This should do it where is the column name you are counting.
$id = $_SESSION['user_id'] ;
$dotaz = "Select COUNT(`customer_contract`) AS CNT, `customer_contract` FROM `contracts` WHERE `user_id`=$id GROUP BY `customer_contract` ORDER BY `CNT` DESC";
Depending on what you are doing you may want to store the results in an array, then process each element in the array separately.
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
$contracts[$row[1]] = $row[0];
}
foreach ($contracts AS $customer_contract => $count){
Process each user id code here
}
Not sure what you are counting. The above counts the customer_contract for a table with multiple records containing the same value in the customer_contract column.
If you just want the total number of records with the same user_id then you'd use:
$dotaz = "Select 1 FROM `contracts` WHERE `user_id`=$id";
$results = $mysqli->query($dotaz);
$count = mysql_num_rows($results);
I am trying to produce a shopping site where I am selling items that fluctuate in price daily (precious metals). I have a table (products) that will contain a multiplier (something like "1.1") for each product. I basically don't want to have to go into my tables and change the prices of hundreds of items every day. My idea is to create another table where I will simply change the price field with the daily value each day. How can I make the final product price total the multiplier from one table multiplied by the entered daily price from another table. Or, is there a better way than using two tables? Here's the coding so far using just one table with a defined price :
if (isset($_GET['id'])) {
//Connect To Mysql Database
include"storescripts/connect_to_mysql.php";
$id = preg_replace('#[^0-9]#i','',$_GET['id']);
//Use This VAR To Check To See If This ID Exists, If Yes Then Get Product
//Details, If No Then Exit Script and Give Message Why
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
//Get All The Product Details
while ($row = mysql_fetch_array($sql)) {
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y",strtotime($row["date_added"]));
}
} else {
echo "That Item Does Not Exist";
exit();
}
} else {
echo "Data To Render This Page Is Missing";
exit();
}
mysql_close();
So, how about a response that isn't the usual mysql_* related pedantry?
In the following schema I've broken the materials table away from the listed price so that they can be stored according to date. You might find this useful for records and/or invoicing.
TABLE products
prod_id INT PK
prod_name VARCHAR
prod_price DECIMAL
mat_id INT FK
...
TABLE materials
mat_id INT PK
mat_name VARCHAR
...
TABLE material_pricing
mat_id INT FK PK
mat_price_date DATE PK
mat_price_factor DECIMAL
SELECT
p.prod_name,
p.prod_price * pr.mat_price_factor AS 'cur_price'
FROM products p INNER JOIN materials m
ON p.mat_id = m.mat_id
INNER JOIN material_pricing pr
ON m.mat_id = pr.mat_id
WHERE mat_price_date = TODAY()
I'm trying to think of a way to change the query to grab the last defined material_pricing entry for the relevant material, but I'm having a tough time lining up the data for a subquery...
edit: this should do the trick
SELECT
p.prod_name,
p.prod_price * pr.mat_price_factor AS 'cur_price'
FROM products p INNER JOIN materials m
ON p.mat_id = m.mat_id
INNER JOIN (
SELECT p1.*
FROM material_pricing p1 INNER JOIN (
SELECT mat_id, MAX(mat_price_date) 'mat_price_date'
FROM material_pricing
WHERE mat_price_date <= $target_date
GROUP BY mat_id
) p2
ON p1.mat_id = p2.mat_id
AND p1.mat_price_date = p2.mat_price_date
) pr
ON p.mat_id = pr.mat_id
Where $target_date in the innermost subquery would be replaced by either today's date, the TODAY() mySQL function, or the date of the invoice being displayed.