How can I pick a single date from my date range picker?
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filtertable.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
here's my query coming from the date range picker:
query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN '".$_POST["from_date"]."' AND
'".$_POST["to_date"]."'
If u I try to select 2 same dates it doesn't work because of this
$query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN '".$_POST["from_date"]."' AND
'".$_POST["to_date"]."' ";
I need to add a statement which is
`$query ="SELECT *
FROM gsm2 WHERE setTime = '".$_POST["from_date"]."' OR
'".$_POST["to_date"]."' ";
how can I add this condition to the old query?
Instead of between you can just do the manual:
SELECT *
FROM gsm2
WHERE setTime >= :fromTime AND setTime <= :toTime
Notice how I'm using placeholders there? You should too, and also use prepared statements.
In practice if you are using MySQLi you could do:
$db = mysqli_connect(...); //Your connection
$stmt = $db->prepare("SELECT * FROM gsm2 WHERE setTime >= ? AND setTime <= ?");
$from = filter_input(INPUT_POST, "from_date");
$to = filter_input(INPUT_POST, "to_date");
$stmt->bind_param("ss", $from, $to);
$stmt->execute();
$res = $stmt->get_result();
// Do things like $res->fetch_assoc or similar here
Note that if your $_POST data are dates but your SQL fields are DATETIME then you might need to do some sort of casting e.g. do WHERE DATE(setTime) >= ? AND DATE(setTime) <= ?
I may be wrong (as I'm not equipped to test it right now), but this should work:
$query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN ".$_POST['from_date']." AND ".$_POST['to_date'].";
Going by the assumption that your initial query was right, but your PHP code was throwing up some errors as you are using loads of (' and ")'s.
Mainly posting to point out that you are accepting user input and throwing it straight into a SQL query. I am honestly surprised that in 2018 on StackOverflow, so many users in this category are placing PHP input variables directly into a SQL query and then executing it without checking the input to ensure that it is valid first.
Input such as 1; DROP TABLE gsm2; could have the potential to delete your entire table. I'm not sure what kind of server-side firewalls are in place to deal with this type of attack, but it's terrible practice all the same.
Related
The goal I am trying to accomplish is a work-around method to store a PHP variable in MySQL. One of the columns in this table is storing words such as {{literature}}, or {{coffee}}, etc.
My second table has the name of the person who has that job in a group.
What is the best way to use str_replace to change {{chips}} to the variable that is stored in the second screenshot after it has been echo'd out in PHP?
This is my php code that selects the content from sys_format (first image):
// Select THIRD associated meeting format item based on selected meeting
$sql = "SELECT * FROM sys_format WHERE sys_meeting_related = '$sys_current_meeting' AND sys_format_order_id = '3'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<h4>" .$row['sys_format_name']. "</h4>
<blockquote class='topmargin bottommargin'>
<p>" .$row['sys_format_content']. "</p>
</blockquote>";
}
}
The problem i am facing with PHP's str_replace() function is that the parameters it has to follow won't work for the method I am calling the content. The content is question to be replaced is coming from the above select statement and is dynamic so I cannot specifcy the string to be searched.
Javascript's replace() functions seems to have similar limitations, unless I'm misunderstanding you need to define the string to be searched. Same issue there.
Did I miss something? Thank you all in advance for taking the time to read my post.
Thanks to the above comment from #AbraCadaver, I was able to make this work. (Yes I realize these statements are vulnerable to sql injection.. This is only for practice purposes.
$sql = "SELECT * FROM sys_commits WHERE sys_commit_name = 'Secretary' AND sys_meeting_related = '$sys_current_meeting'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$secretary_commit_assignee = $row['sys_commit_assignee'];
}
}
// Select FIRST associated meeting format item based on selected meeting
$sql = "SELECT * FROM sys_format WHERE sys_meeting_related = '$sys_current_meeting' AND sys_format_order_id = '1'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sys_format_name = $row['sys_format_name'];
$sys_format_content = $row['sys_format_content'];
}
}
echo str_ireplace("{{secretary}}", "$secretary_commit_assignee", "$sys_format_content");"
<h4>$sys_format_name</h4>
<blockquote class='topmargin bottommargin'>
<p>$sys_format_content</p>
</blockquote>";
Hopefully this helps someone down the road.
Cheers to all.
I am trying to make a car booking system using a jquery datepicker. I have the date picker, I have dates in a database(manually inserted in WAMP SERVER phpMyAdmin) that highlight those dates as pre-booked dates (Cursor disabled in css on mouse over) so you can't book those ones.
I'm at the point of assembling all my parts but have become stuck on the last bit of how to store the dates. It seems from what I've read, that storing a bunch of dates in one row is a no no (plus I haven't managed to do it).
So, should I store a start and end date for each client on the one DB table row and generate the in between dates when the page/datepicker loads?
If this approach how do I get and then join each row (many clients) of dates together?
Or should I generate the in between dates and then store all the dates in a separate table with the client id when the datepicker selects start & end?
Could someone help with the correct approach and php code to get me there. I already have the mysqli connection etc.
My DB columns at present are start_date & end_date in tabledates_from_to. My datepicker uses this format 2021-04-15 and the array needed looks like this '2021-04-15','2021-04-16','2021-04-17' to highlight the dates.
Seems like you have a 1:n relation between clients/customers and bookings. So yes you should store them in separate tables according to database normalization rules.
Assume you have a table clients (primary key client_id) and bookings, which replaces your dates_from_to table (with foreign key client_id) you can do the following JOIN:
SELECT *
FROM clients
JOIN bookings
USING (client_id)
WHERE booking_date = '2021-04-05'
For the next part I take the example array. Here is example code to insert one row for every day:
$dates = ['2021-04-15','2021-04-16','2021-04-17'];
// $pdo contains a connected DB instance
$stmt = $pdo->prepare('INSERT INTO bookings (client_id, booking_date) VALUES (?, ?)');
foreach ($dates as $day) {
$stmt->execute([1, $day]);
}
As an alternative you could use first and last day of the period and store everything in one row by replacing booking_date column by start_date and end_date.
Here is the version with mysqli and start/end date (from docs):
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->prepare('INSERT INTO bookings (client_id, start_date, end_date) VALUES (?, ?, ?)');
// iss means (i)nteger, (s)tring and (s)tring parameter
$stmt->bind_param('iss', 1, '2021-04-15', '2021-04-17');
$stmt->execute();
Hope this keeps you going.
After about a month I have the date-picker working, storing all dates in DB on their own row.
It picks a start date & end date from two datepickers.
Creates/produces all the dates in between then inserts all those separate dates into the database each date in it's own row in PHP.
Then redirects to same page & highlights all DB dates & disables them so no one can select already booked dates.
I have copied different bits of code from this site and manipulated it a little & at present I'm very happy with the hybrid outcome.
This is running on a WAMP server.
Below is my code to help other amateurs like me.
<?php
$servername = "localhost:3308";
$username = "root";
$password = "";
$dbname = "datepicker_test_outputs";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date FROM insert_datesarray";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$for_JS_date = null;
// output data of each row
while($row = $result->fetch_assoc()) {
$php_array_dates = date('Y-m-d',strtotime($row["date"]));
$for_JS_date .= "'".$php_array_dates."'".",";
$correct_date_format = substr($for_JS_date, 0, -1);
}
if($_SERVER["REQUEST_METHOD"]=="POST"){
$start_date = $_POST["from"];
$end_date = $_POST["to"];
$dateentry = array();
// populate $dateentry array with dates
while (strtotime($start_date) <= strtotime($end_date)) {
$dateentry[] = date("Y-m-d", strtotime($start_date));
$start_date = date ("Y-m-d", strtotime("+1 day", strtotime($start_date)));
} // end while
// loop through $dateentry and insert each date into database
foreach($dateentry as $entry) {
$my_inserted_dates =("INSERT INTO insert_datesarray
(date) VALUES('{$entry}')")
or die(mysqli_error());
$result = mysqli_query($conn,$my_inserted_dates);
if($result == false)
{
echo "<script>alert('BOOKING IS NOT SUCCESS - PLEASE CONTACT ADMINISTRATOR'); </script>";
}
else
{
/* Header location to refresh the page & load booked dates */
header('Location: '.$_SERVER['PHP_SELF']);
}
} die;
// end foreach
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery UI DatePicker</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.ui-highlight .ui-state-default{
background: red !important;
border-color: red !important;
color: white !important;
cursor:not-allowed !important;
}
</style>
<script type="text/javascript" language="javascript">
var dates = [<?php echo $correct_date_format;?>];
/*var dates = ['2021-04-05','2021-04-15','2021-04-25','2021-04-30'];*/
jQuery(function(){
jQuery('input[id=from]').datepicker({
dateFormat: 'dd-mm-yy',/*CN Changes date format. Remove if required CN*/
changeMonth : true,
changeYear : true,
minDate: 0 ,/*Mindate disables dates before todays date*/
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(dates.indexOf(currDate) >= 0){
return [true, "ui-highlight", 'Date Already Booked'];
}else{
return [true];
}
}
});
})
</script>
<script type="text/javascript" language="javascript">
var dates = [<?php echo $correct_date_format;?>];
/*var dates = ['2021-04-05','2021-04-15','2021-04-25','2021-04-30'];*/
jQuery(function(){
jQuery('input[id=to]').datepicker({
dateFormat: 'dd-mm-yy',/*CN Changes date format. Remove if required CN*/
changeMonth : true,
changeYear : true,
minDate: 0 ,/*Mindate disables dates before todays date*/
beforeShowDay : function(date){
var y = date.getFullYear().toString(); // get full year
var m = (date.getMonth() + 1).toString(); // get month.
var d = date.getDate().toString(); // get Day
if(m.length == 1){ m = '0' + m; } // append zero(0) if single digit
if(d.length == 1){ d = '0' + d; } // append zero(0) if single digit
var currDate = y+'-'+m+'-'+d;
if(dates.indexOf(currDate) >= 0){
return [true, "ui-highlight", 'Date Already Booked'];
}else{
return [true];
}
}
});
})
</script>
</head>
<body>
<p id="dateFrom"></p>
<p id="dateTo"></p>
<form action="" name="form1" method="post">
<label for="from">From</label>
<input type="text" id="from" name="from"onchange="getFromDate()">
<label for="to">to</label>
<input type="text" id="to" name="to"onchange="getToDate()">
<input name="book" type="submit" value="Book">
</form>
</body>
</html>
I have a HTML table that gets populated with values retrieved from the connected database table 'Attendance' on page load with the session UserID of who's logged in.
To adjust this table, I'm using a collection of filters created with <form> and inputs as such:
For Workspace No. it takes all the Workspace number's in the file and lists them as options in the dropdown so they are pre-populated values.
The attendance checkboxes correlate to a checkbox with a value of 1 for Present and 0 for Late
So far I have only the filters for ID search and the Workspace No. written out but I'm unsure if this is the way to go as the SQL query will still have the WHERE ... WorkID = ? even if there has been no selection made for Workspace No. rather than being omitted from the query?
$('.apply').click(function () {
if ($('#idSearch')[0].checkValidity()){ #checks if the form is valid
$('#idSearch').submit();
}
if ($('#chosenWork') != ""){
$('#WorkIDSearch').submit(); #submits the form to POST the Workspace No.
}
});
...
include("config.php");
if (isset($_POST['reqID'])){ #checks if the ID search input field (reqID) has been submitted
$userid = $_POST['reqID'];
} else{
$userid = $_SESSION['sess_user_id'];
}
if (isset($_POST['chosenWork'])){ #checks if the dropdown for Workspace Number (chosenWork) has been selected
$chosenwork = $_POST['chosenWork'];
}
if (isset($_POST['chosenWork']) && isset($_POST['reqID'])){ #checks if both are selected
$chosenwork = $_POST['chosenWork'];
$userid = $_POST['reqID'];
}
$stmt = $conn->prepare("SELECT Number, ID, Date, Log_Time, WorkID, Att_Type FROM Attendance WHERE ID = ? AND WorkID = ?";
$stmt->bindParam("ii", $userid, $chosenwork);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
My desired output is that any of these filters can be applied independently or combined to adjust the WHERE clause of the SQL query.
You can try it this way:
$query = "SELECT Number, ID, Date, Log_Time, WorkID, Att_Type FROM Attendance";
$chosenwork = null;
if (isset($_POST['reqID'])){ #checks if the ID search input field (reqID) has been submitted
$userid = $_POST['reqID'];
$query .= " WHERE ID = ?";
} else{
$userid = $_SESSION['sess_user_id'];
$query .= " WHERE ID = ?";
}
if (isset($_POST['chosenWork'])){ #checks if the dropdown for Workspace Number (chosenWork) has been selected
$chosenwork = $_POST['chosenWork'];
$query .= " WorkID = ?";
}
if (isset($_POST['chosenWork']) && isset($_POST['reqID'])){ #checks if both are selected
$chosenwork = $_POST['chosenWork'];
$userid = $_POST['reqID'];
$query = "SELECT Number, ID, Date, Log_Time, WorkID, Att_Type FROM Attendance WHERE ID = ? AND WorkID = ?";
}
$query .= ";";
$stmt = $conn->prepare($query);
(isset($userid)) ?? $stmt->bind_param("i", $userid);
(isset($chosenwork)) ?? $stmt->bind_param("i", $chosenwork);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
It is hard to help debug without more info, but several things I noticed:
Looking at the error, it says the problem is either syntax but it could be the result of an old version. Have you checked your sql version? Prepared statements were introduced in v4.1.
You haven't shown your html or js validation, but since you are telling sql to expect integers, are you absolutely sure your variables are integers? To be sure, add a 0 to $userid and $chosenwork (e.g. $userid = $userid + 0;) before binding them
For security, validating posted form data should be done on the server not client -- it is trivial to circumvent client-side js validation
The null coalescing operators in Serghei Leonardo's answer will only work if you are using php7 or higher. Also, I am not familiar with his usage of it so I may be wrong, but it looks to me it will return $userid and $chosenwork if they are set and only bind if isset($userid) or isset($chosenwork) are null (i.e. if $userid or $chosenwork are null), which would be backwards from what you want. See another explanation here. This might not work, but try changing it to:
(!isset($userid) ?? $stmt->bind_param("i", $userid));
(!isset($chosenwork) ?? $stmt->bind_param("i", $chosenwork));
I'm trying to fetch data using jquery but I'm having a problem with htmlentities because it shows " instead of " in jquery.
Here is my code for input text:
<input type="text" name="material_name[]" id="material_name<?=$x?>" autocomplete="off" readonly="true" class="form-control oninput" />
And here's JQUERY Fetching the value
$.ajax({
url: 'fetchSelectedOrder.php',
type: 'post',
data: {productId : productId},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#material_name"+row).val(response.material_name);
} // /success
}); // /ajax function to fetch the product data
}
fetchSelectedOrder.php
<?php
require_once 'checker.php';
$productId = $_POST['productId'];
$sql = "SELECT material_name FROM tbl_materials WHERE m_id = $productId";
$result = $controller->runQuery($sql);
$result->execute();
if($result->rowCount() >= 1) {
$row = $result->fetch(PDO::FETCH_ASSOC);
} // if num_rows
echo json_encode($row);
Data From Database:
I use htmlentities to prevent quote inside database.
How can I fetch " as "?
You can use html_entity_decode() to convert it back to the original text.
However, I recommend that you stop using htmlentities() when storing into the database. You don't need to prevent having quotes in the database. If you're getting syntax errors when you try to store it, you should fix the code to use parametrized statements rather than substituting variables into the string. And if you must substitute variables, you should use a proper escaping function, either mysqli::real_escape_string() or PDO::quote().
If you're trying to prevent XSS, call htmlentities() when you're displaying the output on a web page. If you're using JavaScript to display the results on a web page, use the textContent DOM property or the jQuery .text() method, rather than innerHTML or .html(). If you're assigning to the value property, it never gets executed so you don't need to do any encoding.
You can use the following function to decode html:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
// handle case of empty input
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Usage:
$("#material_name"+row).val(htmlDecode(response.material_name));
That will display html as real text.
You could decode the HTML entities coming from the DB on server side.
<?php
require_once 'checker.php';
$productId = $_POST['productId'];
$sql = "SELECT material_name FROM tbl_materials WHERE m_id = $productId";
$result = $controller->runQuery($sql);
$result->execute();
if($result->rowCount() >= 1) {
$row = $result->fetch(PDO::FETCH_ASSOC);
} // if num_rows
// Run html_entity_decode on all $row values
foreach ($row as $k => $v) {
$row[$k] = html_entity_decode($v);
}
echo json_encode($row);
That also is a "patch" for a DB having bad values... But unlike the other answer, which relies on the end user's device, here is a server-side solution.
And please read about prepared statements to prevent injection...
How can I enter the dynamically created input fields in my database using php?
Code snippet explanation:
Firstly the user enters the date1 and date2 values. The javascript code creates dynamic input fields. Then on submitting the values mysql query executes.
Problem is the mysql query is not able to enter the dynamic values into database.
JS:
function getrates() {
var date1 = Date.parse(document.getElementById('date1').value); //taking input from user
var date2 = Date.parse(document.getElementById('date2').value);// taking second input from user
var no_of_days = ((date2-date1) / (1000 * 3600 * 24)); //calculating days b/w date1 and date2
//document.getElementById('nod').value = no_of_days;
var newDateColumn;
var newRow;
var table_columns = 2;
for(counter = 1; counter<= no_of_days; counter++) {
newDateColumn = document.createElement("td");
newDateColumn.innerHTML = "Day "+counter;
newAmtColumn = document.createElement("td");
newAmtColumn.innerHTML = "<input type='text' class='form-contol' name='txt"+counter+"'>";
newRow = document.createElement("tr");
newRow.insertBefore(newDateColumn, newRow.appendChild(newAmtColumn));
//newRow.appendChild(newAmtColumn);
document.getElementById("ratetab").appendChild(newRow);
} }
HTML:
<label>Date1</label>
<input id="date1" name="date1" type="text" placeholder="yyyy/mm/dd">
<label>Date2</label>
<input id="date2" name="date2" type="text" placeholder="yyyy/mm/dd" onchange="getrates();">
<table id="ratetab" class="table">
<tr>
<th>Date</th>
<th>Rates</th>
</tr>
</table>
PHP:
<?php
$conn = new PDO('mysql:host=localhost;dbname=ratebox', 'root', ''); //db connection
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$d1 = new DateTime("$date1");
$d2 = new DateTime("$date1");
$no_of_days = $d1->diff($d2)->days; //calculating no of days
for ($x = 0; $x < $nO_of_days; $x = $x + 1) {
$rate = $_POST['txt' + counter];
$conn->query("insert into tb_rate(rates) values (NOW(),'$rate')") or die(mysql_error());
}
?>
I am not able to enter the input values into database.
You have syntax error in your mysql query.
"insert into tb_rate(rates) values (NOW(),'$rate')"
Here you should have two parameter in as table column and you have passed only one. This query should be something like.
"insert into tb_rate(date_field, rates) values (NOW(),'$rate')"
May this help you.
The below is my 2 cents on the DB only routines. I hope it is useful.
<?php
$date1 = $_POST['date1'];
$date1 = $_POST['date2'];
$d1 = new DateTime("$date1");
$d2 = new DateTime("$date1");
$no_of_days = $d1->diff($d2)->days; //calculating no of days
try {
$conn = new PDO('mysql:host=localhost;dbname=ratebox', 'root', ''); //db connection
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <--- non-production mode, debug
// figure out what some_column is below in your table
$stmt = $dbh->prepare("INSERT INTO tb_rates (some_column,rates) VALUES (now(), :col2)");
$stmt->bindParam(':col2', $rate);
for ($x = 0; $x < $nO_of_days; $x = $x + 1) {
$rate = $_POST['txt'] + counter; // <--- is that better ?
// problem: $rate still has uncleansed user-supplied data
// the next line probably has an error. 1 column versus 2 columns in the values():
//$conn->query("insert into tb_rate(rates) values (NOW(),'$rate')") or die(mysql_error());
$stmt->execute();
}
}
catch (PDOException $e) {
// non-production mode, debug
print "Error!: " . $e->getMessage() . ".";
die();
}
// when are you closing that $conn by the way? Something to think about
?>
Also don't connect with root unless in maintenance-mode. Use prepare and bind with PDO, not passing strings from user-supplied values. What is the point of using PDO otherwise?
So basically, you are combining mysql_* deprecated concepts, error trapping, with PDO, like a cut-and-paste jumble of code. Still allowing for sql-injection imo.