How do add the array values from mysql database? - php

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

Related

Generate duplicate rows in SELECT query (MySql)

Is it possible in SELECT * FROM generate duplicate rows?
In some rows, I have a filed called quantity. When quantity is more than 1, I would like to duplicate that record.
example
item quantity
book 1
phone 3
pencil 1
what I would like to get in recordset is
book
phone
phone
phone
pencil
Is that possible?
You can just add a result for every 'quantity' e.g:
$query = "SELECT * FROM books";
$originalResult = $conn->query($sql);
$modifiedResults = array();
while($row = $originalResult->fetch_assoc())
{
array_push($modifiedResults, $row);
for($i=0; $i< $row.quantity; $i++)
{
array_push($modifiedResults, $row);
}
}
Possible solution is to use REPEAT
SELECT REPEAT(item, quantity) FROM <table_name> WHERE <condition>
and if you want in one string use GROUP_CONCAT
SELECT GROUP_CONCAT(REPEAT(item1, quantity)) FROM <table_name> WHERE <condition>

How to multiply two column values and write it to another column?

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']

how to convert multiple row data into array and subtract it from another array?

I am fetching multiple rows from my data base like,
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
$delete = mysql_fetch_array($resultt);
$std_delete_array = explode(',', $delete['id']);
the value of id in database is like 4,5,6 in different rows but it is giving only first value 4.
Another array I am fetching is,
$query="SELECT * FROM events where id='$district'";
$showdata=mysql_query($query) or die(mysql_error());
$user=mysql_fetch_array($showdata);
$std_fulllist_array = explode(',', $user['std_list']);
the value in database is 4,5,6,8. But in single coloumn, so it is giving proper output. now I want to subtract $std_delete_array from $std_fulllist_array.
I am using following code,
$values = array_diff($std_fulllist_array, $std_delete_array);
which is only subtracting first value of $std_delete array.
strucutre of table student_info is
id ! name ! District
4 a panipat
5 b panipat
6 c panipat
strucutre of table events is
id ! district ! std_list
1 panipat 4,5,6
2 karnal 4,7,8
3 chandigarh 5,6,7
You are saying the value of id in database is like 4,5,6 in different rows
that means your table is look like
id district
-- ---------
4 abc
5 def
6 geh
8 ijk
so your first query is fetching multiple records.
EDIT
So your query would be
$ret_ = array();
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_array($result)) {
echo $row['id'];
$ret_[] = $row;
}
}
print_r($ret_);

SUM of columns while grouping by other column

So this is the structure of my MySQL table that I wanna work this out with:
ID type category_id amount
12 Expense 3 963.39
13 Expense 5 1200.50
14 Expense 3 444.12
15 Expense 5 1137.56
..............................
Desired output:
1407,41 (for category_id = 3)
2338,06 (for category_id = 5)
....... (and for other category_id)
What I get now:
1407,41 (only for category_id = 3)
My query does not add or display the sum of other category_id.
This is the query I am trying:
$query = "SELECT SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
$expense_count = mysqli_fetch_array($expense_query);
echo $expense_count[0];
Been stuck with this for the last couple of days. Any help is very much appreciated. Thank you!
You're only calling mysqli_fetch_array() once. You need to call it in a loop to get all the totals. You should also include the category ID in the SELECT list.
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
echo "{$row['TotalAmount']} (for category_id = {$row['category_id']}<br>\n";
}
The query here works. It's just that you only select the first result from the $expense_count variable. $expense_count[1] will return the second category listed, $expense_count[2 will return the third one, ect...
Try echo implode(" <br>", $expense_count);
Have a nice day.

Create an array of different Id´s with the Id that are POST´ed in a select

I have a SELECT name="idproduct" inside a FORM and its OPTION VALUE is the Id of the product that I have SELECTED. I would like to make an array in PHP with the Id´s of the products that I have SELECTED one after another.
EXAMPLE:
$idproducts=(1, 2, 14, 24, 8)
On the top of the table I have the SELECT and first I choose one product. Then I choose another one etc.... I need the Id´s of the choosen products in that select because down the page I have a table where I want to show the products I have selected at the top.
$sql='SELECT id_product,
nameproduct,
situation,
quantity
FROM product
WHERE id_product = "'.$idproducts.'"';
Somebody would explain me how can I make the array with the posted Id´s of the SELECT?
$sql='SELECT id_product, nameproduct, situation, quantity
FROM product WHERE id_product IN (.$idproducts.)';
Assuming your <select> is multi select, you could loop through the array like so to build the query string:
$sql='SELECT id_product,
nameproduct,
situation,
quantity
FROM product
WHERE 1';
foreach( $_POST['idproducts'] as $k=>$v ){
$sql .= ' OR id_product = ' . $v;
}
If $idproducts is an array:
$sql='SELECT id_product, nameproduct, situation, quantity FROM product
WHERE id_product IN ('.implode(',',$idproducts).')';
Here is a function I like to use to turn arrays of data in to or based where queries.
$sql_stub = "SELECT id_product, nameproduct, situation, quantity FROM product";
$sql = orQuery($sql_stub, array("id1", "id2"), "id_product");
function orQuery($sql_stub, $array, $field){
//START WHERE CLAUSE
$where = "WHERE ";
//ADD DATA TO THE WHERE CLAUSE
foreach($array as $data){
$where = $where." ".$field." = '".$data."' OR ";
}
//CHECK THAT THE WHERE CLAUSE IS MORE THAN JUST WHERE
if($where!="WHERE "){
//REMOVE THE TRAILING OR
$where = substring($where, strlen($where)-4);
//APPEND TO SQL_STUB
$sql_stub = $sql_stub.$where;
}
return $sql_stub;
}

Categories