I have a scheduling system
I have a query to create a error if the date and time has already been scheduled
my problem is i have multiple room and if i create a schedule in one room if it is the same with the other room it wont add
function save_schedule(){
extract($_POST);
$data = "";
foreach($_POST as $k=> $v){
if($k != 'id'){
if(!empty($data)) $data.=", ";
$data.=" {$k} = '{$v}'";
}
}
if(strtotime($datetime_end) < strtotime($datetime_start)){
$resp['status'] = 'failed';
$resp['err_msg'] = "Date and Time Schedule is Invalid.";
}else{
$d_start = strtotime($datetime_start);
$d_end = strtotime($datetime_end);
$chk = $this->conn->query("SELECT * FROM `schedule_list` where (('{$d_start}'
Between unix_timestamp(datetime_start) and unix_timestamp(datetime_end)) or ('{$d_end}'
Between unix_timestamp(datetime_start) and unix_timestamp(datetime_end))) ".(($id > 0) ? "
and id !='{$id}' " : ""))->num_rows;
if($chk > 0){
$resp['status'] = 'failed';
$resp['err_msg'] = "The schedule is conflict with other schedules.";
}else{
if(empty($id)){
$sql = "INSERT INTO `schedule_list` set {$data}";
}else{
$sql = "UPDATE `schedule_list` set {$data} where id = '{$id}'";
}
$save = $this->conn->query($sql);
if($save){
$resp['status'] = 'success';
$this->settings->set_flashdata('success', " Schedule successfully saved.");
}else{
$resp['status'] = 'failed';
$resp['sql'] = $sql;
$resp['qry_error'] = $this->conn->error;
$resp['err_msg'] = "There's an error while submitting the data.";
}
}
}
return json_encode($resp);
}
can anyone help me in this query
$chk = $this->conn->query("SELECT * FROM `schedule_list` where (('{$d_start}'
Between unix_timestamp(datetime_start) and unix_timestamp(datetime_end)) or ('{$d_end}'
Between unix_timestamp(datetime_start) and unix_timestamp(datetime_end))) ".(($id > 0) ? "
and id !='{$id}' " : ""))->num_rows;
assembly_hall table
schedule_list table
Aside from the SQL injection problems, I see a couple of issues:
Your query should be only looking for conflicts for the assembly_hall_id it will be inserting; as is, it looks for conflicting schedules for any assembly hall.
Your conflict check is incorrect; if a hall is reserved for 1pm-2pm and someone tries to reserve it for 12pm-3pm, you don't detect it, because neither the new start nor end is in the reserved range. Correct conflict checking is done with:
least(datetime_end, new end value) > greatest(datetime_start, new start value)
Related
I'm creating PHP API for my Android application which will be used to scan QR codes. Part of that API is checking if scanned code is valid and can be scanned in a certain moment.
Whole checking part is a stored procedure in MariaDB database which is just executed by PHP script. Execution part in PHP is looking like this:
$sql = "CALL someProcedure('qr_code', #out); ";
$sql .= "SELECT #out AS `out`;";
if($conn->multi_query($sql)) {
while ($conn->more_results()) {
$conn->next_result();
}
$rs = $conn->store_result();
$row = $rs->fetch_assoc();
$odp = $row['out'];
if (!empty($rs)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
There are 4 results of that stored procedure:
scanned code doesn't exist,
scanned code is not an package (it is an articles code)
scanned code cannot be delivered just yet
scanning was successful
Now, when there is something wrong with the code, PHP part executes without a problem but if scanning is successful I would get a timeout (doesn't matter if it's default 30 seconds or 5 minutes).
The reason there is a timeout (I think) is that when scanning is successful there are some loops executed in Stored Procedure which may be returned in resultsets and choke PHP script ALTHOUGH when I execute that Stored Procedure in DBeaver (with exact same query as in PHP) there is no problem.
So, my question is what I can do about it? Removing the while loop in PHP script above makes the script execute without a problem (but I can't get the out parameter value.
Why not do two queries instead of one multi-query?
This is a respond to a comment by Rick James
Here's modified code:
$sql = "CALL ".$storedProcedure."(".$columns."); ";
$sql2 = "SELECT #out AS `out`;";
if($conn->query($sql)) {
if($rs = $conn->query($sql2)) {
$row = $rs->fetch_assoc();
$odp = $row;
if (!empty($odp)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
And mysql error while executing the script:
{"success":0,"message":"Commands out of sync; you can't run this command now"}
The problem is when executing the second query.
I finally got it. All I had to do is to store results in every while loop iteration.
Here's how it looks now.
$sql = "CALL someProcedure('qr_code', #out); ";
$sql .= "SELECT #out AS `out`;";
if($conn->multi_query($sql)) {
while ($conn->more_results()) {
$rs = $conn->store_result();
$conn->next_result();
}
$rs = $conn->store_result();
$row = $rs->fetch_assoc();
$odp = $row['out'];
if (!empty($rs)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I have been fighting with this. Hope this helps others as well. I have a page for an invoice display, it populates and displays perfectly, I want to do major DB changes with the "Pay" button.
If there is an OrderIn_id, it should update the order_instate column of paid to "Yes", or if there is an OrderOut_id it should update the order_outstate column of paid to "Yes", there can be an instance where there is one or the other Id's or could have both. Then it inserts values into an invoice table.
The insert works perfectly, I am not getting any error messages, and it goes to the next page as if it all works, but it does NOT update the order tables to paid = "Yes", it keeps the field the same. Can you advise me of what I may not be seeing in this code. This is the php code that is called when the submit button is pressed.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($row['orderIn_id'])) {
$orderIn_id = $row['orderIn_id'];
$ip_id = $row['ip_id'];
$orderIn_quantity = $row['orderIn_quantity'];
$orderIn_total = $row['orderIn_total'];
$orderIn_paid = "Yes";
$changeVal="UPDATE order_instate
SET user_id = '$user_id', ip_id = '$ip_id', orderIn_quantity = '$orderIn_quantity', orderIn_total = '$orderIn_total',
orderIn_paid = '$orderIn_paid'
WHERE orderIn_id = '$orderIn_id'; " ;
$changeCheck=mysqli_query($dbhandle, $changeVal)
or die(mysqli_error($dbhandle));
}
if (mysqli_affected_rows($dbhandle) == 1) {
echo "<span class = 'errorlog'><br />The Order update was successful.<br /></span>";
}
if(isset($row2['orderOut_id'])) {
$orderOut_id = $row2['orderOut_id'];
$op_id = $row2['op_id'];
$orderOut_quantity = $row2['orderOut_quantity'];
$orderOut_total = $row2['orderOut_total'];
$orderOut_paid = "Yes";
$changeVals="UPDATE order_outstate
SET user_id = '$user_id', op_id = '$op_id', orderOut_quantity = '$orderOut_quantity', orderOut_total = '$orderOut_total',
orderOut_paid = '$orderOut_paid'
WHERE orderOut_id = '$orderOut_id'; " ;
$changeCheck2=mysqli_query($dbhandle, $changeVals)
or die(mysqli_error($dbhandle));
}
if (mysqli_affected_rows($dbhandle) == 1) {
echo "<span class = 'errorlog'><br />The Order update for out of state was successful. <br /></span>";
}
$invoice_total = 0;
$invoice_total = $gtotal;
$invoice_shipped = "No";
$add ="INSERT INTO invoice(user_id, invoice_total, invoice_shipped)
VALUES ('$user_id', '$invoice_total', '$invoice_shipped')";
$addCheck=mysqli_query($dbhandle, $add)
or die(mysqli_error($dbhandle));
if($addCheck == NULL){
echo "<span class = 'errorlog'><br />Your Payment was not successful. Please try again. <br /></span>";
} else {
header("location: userOrders.php");
}
}
?>
I am using the following code to determine if a user is signed in or not, I have set the field 'first_sign_in' to 0 in the mysql table but I am still receiving the echo 'already signed in for the start of the day when actually it should return 'not signed in for the start of the day'
Could someone help me on where I am going wrong here.
$time = date('h:i:s', time());
$checkifstaffexists = mysql_query("SELECT user_id from staff WHERE pin = 3012");
if (!$checkifstaffexists) {
die('Failed.');
}
if (mysql_num_rows($checkifstaffexists) > 0) {
$checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
if ($checkfirstsignin == 0) {
echo 'not signed in for start of day</br>';
$checksignintime = mysql_query("SELECT " . date("d") . " " . "_start from staff WHERE pin = 3012");
if($checksignintime > $time) {
echo 'user is late';
$addtolatetable = mysql_query("INSERT INTO lates (user_id, date_time) SELECT user_id, '2014-05-15 12:00:00' from staff WHERE pin = 3012");
//$signuserin = mysql_query(" ");
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
} else {
echo 'user is not late';
//$signuserin = mysql_query(" ")
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
}
} else {
echo 'already signed in for start of day</br>';
$checkifuserisinourout = mysql_query("SELECT status from staff WHERE pin = 3012");
if ($checkifuserisinourout == 0) {
echo 'user is not signed in so we will sign you in';
//$signuserin = mysql_query(" ");
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
} else {
echo 'user is signed in so we will sign you out';
//$signuserout = mysql_query(" ");
$changestatustoout = mysql_query("UPDATE `staff` SET status=0 WHERE pin = '3012'");
//redirect
}
}
} else {
//The user cannot be found
echo 'User doesn\'t exist.';
}
with the line
$checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
you get back a resource that you have to use to fetch data, for example:
$row = mysql_fetch_assoc($checkfirstsignin);
and with this array ($row) you can work further.
Please check the manpage for mysql_query for further reading...
and since this will be posted all the time: mysql_* methods are deprecated, please use mysqli or pdo.
if ($checkfirstsignin == 0)
Will always equal true if the query succeeds even if there are no matching results.
You need to use mysql_fetch_row or mysql_fetch_array to do that.
while($row = mysql_fetch_assoc($checkfirstsignin)){
if($row['first_sign_in']==0){
//do something
}
}
Write this var_dump( $checkfirstsignin );
after this line $checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
And you will see the returned result is an array, so it is always false on the next if check.