Feedback for php code - php

hello guys I am subtracting one unit from a variable called Eppl which resides in a Database and this is working perfectly. However I have added a condition which is that the value of the variable Eppl must be greater than 0 before the subtraction takes place. My code is as follows:
$id = $_GET["id"];
$result = $mysqli->query("SELECT `CreatedBy` AND `Eppl` FROM `events` WHERE `Eid` = '$id'");
$row = $result->fetch_assoc();
$sessionid = $row['CreatedBy'];
$notlesszero = $row['Eppl'];
$zero = 0;
//echo $result;
session_start();
if ((!($_SESSION['login_user'] == $sessionid)) && ($notlesszero>0)){
$mysqli->query("UPDATE `events` SET `Eppl` = `Eppl` - 1 WHERE `Eid` = '$id'");
$mysqli->query("INSERT INTO `eventusers` (EventID, UserID) VALUES ('{$id}', '{$_SESSION['login_user']}')");
header("location:view.php");
//}
}
The if branch works without the second condition $notlesszero>0...
What is the problem here?
Thanks for your help

Instead of querying the database to get the value of the field and then checking it, why not just add a condition on the UPDATE?
$mysqli->query("UPDATE `events` SET `Eppl` = `Eppl` - 1 WHERE `Eid` = '$id'");
to
$mysqli->query("UPDATE `events` SET `Eppl` = `Eppl` - 1 WHERE `Eid` = '$id' AND `Eppl` > 0");

The first query is wrong after you added Eppl to it. Fields to select should not be separated by AND. So
SELECT `CreatedBy` AND `Eppl` FROM
should be
SELECT `CreatedBy`, `Eppl` FROM
This is something you could have caught by inspecting the error information after executing the query, or at least by inspecting $row after changing the query. :-p

Related

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;

PHP MYSQL Update multiple fields including DATETIME field

I can update the field 'delivered' from 0 to 1 no problem but when I try to update 'delivered_time' nothing happens in the database. This may be to do with the way I am writing the code but If anybody could help I would really appreciate it, thanks!
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = '{$date->format('Y-m-d H:i:s')}' AND `delivered` = 1 WHERE `order_id` = $order_id");
}
I have also tried this but this did not work either
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = NOW() AND `delivered` = 1 WHERE `order_id` = $order_id");
}
My MYSQL database is set to have 'delivered' defined to 0 and is stored as an INT value. The 'delivered_time' field is stored as a DATETIME value in the database.
, not AND as the field separator; AND is used in WHERE clauses
UPDATE `listings`
SET `delivered_time` = '{$date->format('Y-m-d H:i:s')}',
`delivered` = 1
WHERE `order_id` = $order_id
Try this code
<?php
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = NOW(),`delivered` = 1 WHERE `order_id` = ".$order_id);
}
?>

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

MySQL MyISAM race condition

The function has next structure:
$q = 'LOCK TABLES table1 WRITE;';
mysql_query($q);
$q = 'select id from table1 where is_delete = 0 limit 1;';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
$q = 'UNLOCK TABLES;';
mysql_query($q);
I locking all tables, but queries run parallel.
How fix this?
Check whether you're getting any MySQL errors on the LOCK TABLES query:
$q = 'LOCK TABLES table1 WRITE';
$r = mysql_query($q) or die(mysql_error());
However, if this is all you are doing, you can also simply write:
UPDATE `table1 SET `is_delete` = 1 WHERE `is_delete` = 0 LIMIT 1
which does not require any locks at all. Of course, this will only work if the data from your first query is not being processed in any way, and if it doesn't really matter which row you are updating, as long as it's one in which is_delete is set to 0. This is what the code you posted does, too, but it's not immediately obvious to me what you would want to use this code for :)
More generally, if you are using the default InnoDB storage engine for your MySQL table, you may want to look into SELECT ... FOR UPDATE:
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
You could write:
$q = 'select id from table1 where is_delete = 0 limit 1 for update';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
See also: http://www.mysqlperformanceblog.com/2006/08/06/select-lock-in-share-mode-and-for-update/

Categories