Date picker date not saving to database - php

I am using a date picker on a form and it selects the date in the format "20 May 2014"
in the form processing i have tried to amend this to save in the correct (Y m d) format but every time i save it it still stores as 0000-00-00 in the database. Not sure what is going on as this WAS working before?
form processing code:
<?php
if (isset($_POST['submit'])) {
//Process the form
$project_title = mysql_prep($_POST["project_title"]);
$start_date = $_POST["start_date"];
$stage = $_POST["stage"];
$acc_manager = $_POST["acc_manager"];
$designer = $_POST["designer"];
$url = $_POST["url"];
$timestamp = strtotime($start_date);
$start_date2 = date("Y m d", $timestamp);
$query = "INSERT INTO projects (";
$query .= " project_title, start_date, stage, acc_manager, designer, url";
$query .= " ) VALUES (";
$query .= " '{$project_title}', '{$start_date2}', '{$stage}', '{$acc_manager}', '{$designer}', '{$url}' ";
$query .= ")";
echo $query;
try { $result = mysqli_query($connection, $query);
} catch (Exception $e) {
return 'Caught exception: '+ $e->getMessage()+ "\n";
}
//Test if there was a query error
if ($result) {
//Success
// would normally use a redirect ie redirect_to("somepage.php");
//$message = "Subject created.";
redirect_to("projects.php");
}else {
//failure
//$message = "Subject creation failed.";
//redirect_to("add_project.php");
echo $query;
}
} else {
// This is probably a GET request
redirect_to("add_project.php");
}
?>

Correct $start_date2 date string.
Try:
date("Y-m-d", $timestamp);

Related

Putting Next 30 days into array

I am needing to find the next 30 days and put in array to repeat a scheduling code.
So I would need to have a variable for
$date= "would hold the date";
$day_of_week= "would hold the # value for the day of week";
I am at a loss of where to even start... I am wanting to repeat the following code for each respective day to schedule crews for the next 30 days.
<?
// Connection Script
include 'connection.php';
date_default_timezone_set("America/New_York");
$tomorrow= strtotime('+ 1 day');
$date= date('N', $tomorrow);
// Get all employees who work tomorrow and group by unit//
$units= "select e.user_id, e.station, e.full_name, max(e.level) level, es.unit, es.days, es.start_time, es.end_time from employees e
left join employee_schedule es on es.pid = e.user_id
where es.days like '%$date%' and e.status = 1
group by es.unit";
$units_result= $conn->query($units);
//Roll through all employees who work tomorrow and place then in appropriate unit.
while($row_unit = $units_result->fetch_assoc()) {
if($row_unit['level'] == 3){
$level= 1;
}elseif($row_unit['level'] == 4){
$level= 2;
}elseif($row_unit['level'] == 5){
$level= 3;
}elseif($row_unit['level'] == 8){
$level= 4;
}
//Get Unit ID from each group
$unitid = $row_unit['unit'];
$intime= date('Y-m-d', $tomorrow);
$intime= $intime.' '. $row_unit['start_time'];
$length= '+ 23 hours';
$intimes= strtotime("$intime");
$endtime= strtotime("$length","$intimes" );
$endtime= date('Y-m-d H:i:s', $endtime);
$station= $row_unit['station'];
$timenow= date('Y-m-d H:i:s');
echo "<p>I am scheduling unit number $unitid to be on at $intime and leave at $endtime </p>";
$unitinsert= "insert into schedules (date_time, unit, level_of_service, start_time, end_time, station)
values ('$timenow', $unitid, $level , '$intime', '$endtime', $station)";
if(mysqli_query($conn, $unitinsert)){
echo "Records inserted successfully.";
$unitinid= $conn->insert_id;
echo $unitinid;
} else{
echo "ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn);
}
$employee = "select e.*, es.unit, es.days, pc.email as pemail from employees e
left join employee_schedule es on es.pid = e.user_id
left join phone_carriers pc on pc.id = e.phone_carrier
where es.days like '%$date%'and es.unit = $unitid and e.status = 1";
$employee_result= $conn->query($employee);
if(mysqli_num_rows($employee_result) > 0){
while($row_employee = $employee_result->fetch_assoc()) {
$pid = $unitinid;
$eid= $row_employee['user_id'];
$ephone = $row_employee['mobile_number'];
$emailphone= $row_employee['mobile_number'].''. $row_employee['pemail'];
$unitcrewinsert= "insert into crew_assignment (date_time, pid, crew_member, phone_number, message_number, confirmed)
values ('$timenow', $pid, $eid , '$ephone', '$emailphone', 0)";
if(mysqli_query($conn, $unitcrewinsert)){
echo "Records inserted successfully.";
echo '<p> Crew Inserted </p>';
} else{
echo "<p>ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn).'</p>';
}
}
}
}
Your best bet is to provide a start date and an end date and get the number of days between them. Then it's just a matter of looping through each day and assigning it to an array. Could probably use the same logic to solve the weeks as well.
Example:
$d1 = Carbon::parse($start_date);
$d2 = Carbon::parse($end_date);
$num_days = $d1->diffInDays($d2) + 1;
$dates = array();
for ($i = 1; $i <= $num_days; $i++) {
array_push($dates, date('Y-m-d', strtotime($start_date.' +'.$i.' days')));
}
var_dump($dates);
I am not sure this is the best way, however it works.
<?php
include 'connection.php';
date_default_timezone_set("America/New_York");
// Start date
$date = '2018-05-18';
// End date
$end_date = '2018-05-31';
while (strtotime($date) <= strtotime($end_date)) {
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
$dayn = date('N', strtotime($date));
echo "<p> $date </p>";
echo "<p> $dayn </p>";
$units = "select e.user_id, e.station, e.full_name, max(e.level) level, es.unit, es.days, es.start_time, es.total_hours from employees e
left join employee_schedule es on es.pid = e.user_id
where es.days like '%$dayn%' and e.status = 1
group by es.unit";
$units_result = $conn->query($units);
//Roll through all employees who work tomorrow and place then in appropriate unit.
if($units_result->num_rows > 0){
while ($row_unit = $units_result->fetch_assoc()) {
if ($row_unit['level'] == 3) {
$level = 1;
} elseif ($row_unit['level'] == 4) {
$level = 2;
} elseif ($row_unit['level'] == 5) {
$level = 3;
} elseif ($row_unit['level'] == 8) {
$level = 4;
}
//Get Unit ID from each group
$unitid = $row_unit['unit'];
$intime = $date . ' ' . $row_unit['start_time'];
$total_hours= $row_unit['total_hours'];
$length = "+ $total_hours ";
$intimes = strtotime("$intime");
$endtime = strtotime("$length", "$intimes");
$endtime = date('Y-m-d H:i:s', $endtime);
$station = $row_unit['station'];
$timenow = date('Y-m-d H:i:s');
echo "<p>I am scheduling unit number $unitid to be on at $intime and leave at $total_hours </p>";
$unitinsert = "insert into schedules (date_time, unit, level_of_service, start_time, total_hours, station)
values ('$timenow', $unitid, $level , '$intime', '$total_hours', $station)";
if (mysqli_query($conn, $unitinsert)) {
echo "Records inserted successfully.";
$unitinid = $conn->insert_id;
echo $unitinid;
} else {
echo "ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn);
}
$inspectioninsert= ""
$employee = "select e.*, es.unit, es.days, pc.email as pemail from employees e
left join employee_schedule es on es.pid = e.user_id
left join phone_carriers pc on pc.id = e.phone_carrier
where es.days like '%$dayn%'and es.unit = $unitid and e.status = 1";
$employee_result = $conn->query($employee);
if (mysqli_num_rows($employee_result) > 0) {
while ($row_employee = $employee_result->fetch_assoc()) {
$pid = $unitinid;
$eid = $row_employee['user_id'];
$ephone = $row_employee['mobile_number'];
$emailphone = $row_employee['mobile_number'] . '' . $row_employee['pemail'];
$unitcrewinsert = "insert into crew_assignment (date_time, pid, crew_member, phone_number, message_number, confirmed)
values ('$timenow', $pid, $eid , '$ephone', '$emailphone', 0)";
if (mysqli_query($conn, $unitcrewinsert)) {
echo "Records inserted successfully.";
echo '<p> Crew Inserted </p>';
} else {
echo "<p>ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn) . '</p>';
}
}
}
}
}
}
?>

Trying to use a function in php to update a database

When I write the code out without a function it works, otherwise I get a 500 connection error. Not sure what error I'm making. Here is my code:
$date = "2016-01-12";
$date = date("Y-m-d", strtotime($date));
$sql = 'INSERT INTO `campaigns` (campaign_id, campaign_date) VALUES (9001, "' . $date . '")';
$result = $link->query($sql);
if ($result) {
echo "database updated";
} else {
echo $link->error;
}
function insertIntoDB($mysqli, $date) {
$sql = 'INSERT INTO `campaigns` (campaign_id, campaign_date) VALUES (9001, "' . $date . '")';
$result = $mysqli->query($sql);
if ($result) {
echo "database updated";
} else {
echo $mysqli->error;
}
}
insertIntoDB($link, $date);
The function works properly when I call it above defining it. Dunno.

Inserting user tweets into mysql table

I am getting user tweets and mentions and inserting into table. Once this process completes, I redirect to next page.
For few users it correctly stores and display tweets and redirect to next page. But for few user, it stuck on the first page where I get tweets and store into table. I am trying since last few days to overcome this.
Can any one tell me what problem can cause this? Does it is due to it unable to store the data (tweet text) into table?
There are two function in which I perform insert operation:
function lookup($tweetid,$connection,$userid)
{
$tweets5 = $connection->get("https://api.twitter.com/1.1/statuses/retweets/".$tweetid.".json?count=1");
//var_dump($tweets5);
$json = json_encode($tweets5);
foreach($tweets5 as $item)
{
$text = $item->text;
$text_id = $item->id;
// $user_id = $item->user->id;
$name = $item->user->name;
$constant = 'retweet';
$time = $item->created_at;
$dt = \DateTime::createFromFormat('D M d H:i:s e Y', $time);
// $dt = new \DateTime($time);
$tweet_time = $dt->format('H:m:s');
$tweet_dtm = $dt->format('Y:m:d');
$year = $dt->format('Y');
$month = $dt->format('m');
echo $text."-".$text_id."-".$name."-".$time."-".$tweet_time.$tweet_dtm.$year.$month.$rt_count.$follower.$friend."<br>";
echo "<br>";
$inreplyto = $item->in_reply_to_screen_name;
$follower = $item->user->followers_count;
$rt_count = $item->retweet_count;
$friend = $item->user->friends_count;
$con = mysqli_connect('127.0.0.1', 'root', 'karim', 'karim');
$text = mysql_real_escape_string($text);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$insertQuery1 = "INSERT INTO twitter_retweet(`username`,`userid`,`tweet_text`,`text_id`,`time`,`month`,`year`,`date`,`user_follower_count`,`rt_count`,`constant`,`in_reply_to`) VALUES ('".$name."','".$userid."','".$text."','".$text_id."','".$tweet_time."','".$month."','".$year."','".$tweet_dtm."','".$follower."','".$rt_count."','".$constant."','".$inreplyto."')";
if (!mysqli_query($con,$insertQuery1))
{
die('Error: ' . mysqli_error($con));
// echo "error";
}
// echo "Text : $text <br> ID : $user_id <br> Name : $name <br> Follower : $follower <br> Friends : $friend <br> ---";
}
}
Is there anything wrong in this code? I am not sure whether it stuck here during insertion or what.
2nd function, this prints the data, but it does not store $text into database. why?:
foreach ($tweets1 as $item)
{
$text = $item->text;
//echo $userid.$text;
$text_id = $item->id;
$constant = 'mention';
$time = $item->created_at;
//echo $time;
//$dt = new DateTime('#' . strtotime($time));
$dt = \DateTime::createFromFormat('D M d H:i:s e Y', $time);
//var_dump($dt);
$tweet_time = $dt->format('H:m:s');
$tweet_dtm = $dt->format('Y:m:d');
$year = $dt->format('Y');
$month = $dt->format('m');
$user_name = $item->user->name;
// echo $year.$month.$user_name;
$inreplyto = $item->in_reply_to_screen_name;
$rt_count = $item->retweet_count;
$follower_count = $item->user->followers_count;
echo $text."-".$text_id."-".$time."-".$tweet_time.$tweet_dtm.$year.$month.$user_name.$rt_count.$follower_count."<br>";
echo "<br>";
$con = mysqli_connect('127.0.0.1', 'root', 'karim', 'karim');
//$text = mysqli_real_escape_string($text);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$insertQuery1 = "INSERT INTO twitter_mention(`username`,`userid`,`tweet_text`,`text_id`,`time`,`month`,`year`,`date`,`user_follower_count`,`rt_count`,`constant`,`in_reply_to`) VALUES ('".$twitteruser."','".$userid."','".$text."','".$text_id."','".$tweet_time."','".$month."','".$year."','".$tweet_dtm."','".$follower_count."','".$rt_count."','".$constant."','".$inreplyto."')";
if (!mysqli_query($con,$insertQuery1))
{
die('Error: ' . mysqli_error($con));
// echo "error";
}
}
This is the code at the end to redirect to next page:
echo '<form name="myForm" id="myForm" action="start.php" method="POST">
<input style="display:none" name="userid" value="'.$userid.'" />
</form>
<script>
function submitform()
{
document.getElementById("myForm").submit();
}
window.onload = submitform;
</script>
';

How do I send a time to a MySql database with PHP?

I am trying to send a time to my MySql database on localhost using a simple PHP query. Here's the code.
On the HTML side:
<form action = "Timecard.php"
method = "get">
<fieldset>
<label>Enter employee number:</label>
<input type = "text"
name = "EmployeeNumber" />
<button type = "submit" name = "submit" value = "ClockIn">
Clock In
</button>
<button type = "submit" name = "submit" value = "ClockOut">
Clock Out
</button>
</fieldset>
</form>
And the PHP:
<?php
require ("conn.php");
$filled = true;
$EmpNum = $_REQUEST["EmployeeNumber"];
if ($EmpNum == "") {
$filled = false;
}
if ($filled == false) {
print "Must enter a valid employee number to log in. Click <a href = 'http://localhost/Employee Timecard/Timecard.html'>HERE</a> to return to the login screen";
} else {
$timestamp = $_SERVER['REQUEST_TIME'];
$date = date('Y-m-d', $timestamp);
$time = sprintf(date('h-i-s', $timestamp));
print $timestamp . "<br>";
print $EmpNum . " has just logged ";
if (($SubmitButton = $_REQUEST["submit"]) == "ClockIn") {
print "in on " . $date . " at " . $time;
$query = sprintf("INSERT INTO timestamp(EmployeeNumber, Date, TimeIn, TimeOut) VALUES (".$EmpNum.",'".$date."','".$time."','')");
print $query;
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
print "checkpoint 2";
} else if (($SubmittButton = $_REQUEST["submit"]) == "ClockOut") {
print "out on " . $date . " at " . $time;
$query = sprintf("INSERT INTO timestamp(EmployeeNumber, Date, TimeIn, TimeOut) VALUES (".$EmpNum.",'".$date."','',".$time.")");
print $query;
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
print "checkpoint 2";
}
}
print "<br>checkpoint 3";
?>
When I submit to the database the date goes through fine but the time is incorrect -- something like -00:00:47 or 00:00:05. The type of the field in the database is set to "time". Why would I be getting these results? It has to be simple, but it's driving me nuts.
You can simply use date() here,
$query = "INSERT INTO timestamp(EmployeeNumber, Date, TimeIn, TimeOut)
VALUES (".$EmpNum.",'".$date."','','".date('H:i:s')."')";
print $query;

PHP: Compare Date

I'm encountering the following problem:
I'd like to compare today's date against some dates in a database, then if it isn't expired yet, show something... but if all the dates in the table are expired, show something like 'No lecture scheduled at this time, return again'.
As for the first thing it's no problem, but I can't show the text where there aren't any future dates...
Here's the code,
Table:
id, dateposted, date_course, title, body
$sql = "SELECT *
FROM L
ORDER BY L.dateposted DESC;";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$exp_date = $row['date_course'];
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date >= $today)
{
echo "<a href='courses.php'>" . $row['title']. "</a>";
echo "</br>";
}
}
I'll assume you're using MySQL. A couple of small changes to your query and code should make this work. You should definitely do this kind of filtering in the query and not the code.
$sql = "SELECT *
FROM L
WHERE date_course < NOW() AND dateposted < NOW()
ORDER BY L.dateposted DESC;";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo "<a href='courses.php'>" . $row['title']. "</a>";
echo "</br>";
}
}
else
{
echo "No results available";
}
Several ways to do it. One would be to make the date comparison part of the query. If no rows are selected, show your special message.
Otherwise, you can set a flag like
$has_courses = false;
while ($row = fetch() {
$has_courses = true;
...
}
if (!$has_courses) { echo 'No courses'; }
Although you could do this far more efficiently by improving your query, here is the specific fix you request:
$sql = "SELECT *
FROM L
ORDER BY L.dateposted DESC;";
$result = mysql_query($sql) or die(mysql_error());
$out = false;
while($row = mysql_fetch_assoc($result))
{
$exp_date = $row['date_course'];
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date >= $today)
{
$out = true;
echo "<a href='courses.php'>" . $row['title']. "</a>";
echo "</br>";
}
}
if (!$out)
echo 'Nothing found.';

Categories