I have two tables in my MySQL database:
1 named "stock"
id | product | qty
----------------------
1 | 1 | 15
----------------------
2 | 1 | 20
And the second one named "orders"
id | product | qty | stock_id
----------------------------
1 | 1 | 7 | 1
-----------------------------
2 | 1 | 8 | 1
So, before register a new "order", I need to verify which "stock.id" has free product to sell, with SUM all existent orders.qty and subtract it to stock.qty, for this example I'm going to insert a new order of 10 pieces of product with id '1' ($new_order = '10' (pieces):
for each stock.id { SUM(orders.qty) as total | then verify if 'total' >= $new_order | if(total >= $new_order){select that stock.id} if don't { continue looking for an stock.id with free product for sale } }
Hoping to make myself known, I need your help to structure MySql query from PHP for that function.
UPDATE
I've solved with this double query:
<?
$queryL = "SELECT id,unidades,producto FROM stock WHERE `producto` = '$producto'";
$resultL = $mysqli->query($queryL);
/* array asociativo */
while($rowL = mysqli_fetch_array($resultL, MYSQLI_ASSOC))
{
$id_lote = $rowL['id'];
$unidades = $rowL['unidades'];
$queryD = "SELECT SUM(cantidad) as total FROM `pedidos` WHERE `lote` = $id_lote";
$resultD = $mysqli->query($queryD);
/* array asociativo */
if($rowD = mysqli_fetch_array($resultD, MYSQLI_ASSOC)){
$ventas = $rowD['total'];
$disponible = $unidades - $ventas;
if($disponible >= $cantidad){ $lote = $id_lote; }
}
}
?>
Can someone help me simplifying this?
Related
-----------------------------------------------------
| id | posts_id | users_id | ratings |
-----------------------------------------------------
| 1 | 7 | 20 | 5 |
| 2 | 8 | 20 | 3 |
| 3 | 7 | 21 | 4 |
-----------------------------------------------------
Table name: mytable
\I want to make sure that ratings between posts_id and users_id are matched on the same column.
$query = $conn->query("SELECT ratings FROM mytable WHERE posts_id=7 and users_id=20");
$row = $query->fetch_array();
echo $row['ratings'];
This query does not work. I know there must be something wrong.
I want to get results: 5
What is the best query to show ratings?
----------------UPDATE-----------------------------
Sorry, my first problem lies with the connection, and now it is resolved.
But now there is a new problem.
I want to display the total sum of the rating results.
My new code
$Rate = $conn->query("SELECT * FROM mytable WHERE posts_id=7");
while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'] + $Rated['ratings'];
}
For example on posts_id=7
Here I expect 5 + 4 = 9
But my code results exactly 54 + 54
How to fix this code?
For the updated question, this code should be work. We can use sum() function. Check here sum() function
$Rate = $conn->query("SELECT sum(ratings) as ratings FROM mytable WHERE posts_id=7");
while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'];
}
I have a Mysql database table named as_items as below:
-----------------------------------------------------------------------
| itemid | item_type | item_number | item_title | item_content |
-----------------------------------------------------------------------
| 1 | 1 | 2 | First Item | The first item |
| 2 | 2 | 3 | Second Item | The second item |
| 3 | 3 | 5 | Third Item | The third item |
| 4 | 3 | 1 | Forth Item | The forth item |
| 5 | 2 | 4 | Fifth Item | The fifth item |
-----------------------------------------------------------------------
I would like to get multiple queries from the same column which in this case is "item_type" using my php script. In my php script the reference value could one or multiple based on the existence of the character "," in it which my code check for.
if (strpos($itemtypes, ',') !== false) {
$items = explode(',',$itemtypes);
$query = "SELECT ";
foreach ($items as $item){
$query .= "(SELECT * FROM as_items WHERE item_type=$item ORDER BY item_number ASC) AS j$item, ";
}
$result = mysql_query($query) or die(mysql_error());
} else {
$songbook = $songbookids;
$result = mysql_query("SELECT * FROM as_items WHERE item_type= $itemtypes ORDER BY item_number ASC") or die(mysql_error());
}
Take into account the query is based on the php final output. When i use the multiple query I get an error from the server as "Operand should contain 1 column(s) "
NOTE:
Please note the reference item is from my other code where when 2 or 3 item types are selected its output is like "itemtype,itemtype,itemtype" but when only one is selected it is just plain as "itemtype".
Instead of doing the query(s) like that, try this:
$query = "SELECT * FROM as_items WHERE item_type IN ('".str_replace(',', '\',\'', $itemtypes)."') ORDER BY item_number ASC";
$result = mysql_query($query);
This should replace your whole thing, no need to check if , is in the string.
Table (showing only relevant columns)
ID | product_name | stock | stock_level
6 | test name | 5 | 4
7 | test name 2 | 3 | 9
I have a lot more rows in my database.
In MYSQL, how can I get every row where the stock value is less than the stock_level value?
Like this?
SELECT * FROM table WHERE stock < stock_level
That would return row2 (stock = 3, stock_level= 9) but not row1 (stock = 5, stock_level= 4).
<?php
$result = mysqli_query($myslqi, "SELECT * FROM table WHERE stock < stock_level")) {
....
}
I need to count how many times in ripeted the same values in different columns for the same id..
I'll try to clarify with an example:
TABLE:
+-----+-----+-----+-----+-----+
| id | d01 | d02 | d03 | d04 |
+=====+=====+=====+=====+=====+
| 1 | A | A | B | B |
+-----+-----+-----+-----+-----+
| 2 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 3 | B | B | A | A |
+-----+-----+-----+-----+-----+
| 4 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 5 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 6 | B | A | A | A |
+-----+-----+-----+-----+-----+
I need to know how many times the value "B" is repeating for any person (ID)..
Is that possible to do that? RESULTS
+-----+-----+-----+
| id | count B |
+=====+=====+=====+
| 1 | 2 |
+-----+-----+-----+
| 2 | 0 |
+-----+-----+-----+
| 3 | 2 |
+-----+-----+-----+
I was thinking to use the function "SUM" but I have no idea how to display just the single ID.
Thanks in advance, hope the question is clear enough!
If there are only four columns:
SELECT id, (d01 = 'B') + (d02 = 'B') + (d03 = 'B') + (d04 = 'B')
FROM tablename
No there are 31 columns
That's a problem which you can solve in two ways:
Repeat the condition for the other 27 columns :)
Normalize your structure so that each value is dependent on both the id and a numeric value that represents a calendar.
The PHP way
You can also fetch all columns and let PHP solve this for you:
$res = $db->query('SELECT * FROM tablename');
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row) {
$id = $row['id'];
unset($row['id']); // don't count the id column
$count = count(array_keys($row, 'B', true));
printf("ID %d: %d\n", $id, $count);
}
Since you seem to be using mysql_*:
// SHOW COLUMNS returns all the columns and constrains of the defined table
// We only need the column names so we will be later calling it by 'Field'
$sql = mysql_query("SHOW COLUMNS FROM table"); //your table name here
$val_to_count = 'B'; //value to count here
$id = 1; //id to search for
$new_sql = 'SELECT id, ';
// In this loop we will construct our SELECT query using the columns returned
// from the above query
while($row=mysql_fetch_array($sql)){
if($row['Field']!='id'){
$new_sql .= ' ('.$row['Field'].' = "'.$val_to_count.'") + ';
}
}
//Removing the last "+ " produced in the select query
$new_sql = rtrim($new_sql,"+ ");
$new_sql .= ' as count FROM table WHERE id = '.$id; //table name here again
// so $new_sql now has an output like:
// SELECT ID, (d01 = 'B') + (d02 = 'B') ... WHERE id = 1
$sql2 = mysql_query($new_sql);
//executing the constructed query with the output below
while($row2=mysql_fetch_array($sql2)){
echo 'ID - '.$row2['id']."<br>";
echo 'Count - '.$row2['count']."<br>";
}
Note:
mysql_* is deprecated, please consider to migrate to mysqli_*
My goal is to work out the total value of stock.
Table name: Stock
Column names: cost(representing an items cost), s_count(representing quantity).
cost multiplied by s_count would give the total value of each item.
how would i go about multiplying these columns together, then totaling the results for all rows together to get the total amount?
$selectstock=$db->query("SELECT * FROM stock");
$result = $db->query('SELECT SUM(s_count) AS value_sum FROM stock');
$rowes = mysql_fetch_assoc($result);
$sum = $rowes['value_sum'];
$result2 = $db->query('SELECT SUM(amountfailed) AS value_sum FROM stock');
$rowes2 = mysql_fetch_assoc($result2);
$sum2 = $rowes2['value_sum'];
$uparts = mysql_num_rows($selectstock);
$value = // how do i do this?
print "<h3>Stock overview..</h3><br />
<div><p><br />
Amount of unique parts in stock: {$uparts}<br />
total quantity of stock: {$sum}<br />
Current value of all stock: {$value}<br />
Amount of parts failed: {$sum2}<br />";
if this was the table below...
example:-
| id | cost | quantity |
| 1 | 20 | 5 |
| 2 | 5 | 10 |
| 3 | 2 | 2 |
| 4 | 10 | 1 |
| 5 | 7 | 3 |
then $value would need to be 20*5 + 2*10..etc
so $value would return 185.
Is this what you want?
SELECT SUM(s_count*cost) AS value_sum
FROM stock