Generate duplicate rows in SELECT query (MySql) - php

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>

Related

How do add the array values from mysql database?

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

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.

PHP, SQL - getting fetch where table id = user id and count other table where row is = user id

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

MySQL/PHP query to reverse relationship

I have a mysql table with the following columns:
ID Units
1 1234,6543,9876
2 1234,6543
3 6543
4 9876
5 0987
I would like to reverse the relationship to get an output like this:
Unit IDs
1234 1,2
6543 1,2,3
9876 1,4
0987 5
I was wondering if this could be done in a query or some php, without chunking through with explodes etc?
Using comma-separated lists in SQL is awkward. This is a denormalized design, and SQL is not well suited to work with data in this format.
I would fetch all the data back into PHP and manipulate it there.
$id_per_unit = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$unit_array = explode(",", $row["Units"]);
foreach ($unit_array as $unit) {
$id_per_unit[$unit][] = $row["Id"];
}
}
Something like this:
$query = "SELECT `Unit`, `IDs` FROM `table` ORDER BY `Unit`";
$data = mysqli_query($con, $query);
$prev_unit = '';
while ($row = mysqli_fetch_array($data)) {
if ($prev_unit != $row['Unit']) {
// echo a new row with the new unit and then ID
} else {
// echo just the ID in the same row, this unit is the same as the last one.
}
$prev_unit = $row['Unit'];
}
With only SQL, you can do something like this :
SELECT unit , GROUP_CONCAT(id)
FROM (
SELECT id,substring_index(Units,',',1) AS unit
FROM Table1
UNION
SELECT id,REPLACE(
REPLACE(SUBSTRING_INDEX(Units,',',2),SUBSTRING_INDEX(Units,',',1),'')
,',','') AS unit
FROM Table1
UNION
SELECT id,REPLACE(
REPLACE(SUBSTRING_INDEX(Units,',',3),SUBSTRING_INDEX(Units,',',2),'')
,',','') AS unit
FROM Table1) AS UNITS
WHERE unit != ''
GROUP BY unit
See SQLFIDDLE

Count how many times a specific value is retrievied from a SQL QUERY

MySQL table: name, salary, childrens, brothers, age
I'm trying to retrieve the name of the person who has the max value in salary, childrens and brothers, with age>30. Note: every name is unique.
To do achieve this I loop through all columns whit this array:
$columns = array('salary','childrens','brothers')
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
echo $rows[name];
};
};
Everything works fine, but I would also like to count the amount of times each name is retrived (echoed).
i.e.: Max has the highest salary and the highest amount of brothers, so his name has been retrivied 2 times. Loren only has the highest amount of childrens, so his name has been retrivied 1 time. Jason has never been retrivied, so it's 0 for him.
I tried this:
$i=0;
$columns = array('salary','childrens','brothers')
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
echo "The person who has the max amount of $value is $rows[name]";
$count[$rows[name]] = $i++;
};
};
But it doesn't work as intended, it counting the number of times eache name appears in every columns without taking into account if it has the max value.
Any help would be appriciated.
ps: if you also can improve the code the retrivie the max value I would be grateful.
UPDATE:
The query for each table should output this:
Name salary
Max 2000
--
Name childrens
Loren 4
--
Name brothers
Max 3
The $count array should be:
$count = array('Max'=>2,'Loren'=>1,'Jason'=>0,'etc'=>0);
You used the same counter for all names. Try to split them. Something like that:
$count=array();
$columns = array('salary','childrens','brothers')
foreach($columns as $value) {
$result=mysql_query(
"SELECT `name`, `$value`
FROM table_name
WHERE `age`>30
ORDER BY `$value` ASC
LIMIT 1"
);
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "The person who has the max amount of $value is $rows[name]";
if(!isset($count[$rows[name]]))
$count[$rows[name]] = 0;
++$count[$rows[name]];
};
};
print_r($count);
UPD: And also if you need a row with MAX value, you must use DESC instead of ASC
UPD2: To retrieve all the users, you need also execute SELECT DISTINCT name FROM table_name before previous code and fetch it into array $count[$r['name']] = 0
I'm not sure what you up to , but in programing i will use comparing method to get highest value , but there is another MAX() function in server side language to get greatest value of all record http://www.w3schools.com/sql/sql_func_max.asp
$columns = array('salary','childrens','brothers');
$highest = array(array('salary'=>0,'childrens'=>0,'brothers'=>0));
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
//compare the value of each record if greater then replace
if($highest[$value]<$rows[$value]){
//replace with current highest value and set name into array
$highest[$value]=$rows[$value];
$highest[$value]=$rows[name];
}
};
};
print_r($highest);

Categories