while loop inside foreach loop problems - php

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.

Related

php and mysql query to get date of the last 12 months

I have a php function to get dates for a morris pie chart and it was working fine.
But now that I have more data (date for the last year and the first 3 months of this year). It's now displaying duplicate months. In this case february of last year and this years data is now showing on the same pie chart.
I'd like to write a some mysql code in php that will only display the last 12 months. I have the following code:
function writesql($rec) {
$year = date('Y') -1;
$month = date('m');
$lastyear = $year - $month; // I know this is a problem.It's subtracting the two variables
$sql = "";
$sql = $sql . " SELECT";
$sql = $sql . " YEAR(`value`)as 'Year',";
$sql = $sql . " MONTH(`value`)as 'Month',";
$sql = $sql . " `value` , ";
$sql = $sql . " COUNT(`value`) as 'Calls' ,";
$sql = $sql . " ROUND(SUM( `value` ),2) as 'Value'";
$sql = $sql . " FROM `table`";
$sql = $sql . " GROUP BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)" ;
$sql = $sql . " ORDER BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)";
$sql = $sql." WHERE (`value`)='".$lastyear."'";// I also know this is wrong too but im lost as to how to fix it.
return $sql;
}
Then the rest follows, I only want to get the data for the last 12 months how should I be executing this.
You could do WHERE value >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR);
This would show 12 months up to the current date.
You are close. Make these changes
$year = date('Y') -1; // This will give last year
$sql." WHERE YEAR(`value`)='".$year."'"
Updated Query
$sql = "
SELECT YEAR(`value`) as 'Year', MONTH(`value`) as 'Month', `value`,
COUNT(`value`) as 'Calls', ROUND(SUM( `value` ),2) as 'Value'
FROM `table`
WHERE YEAR(`value`) = '$year'
GROUP BY YEAR(`value`), MONTH(`value`)
ORDER BY YEAR(`value`), MONTH(`value`)";
First off, I find this easier to read:
$sql = "
SELECT YEAR(value) Year
, MONTH(value) Month
, value
, COUNT(value) Calls
, ROUND(SUM(value),2) Value
FROM `table`
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value)
WHERE (value) = '".$lastyear."'
";
But this query is syntactically incorrect. So here's a syntactically correct version:
$sql = "
SELECT YEAR(`value`) Year
, MONTH(`value`) Month
, COUNT(value) Calls
, ROUND(SUM(value),2) Total_Value
FROM `table`
WHERE value = '".$lastyear."'
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value);
";
Now see about prepared and bound queries

Update SQL Datefield to add a week BUT keep same time

I have a countdown script that works 100% successfully. It's pulling the data down from the database but I'm having a few issues with a cronjob script. I want it to add a week to the community_night date.
When I try adding to this, it keeps resetting the date to 0000-00-00 however I can see that the query should be working correctly.
<?php
$con = mysqli_connect("localhost","","","") or die("Error in the consult.." . mysqli_error($connect));
$result = mysqli_query($con,"SELECT * FROM Community_Night");
while($row = mysqli_fetch_array($result))
$dbDate = $row['community_night'];
$date = strtotime($dbDate . ' + 1 week');
$setDate = date('d-m-Y',$date);
$sql = "UPDATE Community_Night SET community_night =" . $setDate;
if (mysqli_query($con, $sql)) {
echo "Record updated successfully: " . $sql;
} else {
echo "Error updating record: " . mysqli_error($con);
}
?>
the SQL column is set to DATE.
I haven't tested this, but it should work:
$sql = "UPDATE Community_Night SET community_night = community_night + INTERVAL 1 WEEK";
Bear in mind this will update all the rows in the table.

PHP/SQL UPDATE value WHERE date equals maximum/newest date

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.

Between dates where user inputs values sql

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.

Can't get score to update with this mysql statement

I'm guessing that I'm just a little rusty or something because it seems like this should be working. Am I missing something here...
Here is the code I am trying to use...
<?php
echo dbConn();
$existing_time = mysql_result(mysql_query("SELECT p_time FROM scores WHERE p_uid=$uid"), 0);
$existing_category = mysql_result(mysql_query("SELECT p_cat FROM scores WHERE p_uid=$uid AND p_cat=$pieces"), 0);
if ($existing_category == "") {
mysql_query(
"INSERT INTO scores VALUES (
'',
'$uid',
'$pusername',
'$time',
'$pieces'
)");
} elseif ($existing_time <= $time) {
echo "No Change! Old Score Was Better (Lower)";
} elseif ($existing_time > $time) {
mysql_query("UPDATE scores SET p_time = " . $time . " WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
};
?>
Now... Here is what I am trying to do...
I am collecting info from the database where the users username AND category match. If the category for that user does not exist, it inserts the latest score. (This much works.)
Then, if the category does exist but the old score is better, it just does nothing. (This part works too)...
However, what I can't seem to do is get it to update the last score, if the current score is better (lower score, since this is a time based game.) It doesn't update the score.
I am trying it this way: By updating a row in "scores" where the USERNAME and the CATEGORY match at the same time.
Please note... where it says "pieces". this is a category. Where it says "time", this is a score. The score is returned as 00:00:00 for hours minutes and seconds.
EXAMPLE: (in parentheses is the database row name)
id (ID) = just KEY id in sequencial order
user id (p_uid) = 123456789
username (p_username) = somename
score (p_time) = 00:01:03
category (p_cat) = 10
Change you update statement to:
mysql_query("UPDATE scores SET p_time = '" . $time . "' WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
You have missed quotes in the update statement around $time.

Categories