jQuery causing my php to break - php

I'm working on an online booking system, so I have a php script that receives a date and will output an array of possible timeslots that are free on that date. I'm trying to make it so that when closing the datepicker it sends the variables to the file and retrieves the result. At the moment the submit button also leads to the php file, and will show me available slots when I choose a date. The php part works, but when I add events to the datepicker it won't submit any variables to the php file. I think this is also the cause that when I add another load.('input_date.php'); I get the full timeslot list caused by the if(isset... Can anyone tell me why jQuery is ruining my variable posting? Thanks in advance..
$(document).ready(function() {
$("#dates").load('input_date.php');
$("#datepicker").datepicker({onClose: function() {
$.post("input_date.php", $('#datepicker').serialize());
alert(1);
}});
});
This is the php file:
<?php
include('connection.php');
error_reporting(0);
$treatment = $_POST['treatment'];
$bookdate = $_POST['bookdate'];
if(isset($treatment) && isset($bookdate)){
$exp = explode("-", $bookdate);
//determine what day of the week it is
$timestamp = mktime(0,0,0,$exp[1],$exp[0],$exp[2]);
$dw = date( "w", $timestamp); // sun0,mon1,tue2,wed3,thur4,fri5,sat6
echo $dw."weekday"; //week day
echo"<br/>";
//find bookings with same date
$q = mysql_query("SELECT BOOK_SLOT_ID FROM BOOKINGS WHERE BOOK_DATE='$bookdate'");
//make array of booking slots
$array1 = array();
while ($s = mysql_fetch_array($q)) {
$array1[] = $s['BOOK_SLOT_ID'];
}
$q2 = mysql_query("SELECT SL_ID FROM SLOTS");
//make array of all slots
$array2 = array();
while ($s2 = mysql_fetch_array($q2)) {
$array2[] = $s2['SL_ID'];
}
//remove bookings from all slots
$arr_res = array_diff($array2, $array1);
//make selectable options of results
echo "<SELECT>";
foreach($arr_res as $op){
$r = mysql_query("SELECT SL_TIME FROM SLOTS WHERE SL_ID='$op'");
$q3 = mysql_fetch_array($r);
echo "<OPTION value=".$op.">".$q3['SL_TIME']."</OPTION>";
}
echo "</SELECT>";
}else{
$else = mysql_query("SELECT * FROM SLOTS");
echo "<SELECT>";
while($array_else = mysql_fetch_array($else)){
echo "<OPTION value=".$array_else['SL_ID'].">".$array_else['SL_TIME']."</OPTION>";
}
echo "</SELECT>";
}
?>

I believe it is because you have this line of code:
$('#datepicker').serialize()
This should be changed to the id of the form not the datapicker. In your PHP you are trying to get two seperate values:
$treatment = $_POST['treatment'];
$bookdate = $_POST['bookdate'];
Right now you are just sending the value of the input field #datepicker.

Related

How to save query in multidimesional array?

I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']

PHP Beginner - What am i doing wrong?

First of all, im a beginner so please excuse me if i don't mention things that could be important.
I have Sellers, that are in different countries in the world. Each country belong to a continent. Im trying to:
get the seller name
Fetch Database to see in what countries (China,Italy,Germany...) he offers his goods.
Then fetch another database and see in what continents (ASIA,EU) belong each country
Store the countries (Italy,Germany) to a variable $country_eu and $country_asia (China). So later i will add this variables to update database fields.
if($continent == 'ASIA') is not included in the code YET since i take one by one the steps. I want to make first EU work, then i figure out the rest.
include_once('../db.php');
session_start();
$seller_name = $_SESSION['seller_name'];
echo $seller_name;
if (!empty($_POST['flag_image'])){
$flags_array = $_POST['flag_image'];
$flags_string = implode(",",$flags_array);
}else{
$flags_string = '';
}
$cont_eu = '';
// Assign Flags to Continents
foreach ($flags_array as $flag_image){
$qry_find_flag_continent = " SELECT continent FROM flags WHERE flag_image = '$flag_image' ";
$result = $dbdetails->query($qry_find_flag_continent);
while($row = mysqli_fetch_array($result)) {
$continent = $row["continent"];
if ($continent == 'EU') {
$cont_eu .= $flag_image;
}
}
echo $cont_eu;
The problem with my code is that when i echo $cont_eu is giving me just 1 result(Germany) and not the EXPECTED (Italy,Germany)
Thank you all for your precious time and attempts to help. Here is the new code that works great.
include_once('../db.php');
session_start();
$seller_name = $_SESSION['seller_name'];
echo $seller_name.'<br>';
if (!empty($_POST['flag_image'])){
$flags_array = $_POST['flag_image'];
$flags_string = implode(",",$flags_array);
} else {$flags_string = '';}
// Assign Flags to Continents
foreach ($flags_array as $flag_image){
$qry_find_flag_continent = " SELECT continent FROM flags WHERE flag_image = '$flag_image' ";
$result = $dbdetails->query($qry_find_flag_continent);
while($row = mysqli_fetch_array($result)) {
$continent = $row["continent"];
if($continent == 'EU'){ $eu_flags_array[] = $flag_image;}
}
}
print_r($eu_flags_array); //Gives me Array ( [0] => Germany.png [1] => Italy.png )

Query missing months in which we haven't sold anything?

My query is:
$sql="SELECT COUNT(`Variant`) AS tsold, MONTHNAME(`sold_date`) AS mname FROM `vehicle_sold` GROUP BY MONTH(`sold_date`) ";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row["mname"],"---", $row["tsold"],"<br />";
}
which gives me the below result:
January---1
February---2
March---7
April---11
May---6
July---1
There are no sales in June so what I want is the query to return "June---0" for example. If it also shows the next months up to December it's ok. I'd like the following output:
January---1
February---2
March---7
April---11
May---6
June---0
July---1
Aug---0
Sept---0
Oct---0
Nov---0
Dec---0
Use an array of month names -
$months = array('January', 'February', ..., 'December');
Generate and array with the data returned from database -
while($row = mysqli_fetch_array($result)) {
$data[$row["mname"]] = $row["tsold"];
}
And print them accordingly -
foreach($months as $value) {
echo $value.' - '. (array_key_exists($value, $data) ? $data[$value] : 0) . '<br/>';
}
I assume you have actually no data in the database if you did not sell anything. Hence its a bit hard to generate a month without info.
You want an array with all the months, corresponding with the amount of sales.
I would suggest you make something like this:
Prepare an array with the months with all the values on 0 as default (you can make this array list 'nicer', but just now as example).
$data['March'] = 0;
$data['April'] = 0;
Now you can iterate like you did
while($row = mysqli_fetch_array($result)) {
$data[$row["mname"]] = $row["tsold"];
}
If it does not get filled by the database, the value would still be 0. Otherwise it gets overwritten by the database value.

Catogerizing by year in mysql and php

I am trying to write a program of photoalbums in simple PHP, but i want to make it a little more advanced then i used to do.
Usually i wrote it like this:
<?php $query = mysql_query("SELECT year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
$query2 = mysql_query("SELECT albumName, url FROM photo WHERE year = '".$year."'");
while($album = mysql_fetch_object($query2)){
echo "".$albumName."<br>";
}
} ?>
As you would understand it's really bad to have two while loops in one, so i want to do it differently. I want to learn how to do this better. The thing is, I don't know a name for this so it's difficult to search on this subject. Is there anyone able to hand me a snippet of code, a source or something to get me on the way?
Thank you so much.
You could do
<?php
$year = ''; // create a generic variable that will hold the album year
$query = mysql_query("SELECT albumName, url, year FROM photo ORDER BY year"); // Sort by year
while($album = mysql_fetch_object($query)) {
if($album->year != $year){ // check if $album->year is the same as the $year value
echo $album->year."<br>"; // if not the same echo the year
}
$year = $album->year; // set the $year value to the $album->year
echo "".$album->albumName."<br>";
}
?>
What if you do this:
<?php $query = mysql_query("SELECT albumName, url, year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
echo "".$albumName."<br>";
}
?>
What would be wrong?
Now your code might produce an album more than one times, if there are many albums per year.

DATE_FORMAT omit seconds

Trying to bring back a time id and time itself into listbox stored in mysql. run the sql in myadmin runs fine, try it in the code ... not so fine. bring back indefined index error.
thanks.
<?php
function get_times(&$a_class, &$db){
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i')
FROM tb_time24
ORDER BY timeId
EOT;
if ($query_result = mysql_query($str_sql, $db)) {
while ($a_result = mysql_fetch_assoc($query_result)) {
$a = array();
$a['timeId'] = $a_result['timeId'];
$a['tSel'] = $a_result['tSel'];
array_push($a_class, $a);
}
}
else {
$i_result = mysql_errno($db);
}
if(isset($i_result)){
return $i_result;
}
}
?>
calling it here.
Start Time:<select name="startTime" id="StartTime">
<?php
$a_class = array();
get_times($a_class, $db_handle);
foreach ($a_class as $a_class) {
print "<option value='".$a_class['timeId']."'>{$a_class['tSel']}</option>\n";
}
?>
</select>
Give a name to the formatted column:
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i') tSel
FROM tb_time24
ORDER BY timeId
EOT;
Otherwise the keys in the array returned by mysql_fetch_assoc would be timeId and DATE_FORMAT(tSel, '%H:%i').

Categories