Date is not saving to database - php

I'm creating an appointment plugin, in that for already members and new members are there. in already member area the date entry is not entring into db. but when displaying the variale contains the date. i'm have been checking this from morning but didn't get what is the error. my code is:
$source = mysql_real_escape_string(trim($_POST['apdatetime']));
$datetime = explode(',', $source);
$dates = $datetime[0];
$app_time = $datetime[1];
if($app_time < 12){
$app_session = 'am';
}
else{
$app_session ='pm';
}
$splitdatet = explode('/', $dates);
$yyear = $splitdatet[2];
$mmonth = $splitdatet[1];
$ddate = $splitdatet[0];
$app_date = $yyear . "-" . $mmonth . "-" . $ddate;
if ($_POST['isnewpatient'] == "false") {
//$cSql = "select * from " . WP_contact . " where appointments_c_patientid='" . trim($_POST['ptntid']) . "' ";
$cSql = "select * from " . WP_eemail_TABLE_SUB . " where eemail_patient_id='" . trim($_POST['ptntid']) . "' ";
$data = $wpdb->get_results($cSql);
if (empty($data )) {
$err = 1;
echo "<div id='message' class='aerror'>No such patient ID exists....</div>";
} else {
#$mobile = htmlspecialchars(stripslashes($data[0]->eemail_mobile_sub));
#$email = htmlspecialchars(stripslashes($data[0]->eemail_email_sub));
#$name = htmlspecialchars(stripslashes($data[0]->eemail_name_sub));
$sqlss = "insert into " . WP_Appointments .
" (`appointments_patient_id`,`appointments_date`,`appointments_time`,`appointments_session`,`appointments_reg_date`) VALUES ('" .
mysql_real_escape_string(trim($_POST['ptntid'])) . "','" .
$app_date . "','" .
$app_time . "','" .
$app_session . "',CURRENT_TIMESTAMP() )";
$dd=$wpdb->get_results($sqlss);
var_dump($dd);
echo 'Date:'.$app_date;
// return $suc;
echo "<div id='message' class='asuccess' >Request has been sent for appointment</div>";
}
}
The output of the var_dump is array[0] and $app_date is Date:2014-10-22
The db entry is
appointments_id :393
appointments_patient_id : 9999999999
appointments_date : 0000-00-00
appointments_time : 9:00
appointments_session : am
appointments_reg_date : 2014-09-25 14:21:35
could anyone please point out the mistake in the code if any??

You should convert your string into date object like this:
$app_date = date('Y-m-d',strtotime($app_date));

Related

I am unable to increament id

I searched many stackoverflow questions it didn't help
I want to increment id by fetching last id from MySQL table.
I don't want to do auto increment in MySQL table because already one column is auto incremented.
<?php
include 'db.php';
$created = date('Y-m-d H:i:s');
//$json_data = array();
$message = array();
$error = array();
if ($_GET['vendor_id'] == "") {
$message[] = array("message" => "Values Empty");
} else {
$result = mysqli_query("SELECT loo_id FROM loo_list ORDER BY loo_id DESC LIMIT 1");
if ($result) {
$order_array = mysqli_fetch_assoc($result) or die(mysqli_error());
//echo $order_array['loo_id'];
}
$loo_id = $order_array['loo_id'] + 1;
$sql = "insert into loo_list(loo_id,name,address,geolocation,price,facility_category,facilities,count,accessbility,image,type,category,created_vendor,days,timings,terms_conditions,vendor_approval,created,warning,url,user_ids,overall,admin_approval,updated)values('" . $loo_id . "','" . $_GET['loo_name'] . "','" . $_GET['address'] . "','" . $_GET['loo_location'] . "','" . $_GET['price'] . "','" . $_GET['facility_category'] . "','" . $_GET['facilities'] . "','" . $_GET['count'] . "','" . $_GET['accessbility'] . "','" . $_GET['image'] . "','Offerers','" . $_GET['category'] . "','" . $_GET['vendor_id'] . "','" . $_GET['days'] . "','" . $_GET['timings'] . "','" . $_GET['terms_conditions'] . "','1','" . $created . "','0','','" . $_GET['user_ids'] . "','" . $_GET['overall'] . "','1','" . $created . "')";
$res1 = mysqli_query($db, $sql) or die(mysqli_error());
$message[] = array("message" => "success");
}
$json_data = array("result" => $message);
echo json_encode($json_data);
?>
Try this code.
if(trim($order_array['loo_id']) === ''){
$loo_id = 1;
}else{
$loo_id = intval($order_array['loo_id']) + 1;
}

how to apply array_diff with php and sql

Hi im unable to apply array_diff() for when user edits the stockroom detail to replace with the new result.
Here is the edit function where i call out all the variables via sql.
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
Here is the array_diff() function. There may be unnecessary calling and/or lack of coding..not too sure. This set of codings result in no output. The server basically crashes. Any help on this?
//oldsr is existing stockroom data
//newsr is new stockroom data through edit function
//resultsr is the end result
<?php
$StockroomGetAllDetails = array();
$arr2 = einv_getStockrmDetailFromCode($stockroomCode);
$codearr = explode(",", $arr2['einv_stockrm_code']);
$oldsr = array($codearr);
$newsr = array($codearr);
$resultsr = array_diff($newsr, $oldsr);
if(!count(array_diff($oldsr, $newsr)) && !count(array_diff($newsr, $oldsr))) {
// Arrays are equal
} else {
// Array values are different
echo $resultsr;
}
?>
This code is for redirect.
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
This set of codes able to display the new datas added and removed accordingly :)
$oldCat = $Stockroom["einv_stockrm_cat"];
$oldCatArr = explode(",",$oldCat);
$newCatArr = explode(",",$cat);
//Debugging
//print_r($oldCatArr);
//print_r($newCatArr);
$resultCatAdd = array_diff($newCatArr, $oldCatArr);
$resultCatRemove = array_diff($oldCatArr, $newCatArr);
//Debugging
print_r($resultCatAdd);
print_r($resultCatRemove);

Output stops after a while loop, without using "or die()"

I know there is another question with the same topic, but that question involves the or die() statement. I have the same problem, but i'm not using a or die() statement on my while loop. The answer is probably pretty obvious, but i can't figure it out.
$Dates = "1";
$Select = $mysqli->query("SELECT * FROM ----");
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
$Vals = $Get->fetch_assoc();
if ($Vals != "") {
$TimeIn = $Vals["Time_In"];
$TimeIn2 = explode(":",$TimeIn);
$TotIn = ($TimeIn2[0]*60)+$TimeIn2[1];
$TimeOut = $Vals["Time_Out"];
$TimeOut2 = explode(":",$TimeOut);
$TotOut = ($TimeOut2[0]*60)+$TimeOut2[1];
$TotTime = ($TotOut - $TotIn)/60;
$TotalTime = floor($TotTime) . " Hours " . ($TotTime-floor($TotTime))*60 . " Minutes";
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td>" . $TimeIn . "</td><td>" . $TimeOut . "</td><td>" . $TotalTime . "</td></tr>";
}
if ($Vals == "") {
echo "<tr><td>" . str_replace("_","/",$Dates["Meeting_Date"]) . "</td><td colspan='3' style='background-color: rgba(0,0,0,0.25)'>Did not Attend</td></tr>";
}
}
Anything i put after the while loop, doesn't get executed, even though the while loop only executes 2 times like it is supposed to...
Any ideas are appreciated
This is the problem:
while ($Dates != "") {
$Dates = $Select->fetch_assoc();
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");
When there are no more records, $Dates will be empty (NULL) so the next line will lead to a fatal error.
You can change it to:
while ($Dates = $Select->fetch_assoc()) {
$Get = $mysqli->query("SELECT * FROM " . $Dates["Meeting_Date"] . " WHERE Last_Name='" . $LName . "'");

PHP is updating a database index that doesn't exist

On my main page, when someone signs-in, i have jQuery using AJAX to 'talk' to a PHP file, and the same for when they sign-out. But, when they sign out, it is supposed to update a database index with the time they left. If they database entry for their last name doesn't exist (meaning, they didn't sign-in), it is supposed to return an error. Instead, the PHP file is saying that it IS updating a non-existant database index. i am using IF statements to achieve this. and for some reason it thinks the index does exist. I've checked the database that it is writing to and the indexes it's supposed to be updating don't exist.
Here's my code:
if ($Type == 1)
{
$mysqli = new mysqli("localhost","----","----", "----");
if (!$mysqli)
$Type = 3;
$Select = $mysqli->query("SELECT Time_Out FROM " . $Date . " WHERE Last_Name = '" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_Out'];
if ($Row2 !== "-1") $Type = 4;
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
$Select = $mysqli->query("SELECT Time_In FROM " . $Date . " WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_In'];
$Time2 = explode(":",$Row2);
$Hour2 = $Hour - $Time2[0];
if ($mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'"))
{$Select = $mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row3 = $Row['Hours'];
$Auto += 1;}
$Time3 = 60-$Time2[1];
if ($Hour != 21) $Time4 = $Min;
$Time5 = $Time3+$Time4;
if ($Time2[0]+1 != $Hour)
{$Time5 = $Time5+60;}
$Total = $Time5+intval($Row3);
if ($Type == 1)
{
if ($mysqli->query("UPDATE Names SET Hours = '" . $Total . "' WHERE Last_Name = '" . $LName . "'"))
{$Auto += 1;}
else
{$mysqli->query("INSERT INTO Names (Last_Name, First_Name, Hours) VALUES ('" . $LName . "', '" . $FName . "', '" . $Total . "')");}
}
$mysqli->close();
}
if ($Type == 1) echo "Thank you " . $FName . " " . $LName . " for signing out! See you next time!";
if ($Type == 2) echo "The entered Student ID# is invalid. Please try again!";
if ($Type == 3) echo "An unexpected error has occured. Please try again!";
if ($Type == 4) echo "You have already signed out today!" . $Auto;
if ($Type == 5) echo "You didn't sign in today.";
The UPDATE sql statement will return true, even if it doesn't find any matches (it still runs correctly, it just updates 0 rows).
Change this:
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
To this:
if ($Type == 1) {
if ($mysqli->query("SELECT * FROM " . $Date . " WHERE Last_Name='" . $LName . "'")->num_rows > 0)
$mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'");
else
$Type = 5;
}
You run the select query to first determine if the record exists (if num_rows property of the result is > 0) and based on that either update the record or set your return value to 5.

Filtering MYSQL results by date

We have a script that generate invoice once a month (cron). But we would like to add feature, that we would be able to select date range "from - to" and then generate invoice only for the date selected.
I guess making input fields with calendar pop-up isn't hard, but filtering with PHP is a bit bigger challenge, so if anyone want to take a look at my code and give me some tips, I would be grateful.
function genInvoice($clientID, $orderID=0, $paid=false)
{
if($orderID == 0)
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and status='closed' and tblusers.clientid=" . $clientID;
else
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and tblusers.clientid=" . $clientID . " and tblorders.id=" . $orderID;
$res = full_query($sql) or die(mysql_error());
// If no closed orders uninvoiced, just return
if(!mysql_num_rows($res))
return 0;
$amount = 0;
$orders = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
// print_r($row);
// print "<br><hr>";
$amount += $row['amount'];
$orders[] = $row['id'];
}
$date = date("Y-m-d");
$status = $paid ?'Paid' : 'Unpaid';
$sql = "insert into tblinvoices (clientid, date, duedate, subtotal, total, status) values (" . $clientID . ",'" . $date .
"','" . $date . "'," . $amount . "," . $amount . ",'" . $status . "')";
$res = full_query($sql) or die(mysql_error());
$invoiceid = mysql_insert_id();
$sql = "update tblorders set invoiceid=" . $invoiceid . " where id in (" . implode(",", $orders) . ")";
$res = full_query($sql) or die(mysql_error());
$sql = "select tblorders.id as ReportID, FirstName, LastName, SearchName, CountyID, StateID, bl_orderitems.userid, bl_orderitems.amount, " .
"bl_orderitems.notes from tblorders, bl_orderitems left join bl_search on bl_search.id=packageid where tblorders.id in (" .
implode(",", $orders) . ") and bl_orderitems.orderid=tblorders.id order by tblorders.id,bl_orderitems.id";
$res = full_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
if($row['CountyID'] != 0)
$locale = getCounty($row['CountyID']);
else if($row['StateID'] != 0)
$locale = getState($row['StateID']);
if($row['SearchName'] != "")
$description = mysql_real_escape_string($row['FirstName'] . " " . $row['LastName'] . " " .
$row['SearchName'] . " " . $locale . " (Order #" . $row['ReportID'] . ")");
else
$description = "Search Package: " . mysql_real_escape_string($row['notes'] . " (Order #" . $row['ReportID'] . ")");
$sql = "insert into tblinvoiceitems (invoiceid, userid, type, description, amount, duedate) values " .
"(" . $invoiceid . "," . $row['userid'] . ",'search','" . $description . "','" .
$row['amount'] . "','" . $date . "')";
// print $sql . "<br>";
full_query($sql) or die(mysql_error());
}
sendmessage ('Invoice Created', $invoiceid);
return $invoiceid;
}
not going to look through all that code, but filtering results by a date range is easy.
SELECT id FROM some_table WHERE some_date_field BETWEEN $first_date AND $second_date

Categories