Issue On Updating a Temporary Table Using SQL Select Statement - php

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,

Related

PHP MySQL Query with NOT LIKE specific id

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

PHP, doing mysql update based on loop iteration

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

Need to figure out total hours between check-in and check-out times

I am trying to create a check-in/check-out table in my database. My check-in form works without issue, inserting the time into my database. The problem occurs when I try to check out. Everything is good on the first entry...
But when I try to check in and check out again, this happens...
So far so good, but when I check out...
Currently, my code updates the out column and totalTime column of all matching child_id's.
Here is my code:
// Select the correct child from the database
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$var = $row['id'];
// Insert the check out time for the child
$query = "UPDATE checkinout
SET `out` = :nowTime
WHERE child_id = $var
AND `in` IS NOT NULL";
$statement = $pdo->prepare($query);
$statement->bindValue(':nowTime', date("YmjHis"));
$statement->execute();
// Select check in time for specified child
$sql_inTime = "SELECT `in` FROM checkinout
WHERE child_id = $var";
$inResult = $pdo->query($sql_inTime);
$inRow = $inResult->fetch();
$inTime = strtotime($inRow['in']);
// Select the check out time for specified child
$sql_outTime = "SELECT `out` FROM checkinout
WHERE child_id = $var";
$outResult = $pdo->query($sql_outTime);
$outRow = $outResult->fetch();
$outTime = strtotime($outRow['out']);
// Find total hours
$totalTime = abs($outTime - $inTime)/(60*60);
// Update totalHours column for specified child
$queryTotalTime = "UPDATE checkinout
SET totalTime = :totalTime
WHERE child_id = $var
AND 'out' IS NOT NULL";
$statement = $pdo->prepare($queryTotalTime);
$statement->bindValue(':totalTime', $totalTime);
$statement->execute();
I think you could do all of this in your first update statement using TIMESTAMPDIFF rather than figuring the total time with PHP:
UPDATE checkinout
SET
out = NOW(),
totalTime = TIMESTAMPDIFF(SECOND, `in`, NOW()) / 3600
WHERE
child_id = $var
AND out IS NULL
The criteria WHERE out IS NULL will only update rows that do not have a value in the out column yet.
IF you have MySQL Db THEN sql will be
SELECT TIMESTAMPDIFF(HOUR,in,out) from checkinout;

How to update a value by 1 if the new value inserted into the database clashes with value in the database?

I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '

Pass column value from Select query to another query for insertion in PHP

I was thinking of accomplishing the following as a PHP multi_query. But I'm trying to figure out how to pass the column value from the select query to the insert and update queries.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$query .= "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query .= "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
Problem is, I'm not sure how to pass the link_id value to the other queries. So I'm thinking I might have to rearrange the queries into one, but again, I'm just not sure how to pull that off.
Anyone got any suggestions?
You need to execute select query 1st then use its output to execute 2nd & 3rd query.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$query2 = "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query3 = "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
mysql_query($query2);
mysql_query($query3);
}

Categories