I have a table that has a column called hdate. I have set this withe the date property.
I have a form :
<H2>Search By Date</H2></div>
<form name="attdate" action="datesearch.php" method="post">
From :<input id="datepicker" name = "startd"> To: <input id="datepicker1" name = "endd">
<input type="submit" value="Search Records">
Now my intention is to allow the user to enter a start date and end date and obtain all the rows with these date.
<?php
include 'config.php';
$startd = ($_POST['startd']);
$endd = ($_POST['endd']);
$startd = mysqli_real_escape_string($con,$startd);
$endd = mysqli_real_escape_string($con,$endd);
$sql = "SELECT * FROM handover WHERE hdate AND >= '" . $startd . "' AND <'"
.$endd. "' + ‘ 23:59:59’"
;
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo 'here are your results';
My dates are going in to the database for hdate and in the same format set by the datepicker.
I am successfully getting results querying other columns. Any ideas? note time added after reading on a couple of sites. I have read other questions on stacked but they do not relate to user input.
When testing with the current set up I am not getting errors just the "No matches so I guess the query is valid but not set up right to query my hdate column.
I can change column easily so if the simplest solution is to use timestamp or something then it okay to do so.
<?php
include 'config.php';
$startd = ($_POST['startd']);
$endd = ($_POST['endd']);
$startd = mysqli_real_escape_string($con,$startd);
$endd = mysqli_real_escape_string($con,$endd);
$startd = '2014-11-18';
$endd = '2014-11-20';
$sql = "SELECT * FROM handover WHERE hdate >= date('" . $startd . "') AND hdate <
ADDDATE(date('" . $endd . "'), INTERVAL 1 DAY)";
echo $sql; // run in mys
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
Im still just getting a "no matches " echo
Assuming that $startd and $endd are in your basic MySQL date format of YYYY-MM-DD, then:
$sql = "SELECT * FROM handover WHERE hdate >= date('" . $startd . "') AND hdate < ADDDATE(date('" . $endd . "'), INTERVAL 1 DAY)";
Otherwise, you'll probably have to perform some string operations to reformat $startd and $endd into YYYY-MM-DD before using the above.
My tip for how to debug this stuff in general would be hardcode some values in the variables and print the SQL out, then run it in the console and mess with it until you can get it to work as expected:
$startd = '2014-11-18';
$endd = '2014-11-20';
$sql = "SELECT * FROM handover WHERE hdate >= date('" . $startd . "') AND hdate < ADDDATE(date('" . $endd . "'), INTERVAL 1 DAY)";
echo $sql; // run in mysql console and see how it works before moving forward in php
Then after that works, upgrade to using the POST parameters and printing the SQL out, and you'll know whether it looks right or not based on whether it matches what was working before.
Please note your SQL syntax has been corrected above, as you had AND twice where its only needed once, and you were missing the reference to hdate after your second AND.
Related
I have a table in Database PhpMyAdmin with certain values, and I want to UPDATE only ONE value of these, WHERE the latest initial_date (TIMESTAMP) is.
I write down here the code I generated as an example, so you can see I actually obtain that date value through SELECT, but I don't manage to UPDATE it. Thank you very much.
$select = "SELECT MAX(initial_date) AS max_value FROM services WHERE matricula = '" . $_POST["taxi"] . "'";
$select_results = mysqli_query($conexion, $select);
while($row = mysqli_fetch_array($select_results)){
echo $row['max_value'];
$update_carrera = "UPDATE services SET";
$update_carrera .= " costo_carrera = costo_carrera + " . $_POST["costo_carrera"] . ",";
$update_carrera .= " final_date = CURRENT_TIMESTAMP";
$update_carrera .= " WHERE initial_date = ''";
$update_carrera_results = mysqli_query($conexion, $update_carrera);
}
I leave WHERE initial_date = '' empty so you can tell what should it be. I get a correct date value in the echo $row['max_value']; if I solve the WHERE with a WHERE initial_date = '20160405153315' (INTEGER), but I don't want to put myself the integer, of course I want to get the newest date from the table database.
I am setting a variable that contains an array as a constraint to a SELECT sql statement. However the constraint seems only to apply to one piece of data in the array. Why is this?
Code below:
<?php
include 'connection.php';
$Date = $_POST['date'];
$Unavail = 0;
$Avail = 0;
$Availid = 0;
$low = 99999;
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
while($request = mysql_fetch_array($dayresult)) {
$Unavail = $request;
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance WHERE Username != '$Unavail[username]'";
$dayresult1 = mysql_query($query1);
while($request1 = mysql_fetch_array($dayresult1)) {
echo "<span>" . $request1['name'] . " is available.</br>";
if ($request1['work_stats']<=$low) {
$low = $request1['work_stats'];
$Availid = $request1['name'];
}}
echo "<span>" . $Availid . " is available on " . $_POST['date'] . " and is on workstat level " . $low . ".</span></br>";
?>
The output shows two names in the first echo but then shows one of those names as available in the second echo (these echos are only in place as part of my testing),
Many Thanks
The first query can have multiple results.
SELECT username FROM daysoff WHERE date = '$Date'
Let's say if gives two rows: Dave and John.
You're only keeping the last record so it will seem like Dave is available.
You should probably do something like:
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
$unavailable_users = array();
while($request = mysql_fetch_array($dayresult)) {
$unavailable_users[] = $request["username"];
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance
WHERE NOT Username IN ('" . implode("','", $unavailable_users) . "')";
// etc
Or in one go with a LEFT JOIN:
SELECT `Username`, `name`, `work_stats`
FROM `freelance`
LEFT JOIN `daysoff` ON `freelance`.`Username` = `daysoff`.`username`
AND `daysoff`.`date` = '$Date'
WHERE
`daysoff`.`username` IS NULL
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
I grabbed this piece of code off the Internet and modified it slightly to fit my needs but it doesn't work and I don't know why. I'm sure I've overlooked something but I don't know enough about PHP to know what I'm doing wrong. The uid is showing up, but nothing else. I'm just trying to get information from the MySQL data based on the user's session id. I checked the database to make sure that the uid that shows matches the data -- it does.
<?php
include("connect.php");
session_start();
$uid = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM users WHERE id = ' . $uid . '");
if ($result) {
echo "Connect"; } else
{ die('Invalid query: '.mysql_error()); }
$info = mysql_fetch_array($result);
echo "<br>ID: ", $uid;
echo "<br>Full Name: " .$info['full_name'] ;
echo "<br>User Name: " .$info['user_name'] ;
echo "<br>";
?>
p.s. - Yes, I know that mysql_query (and other syntax like it) has been deprecated.
$result = mysql_query("SELECT * FROM users WHERE id = '" . $uid . "'"); // not ' . $uid . '
NOTE: You were searching for . ID . not actual ID
Query should be as
$result = mysql_query("SELECT * FROM users WHERE id = $uid ");
Assuming id is int in the table
You had
$result = mysql_query("SELECT * FROM users WHERE id = ' . $uid . '");
^.... ^.... was the issue.
I'm trying to update a range of dates with a Shift_ID but the Shift_ID that is entered depends upon what day of the week it is. So, for example, if I have a range of dates $from = "2012-12-01" $to = "2012-12-28" I'm trying to make it so that I can select a check box (for example: value="Fri" name = "offdays[]") to indicate what day is an offdays. If an offdays is matched with a day in the set range, then the Shift_ID = "6" otherwise it is a work day and Shift_ID = "3"
Hopefully this will all make sense in a minute, I'm doing my best to explain it as well as give you some useful variables.
So here is my code:
if(isset($_POST['submit']))
{
if(isset($_POST['offdays']))
{
//$off is set through the config settings//
$shift = mysqli_real_escape_string($_POST['shift']);
$from = mysqli_real_escape_string($_POST['from']);
$to = mysqli_real_escape_string($_POST['to']);
$emp_id = mysqli_real_escape_string($_POST['emp_id']);
foreach($_POST['offdays'] as $checkbox)
{
echo "Checkbox: " . $checkbox . "<br>";//error checking
$sql = ("SELECT Date FROM schedule WHERE (Date BETWEEN '$from' AND '$to') AND (Emp_ID = '$emp_id')");
if(!$result_date_query = $mysqli->query($sql))
{
echo "INSERT ERROR 1 HERE";
}
echo "SELECT SQL: " . $sql . "<br>";//error checking
while($row = $result_date_query->fetch_assoc())
{
echo "Date: " . $row['Date'] . "<br>";//error checking
$date = date('D',strtotime($row['Date']));
if($date == $checkbox)
{
echo "MATCHED! Date: " . $date . " Checkbox: " . $checkbox . "<br>";//error checking
$sql = ("UPDATE schedule SET Shift_ID = '$off' WHERE Date = '" . $row['Date'] . "' AND Emp_ID = '$emp_id'");
if(!$result_update_offdays_query = $mysqli->query($sql))
{
echo "INSERT ERROR 2 HERE";
}
echo "UPDATE DAYS OFF SQL: " . $sql . "<br><br>";//error checking
}
else
{
echo "NOT MATCHED! Date: " . $date . " Checkbox: " . $checkbox . "<br>";//error checking
$sql = ("UPDATE schedule SET Shift_ID = '$shift' WHERE Date = '" . $row['Date'] . "' AND Emp_ID = '$emp_id'");
if(!$result_update_shift_query = $mysqli->query($sql))
{
echo "INSERT ERROR 3 HERE";
}
echo "UPDATE SHIFT SQL: " . $sql . "<br><br>";//error checking
}
}
}
}
}
When I look at my printed echo statements, everything is perfect! When a date lands on a Friday, it shows that it's entering Shift_ID = "6" and any other day shows Shift_ID = "3". The problem is the tables don't reflect what my statements are telling me, they all just get updated to Shift_ID = "3".
In the end I want to be able to select more than one offdays, but when I select more than one, it overwrites my previous day during the next loop, which makes sense.
I've got no idea what is going on, if anyone can give me a clue, I would really appreciate it.
UPDATE: When I add exit; after the days off update, like this:
echo "UPDATE DAYS OFF SQL: " . $sql . "<br><br>";//error
exit;
it does update the day off to Shift_ID = "6", so it must be something happening after that.
EDIT: It appears as though the problem was with user permissions. I can't explain why, but after deleting the user and creating a new one with full permissions, things started to work. I chose #andho's answer as he helped me get to the answer in the chat forum and also added a way to clean up my code.
This doesn't solve your issue, but simplifies the solution!
if your offdays variable is as follows: $offdays = array('Fri', 'Sun');
You can first set all dates in range to $shift in one query:
UPDATE Schedule SET Shift_ID = '$shift' WHERE Date BETWEEN '$from' AND '$to' AND Emp_ID = '$emp_id'
Then you can loop through the foreach ($offdays as $offday) { and update those offdays:
UPDATE Schedule SET Shift_ID = '$off' WHERE Date BETWEEN '$from' AND '$to' AND Emp_ID = '$emp_id' AND DATE_FORMAT(Date, '%a') = '$offday'
That should update all the $offday's in the range to $off.
This will reduce your loops and queries, which gives leaner code.
$sql = ("SELECT `Date` FROM schedule WHERE (`Date` BETWEEN '$from' AND '$to') AND (Emp_ID = '$emp_id')");
Use backtick(`) to all the fieldname date because it is reserved in mysql.