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;
Related
i try to write a website for library as an exercise. I have while loop to display all books in my database. If user is logged in and state(stan) of book(ksiazka) is free(Wolny) it shows button under book. After clicking it takes all free books to database and update their state as hired not only that one which user want. Here is the code, thanks.
$findbook2 ="select ksiazka.id_ksiazka, ksiazka.tytul, ksiazka.id_stan, autor.id_autor, autor.imie_autor, ksiazka.rok_wydania, autor.nazwisko_autor, stan.id_stan, stan.nazwa_stan FROM ((ksiazka inner join autor ON ksiazka.id_autor = autor.id_autor) inner join stan ON ksiazka.id_stan = stan.id_stan);";
$stan = mysqli_query($connect, $findbook2);
while($row = mysqli_fetch_array($stan))
{
echo "Tytuł:" . " " .$row['tytul']." ". "Autor:" . " " . $row['imie_autor']." ". $row['nazwisko_autor']. " ". "Rok wydania" . " ". $row['rok_wydania'] . " ". "Stan ". $row['nazwa_stan']. " ";
if(isset($_SESSION['id_czytelnik'])){
if($row['nazwa_stan']=='Wolny'){
echo '<form method = "GET" action = "ksiazki.php">';
echo '<input type = "submit" name = "submit" value = "Wypożycz"/>';
echo '</form>';
if(isset($_REQUEST['submit'])){
$id_czytelnik = $_SESSION['id_czytelnik'];
$id_ksiazka = $row['id_ksiazka'];
$data_oddania = date('Y-m-d', strtotime('+30 days'));
$wstaw_ksiazke = "INSERT INTO `wypozyczenie`(`id_wypozyczenie`, `id_czytelnik`, `id_ksiazka`, `id_pracownik`, `data_wypozyczenia`, `data_oddania`) VALUES ('','$id_czytelnik','$id_ksiazka',2,NOW(),'$data_oddania')";
if(mysqli_query($connect, $wstaw_ksiazke)){
$update = "Update ksiazka set id_stan = 3 where id_ksiazka = '$id_ksiazka'";
if(mysqli_query($connect, $update)){
echo "Wypozyczyłeś książkę";
}
}
}
}
}
echo "</br>";
}
Consider the statement if(isset($_REQUEST['submit'])) which is always true inside your while loop after clicking submit as it is not unset anyway.It causes repeated execution of a statement while the Array is not empty.
My dropdown menu is loading from the database, I can select multiple options from the list. When I click my 'Add' button everything appears to be behaving as expected, apart from the fact that nothing is saving back to the database. Unfortunately I've done so many tweaks now, having looked at stack overflow and others, I'm in the realm of confusion rather than progress.
I have set up a logger file to show when a page is reached. So I can confirm that I do get to the insert_rooms.inc.php page.
<?php
session_start(); // gets current session data for user // this function sends headers so it cannot be called after any output.
require_once '../dbconfig.php';
$date = new DateTime();
$date = $date->format("y:m:d h:i:s");
$id = $_SESSION['u_nickname'];
$u_id = $_SESSION['u_id'];
$file = "../ips.txt";
$text = file_get_contents($file);
$text .= $date ." " . $id . " visited insert_rooms.inc.php"."\n"; ///////// this text must be changed for each page
file_put_contents($file, $text);
$conn = OpenCon();
if ($conn)
{
if(isset($_POST['room[]']))
{
$room = mysqli_real_escape_string($conn, $_POST['room']);
if($room) // if a room exists insert into db with users id.
{
foreach($_POST['room'] as $r)
{
//here we need to take for example the word kitchen and find the id belonging to kitchen from the master_rooms table use it to find the master_room_id for kitchen and insert that into the table called user_room_list - along with the user id taken from the session u_id
$room_id = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r'");
$sql = "INSERT INTO user_room_list(user_info_id, master_room_id)
VALUES(' ".$u_id." ', ' " .$room_id. " ') ";
mysqli_query($conn, $sql);
}
}
}
//session_unset();
//session_destroy();
header("Location: ../room_choice.php");
exit();
CloseCon($conn);
}
?>
extract from other file:
<div class="dropdown">
<form action="includes/insert_rooms.inc.php" method="POST">
"Hold down the Ctrl (windows) / Command (Mac) button to select multiple options."
<br/>
<br/>
<select name="room[]" multiple>
<?php
$conn = OpenCon();
if ($conn)
{
$query = "SELECT master_room_name FROM master_rooms";
mysqli_query($conn, $query) or die('Error querying database.');
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
for ($i = 0; $i < count($row); $i++)
{
echo "<option value=". $row[$i] . ">" . $row[$i] ."</option>";
}
}
CloseCon($conn);
echo "</select>";
echo " <input type="."submit"." value="." Add "." name="."send"."> ";
echo " </form> ";
}
?>
Below is the solution I found. Code is corrected accordingly.
foreach($room as $r) {
$result = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r' ;");
$room_id_array = mysqli_fetch_array($result);
$room_id = $room_id_array[0]; // required as room_id goes into an array of length 1
$stmt = $conn->prepare("INSERT INTO user_room_list(user_info_id, master_room_id) VALUES (?, ?)");
$stmt->bind_param("si", $u_id, $room_id);
$stmt->execute();
I have a form which updates information inside of a DB, everything works perfectly as it should....... except for some reason the header does not work for me. I am using the header redirect in a lot of other scripts within the same site; it is just this one script that the header redirect does not work. I know that the if statement the header is inside of is called because the echo right below the header is displayed on the page, its just kind of ignoring the header line. If you have any suggestions that would be very helpful.
The code below has been minimized so its not to long for everyone to read but if it is still a problem ill clean it up even more
the form
<form class="editUser" action="uploadEmployee.php" method="post" enctype="multipart/form-data" />
<input name="editUserFirstName" id="editUserFirstName" type="text" placeholder="Enter The User's First Name" />
<label>Employee's Coverage</label>
<input type="file" name="file_array[]" placeholder="Add The Employees Coverage" />
<input name="addUserSubmit" type="submit" value="Submit" />
</form>
The uploading scripts
<?php
include("includes/connect.inc.php");
if(isset($_FILES['file_array'])){
$day = date('d');
$month = date('m');
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F'); // March
$year = date('Y');
$date = $monthName . ", " . $day . ", " . $year;
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
$payCheque = $name_array[0];
$T4 = $name_array[1];
$coverage = $name_array[2];
$selectedId = $_POST['editId'];
$name = $_POST['editUserFirstName'];
if($_POST['editUserPermission']){
$permission = "1";
}else{
$permission = "0";
}
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
$title = "This Is A Test Title";
$icon = "0";
if($i == 0){
$icon = "1";
$title = "You Have Received A New Pay Cheque";
$comment = "Hello " . $name . ", click view document to view and download your pay cheque for " . $date . ". Your pay cheque will be a PDF file. Thank you.";
}
$sql = "INSERT INTO securedFiles (title, date, PDF, comment, idOfUser, icon)
VALUES ('$title', '$date', '$name_array[$i]', '$comment', '$documentId', '$icon')";
if ($connect->query($sql) === TRUE) {
//header("Location: hub.php");
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
echo $payCheque ." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
$sql = "UPDATE dealerEmployees SET firstName = '$_POST[editUserFirstName]', lastName = '$_POST[editUserLastName]', password = '$_POST[editUserPW]', permission = '$permission', address = '$_POST[editUserAddress]', email = '$_POST[editUserEmail]', phone = '$_POST[editUserPhone]' WHERE id = $selectedId";
if ($connect->query($sql) === TRUE) {
header('Location: hub.php');
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
//$connect->close();
?>
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
And in your case, you are using echo before header()
So you can use a redirect method(that i use in all my projects, no problems ever)
<?php
if ($connect->query($sql) === TRUE) {
echo "<script> parent.self.location = \"hub.php\";</script>";
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
?>
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);
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>
';