I have a php file that works up to a certain point but I need a bit of help on the loop for doing a MySQl Insert.
The following preforms a SELECT and then stores the Order ID for all records that have a order_status of 'S'. This works perfectly, printing each appropriate order ID.
I then push those affected ORder IDs to an array so that I can keep them stored for various functions.
//Query for checking all records in order_status
$orderCheck = "
SELECT
order_id,
order_status
FROM order_status
";
$result = mysqli_query($mysqlConn, $orderCheck);
$order_ids = array();
//loop results to gather order IDs and store them
while ($row = mysqli_fetch_array($result))
{
$order_id = $row['order_id'];
if ($row['order_status'] == "S")
{
array_push($order_ids, $order_id);
}
}
//print_r($order_ids);
//This does indeed print the correct order Ids
The following portion needs some work and I'm not quite sure what to do here. I'm iterating and foreach of those iterations I have an update, but i fear the syntax is incorrect on the update and I don't know if I'd need to do another array in here.
//This is where I'm stuck//
//Now I need to iterate through those orderIDs and update is_placement to 1, since it's a bit column, and udpate date_updated to curdate()
for($i=0; $i<count($order_id); $i++) {
$sql = "UPDATE order_status SET is_placement = '1' and date_updated = curdate() WHERE order_id = '$order_id'"; //I don't believe this syntax is correct
}
Basically, I need to preform a mysql update for each iteration of the previously stored $order_id array.
Any ideas or suggestions/guidance are much appreciated.
UPDATE:
output of the array:
[287] => 11605809
[288] => 11605817
[289] => 11605825
[290] => 11605863
[291] => 11605869
[292] => 11605870
[293] => 11605875
[294] => 12605471
[295] => 12605643
[296] => 12605715
[297] => 12605778
[298] => 12605817
It makes little sense to ask MySQL for all the orders, and then select manually those with status S.
Better:
// Select only orders in status S.
$orderCheck = "SELECT order_id FROM order_status WHERE order_status = 'S';"
$result = mysqli_query($mysqlConn, $orderCheck);
$order_ids = array();
while ($row = mysqli_fetch_array($result)) {
$order_ids[] = $row['order_id'];
}
Now you want to update those records. If you do it one by one, you do:
foreach ($order_ids as $order_id) {
$sql = "UPDATE order_status SET is_placement = 1, date_updated = DATE(NOW()) WHERE order_id = '$order_id';";
// EXECUTE
}
A faster way would be (I'm not adding quotes, assuming that order ids are numeric, but if they aren't things get a bit more complicated) to put all order ids together and use the IN syntax:
$bunchOfOrders = implode(',', $order_ids);
$singleQuery = "UPDATE order_status SET is_placement = 1, date_updated = DATE(NOW()) WHERE order_id IN ({$bunchOfOrders})";
But you could have done all this in MySQL too:
$orderUpdate = "UPDATE order_status SET is_placement = 1, date_updated = NOW() WHERE order_status = 'S';"
$result = mysqli_query($mysqlConn, $orderUpdate);
Since the above does not change the order status from S, you can then also run $orderCheck and retrieve the order-ids involved, if necessary.
To be sure that nothing untoward happens, I would also wrap the whole operation inside a transaction.
Another twist
What if we have to run a series of different modifications depending on some condition (mutually exclusive, of course)?
We can do this with a map, as long as we use deterministic functions and no modification changes the conditions below (so, you can't change order_status in any of the "recipes", or it would influence those that come after):
$todo = array(
"order_status='S'" => "is_placement = 1, date_updated = DATE(NOW())",
"order_status='K'" => "is_placement = 2, date_updated = DATE(NOW())",
"order_status='L'" => "owner='NOBODY'",
"o_s='X' AND a=12" => "note='A random condition'",
// We can also supply a "what to do if none of the above":
"DEFAULT" => "note='THIS RECORD DOES NOT MATCH'",
);
$else = array();
foreach ($todo as $when => $then) {
if ('DEFAULT' !== $when) {
$else[] = "({$when})";
} else {
// "ELSE" means when no other condition is matched.
// i.e. NOT when1 AND NOT when2 AND NOT when3...
// which is equivalent to NOT ( when1 OR when2 ... )
$when = "NOT (" . implode(' OR ', $else) . ")";
}
$sql = "UPDATE order_status SET {$then} WHERE {$when};";
// Execute $sql.
}
What you could use is a foreach() statement:
foreach($order_ids AS $order_id) {
$sql = "UPDATE order_status SET is_placement = '1', date_updated = curdate() WHERE order_id = $order_id";
// execute the query here
}
While you are using information from data contained in your table you should consider learning about prepared statements MySQLi
I would change the initial query so you don't have to loop through anything more than once.
Try this:
//Query for checking all records in order_status
$orderCheck = "
SELECT
order_id,
order_status
FROM order_status
WHERE order_status = 'S'
";
$result = mysqli_query($mysqlConn, $orderCheck);
$order_ids = array();
//loop results to gather order IDs and store them
while ($row = mysqli_fetch_row($result))
{
$sql = "UPDATE order_status SET is_placement = '1' and date_updated = curdate() WHERE order_id = '$row[0]'";
}
Related
Hello I have working mssql php insert codes but i want to get inserted id return with string ($newid) My codes under.
OrderId = int and Primary Key not null
$querysf = "SELECT TOP 1 OrderId FROM Orders ORDER BY OrderId DESC";
$resultsf = mssql_query($querysf);
//Getting manually latest OrderId but this is not good :(
while($rowsf = mssql_fetch_array($resultsf))
{
$newid = $rowsf["OrderId"];
$newid = $newid + 1;
echo("$newid"); //Getting manually latest OrderId but this is not good :( Some one can easily take this id and will be mistakes
$mydate = date("Y-m-d");
$ready = mssql_fetch_assoc(mssql_query("SET IDENTITY_INSERT Orders ON; SELECT CONVERT(NCHAR(100),NEWID()) as Ok"));
$queryer = mssql_query("INSERT INTO Orders (OrderId, CustomerId, DeliveryDate, OrderState,Signature,UserName,special_field,rowguid) VALUES ('$newid', '$CustomerId', '$mydate 00:00:00.000', '1',NULL,'$UserName',NULL,'".$ready['Ok']."')");
$close = mssql_fetch_assoc(mssql_query("SET IDENTITY_INSERT Orders OFF;"));
}
I'm trying my best here to find a solution for my issue, but with no luck.
I have a SELECT in my PHP to retrieve some products information like their IDs.
mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
Every time I run this SELECT, I get 5 rows as result. After that I need to run a DELETE to kill those 5 rows using their id_item in my WHERE condition. When I run, manually, something like:
DELETE FROM mytable WHERE id_item IN (1,2,3,4,5);
It works! But my issue is that I don't know how to make an array in PHP to return (1,2,3,4,5) as this kind of array from my SELECT up there, because those 2 other conditions may vary and I have more "status = 0" in my db that can't be killed together. How am I suppose to do so? Please, I appreciate any help.
Unless there is more going on than what is shown, you should never have to select just to determine what to delete. Just form the DELETE query WHERE condition as you would in the SELECT:
DELETE FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'
But to answer how to get the IDs:
$result = mysqli_query($link, "SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
while($row = mysqli_fetch_assoc($result)) {
$ids[] = $row['id_item'];
}
$ids = implode(',', $ids);
Move to PDO or MySQLi now.
First of all you shouldn't be using mysql_query anymore as the function is deprecated - see php.net
If this is a legacy application and you MUST use mysql_query you'll need to loop through the resource that's returned by mysql_query, which should look something like this
$result = mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$idArray = array();
while ($row = mysql_fetch_assoc($result)) {
$idArray[] = $row['id_item'];
}
if(count($idArray) > 0) {
mysql_query("DELETE FROM mytable WHERE id_item IN (" . implode(',' $idArray) . ")");
}
As said before, probably you don't even need a select. But you can do a select, grouping all ids together, and then put it in the delete IN.
$result = mysql_query("SELECT GROUP_CONCAT(DISTINCT id_item) AS ids FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$ids = mysql_result( $result , 0, 'ids') ; // 1,2,3,4,5
if ($ids != ""){
mysql_query("DELETE FROM mytable WHERE id_item IN (" . $ids . ")");
}
GROUP_CONCAT
Can you please take a look at this code and let me know why I am not able to UPDATE a temporary table on $query3
$query = "CREATE TEMPORARY TABLE IF NOT EXISTS `charts_ecolo_yes` (
SET `econo_sum_projects` = (SELECT COUNT(`project`) FROM `ecolo-cu-yes` WHERE c_1000=1 ),
SET `econo_sum_powerline` = (SELECT SUM(`powerline_length`) FROM `ecolo-cu-yes` WHERE c_1000=1 ),
SET `econo_sum_roads` = (SELECT SUM(`road_length`) FROM `ecolo-cu-yes` WHERE c_1000=1 ),
SET `econo_sum_cost` = (SELECT SUM(`cost_per_year`) FROM `ecolo-cu-yes` WHERE c_1000=1 ),
SET `econo_sum_penstlock` = (SELECT SUM(`penstlock` FROM `ecolo-cu-yes` WHERE c_1000=1 )
";
$con->query($query3);
$query4 = "SELECT * FROM `charts_ecolo_yes`" ;
$results = $con->query($query4);
if ($results) {
$row = $results->fetch_array(MYSQLI_NUM);
$row = array_map('floatval', $row); // Convert strings to numbers
echo json_encode($row);
}
Here is the sample result page, which you can see even after running the $con->query($query3); I am still getting default values(100) at last 5th columns.
Thanks
Your UPDATE query syntax is wrong, you don't need SET for all column. It should be
$query3= " UPDATE `charts_ecolo_yes`
SET `econo_sum_projects` = some_value,
`econo_sum_powerline` = some_other_value,
I'm trying to get the total number of product sales in each category, although the database structure being used doesn't really seem to lend itself to this.
I've gotten it to the point where I have the IDs of products (it's own table) in a category (another table) that have only been purchased (still another table). So looping through the category, I choose the IDs in the orders table and try to count the rows. I end up with the item count per item, but any way I try to merge and count them up them doesn't work.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
while($row_active_accounts = mysql_fetch_row($res_active_accounts)){
print_r($row_active_accounts);
}
};
An example that print_r gives for a specific category that only had 3 items sell, but some items sold more than once:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 1 )
This is correct in that three items sold, sold those number of times.
And array_sum doesn't work on this. I can't seem to do anything to get those numbers to add up. I'm trying to count just specific rows and really don't care about the data in them for the final result.
I understand SQL calls within loops are a bad idea, but this is an admin area script that won't be run often.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL ); while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
$int_total = 0;
while($row_active_accounts = mysql_fetch_row($res_active_accounts) {
foreach($row_active_accounts as $i)
$int_total += $i;
}
// Use $int_total for total value
Some like this should do the trick for your if I understand you correctly.
Try this
$query = mysql_query("select distinct(pgroup) from test") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo $row['pgroup']."=>";
$query1="SELECT count(*),pname FROM `test` where pgroup='$row[pgroup]' group by pname ";
$result1=mysql_query($query1) or die(mysql_error());
$rows1=mysql_num_rows($result1);
while($row_sub=mysql_fetch_array($result1)) {
$query2 = "select * from test where pname = '".$row_sub['pname']."'";
$res2=mysql_query($query2) or die(mysql_error().'errror here');
$row2 = mysql_num_rows($res2);
echo $row_sub['pname']."=".$row2."<br/>";
}
}
I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";