Keep text in text field after submitting - php

I am having a issue keeping text in the text field that was previously there after pushing submit. I am using this:
<input name="date" type="text" id="date" <?php if(isset($_POST['date'])){echo 'value="'.$_POST['date'].'"';} ?>/>
I also have this on successful submit so that it reloads the table but also removes whats above because it's refreshing.
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
My entire code=
<?php
// if ('POST' === $_SERVER['REQUEST_METHOD'])
if (isset($_POST['submit2']))
{
$con = mysql_connect("xx","xx_xx","xx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx_xx", $con);
$date = $_POST['date'];
$_SESSION['date'] = $_POST;
//Writes the to the server
$sql = mysql_query("INSERT INTO `reservation__date` (`reservation_id`, `reservation_date`)
VALUES
('000', '$date')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$_SESSION['DATE'] = $_REQUEST['date'];
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
mysql_close($con);
}
}
?>

If you follow the PRG principle (POST-redirect-GET), you need to track the POST data in the session.
I assume your do something like this after submit:
if (POST is fine) {
do something;
redirect;
} else {
re-render page and show feedback
}
Since the server will discard any POST data on redirect, you need to track the POST data on every submit and re-populate the POST data on page load (GET).
$_SESSION['user_POST'] = $_POST;
if (POST is fine) ...
On your page that contains the form to submit:
if (isset($_SESSION['user_POST']) {
$_POST = $_SESSION['user_POST'];
}
Ignore syntax, I'm not into PHP that much.

FOR TESTING
<?php echo $_POST['date']; ?>
try setting to is equal to true if the above is right
<input name="date" type="text" id="date" <?php if(isset($_POST['date']) === true){echo 'value="'.$_POST['date'].'"';} ?>/>

Here is your requirement
<?php
session_start();
if(isset($_REQUEST['date'])){
$_SESSION['date'] = $_REQUEST['date'];
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
}
?>
<form method="post">
<input name="date" type="text" id="date" value="<?php echo $_SESSION['date'];?>" />
<input type="submit" name="submit" />
</form>

if you are using session variable.. use session_start(); at top of you page..
check if you have method="POST" in the form because by-default its GET..
check weather you have correct action field for the form such as <form action="abc.php">
if you want to put text in value, better check the condition within the value attribute and echo the value. because even if you don't write value in HTML insert tag.. It take as value="" . which creates an ambiguous condition later.
so better do
<form action="abc.php" method="post" >
<input name="date" type="text" id="date" value="<?php if(isset($_POST['date'])){echo $_POST['date'];} ?>" />
.......................
</form
and now on abc.php
<?php
session_start(); // as you are using session variables..
if (isset($_POST['submit2']))
{
$con = mysql_connect("xx","xx_xx","xx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx_xx", $con);
$date = $_POST['date'];
$_SESSION['date'] = $_POST['date']; // POST is an array carrying many elements so be specific which element you want. inthis case it is $_POST['date'];
//Writes the to the server
$sql = mysql_query("INSERT INTO `reservation__date` (`reservation_id`, `reservation_date`) VALUES ('000', '$date')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$_SESSION['DATE'] = $_REQUEST['date'];
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
mysql_close($con);
}
}
?>
hope this will help you...

Related

If clause does not give update only works insertion. Why update is not working?

I want to update and insert conditionally but query always goes "Insert" data. No "update" anyway. My code is below:
<form method="post" action="">
<label>ID: </label> <input type="text" name="id">
<label>Subject: </label> <input type="text" name="subject">
<input type="submit" name="submit">
</form>
<?php
$conn = new mysqli("localhost", "root", "", "zidm");
$id=$_POST['id'];
$subject=$_POST['subject'];
if (isset($_POST['submit'])){
$sql = "UPDATE exam SET subject = '$subject' WHERE id = '$id'";
mysqli_query($conn,$sql);
echo "Data Updated";
}
else {
$sql="INSERT INTO exam (subject) VALUES ( '$subject)";
mysqli_query($conn,$sql);
echo "Data Inserted";
}
?>
The issue is that you are checking for form submission but also have an else statement which will always fire on page load. You need to wrap your entire logic in the form submission check and then check for the id parameter.
// Form was submitted
if (isset($_POST['submit'])) {
if (!empty($_POST['id'])) {
// Update
} else {
// Insert
}
}

Unable to update database row in PHP with $_POST variable

I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

Creating new rows in mysql when refreshing page, why?

I've done a php script that will create a title and a text and load it to my database(mysql). When i press submit the script runs and create 1 row right and then like 3-5 empty rows.
The same thing happens when i refresh the page(empty form), 2 new empty rows shows in my database?
How do i solve it?
<?php
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
<form method="post" onSubmit=window.location="index.php">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/> <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10">
</textarea><br/>
<input type="submit" value="Publicera nyhet">
</form>
Your INSERT query is executing every time when page loads, set a POST variable to check whether the form has been submitted or not and why you are using event attribute window.location for submitting form, you can simply use action attribute and set that value either blank or the file name where you want to send your data.
<form action="" method="post">
OR
<form action="index.php" method="post">
Your date variable is also wrong. To generate date into YYYY-MM-DD format write like below
$date = date('Y-m-d');
Your script may like this
if(isset($_POST['submit'])) {
your post variables and insert query goes here
}
You can also insert a hidden input field into your form tag like so
<form action="" method="post">
<input type="hidden" name="save" value="details">
other HTML code goes here
</form>
in that case you test the post variable like this
if(isset($_POST['save']) && $_POST['save'] === "details") {
your post variables and insert query goes here
}
First learn the basic concept about PHP from http://www.php.net/ and search for appropriate question over here before asking any question.
Wrap your php code around condition to check if the form is submitted or not. Like:
<?php
if(isset($_POST['submit')){
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
Always catch form submission. You can use isset() with this:
<?php
$con = mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Y-m-d"); // put the correct format on the date
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '$date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header('Location: index.php'); // always redirect
}
?>
<form method="post" action="">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/><textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea><br/>
<input type="submit" name="submit" value="Publicera nyhet" />
<!-- ^^ add a name -->
</form>
You should check if $_SERVER['REQUEST_METHOD'] is POST and only then run the INSERT statement.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>

Query not updating not sure why

For some reason this script isn't updating the database properly according to the query. Does anybody have any idea why the script isn't updating? Please let me know!
<?php
session_start();
include '../connect.php';
if(!isset($_SESSION['id'])){
header("Location: ../index.php");
}
if(isset($_POST['submit'])){
$id=$_POST['id'];
$postid=$_POST['postid'];
$content=$_POST['content'];
$title=$_POST['title'];
echo "<pre>";
print_r($_POST);
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
}
$upd=mysql_query("UPDATE replies SET reply_content='$content' WHERE reply_id='$postid'");
if(!$upd){
echo 'Error: '.mysql_error();
}
} else {
if (isset($_GET['id'])){
$postid = $_GET['id'];
$id=$_SESSION['id'];
$q = mysql_query("SELECT * FROM `replies` where `reply_id`='$postid'");
if(!$q){
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_assoc($q);
$q2 = mysql_query("SELECT topic_subject FROM `topics` where `topic_id`='$postid'");
$res2 = mysql_fetch_assoc($q2);
if(!q2){
echo 'Error: '.mysql_error();
}
if ($res['reply_by'] == $id){
} else {
header("Location: ../pagenotfound.html");
}
}
?>
<form action="edit.php">
<input type="text" name="title" value="<?php echo $res2['topic_subject'] ?>" disabled="disabled" />
<br />
<textarea rows="20" name="content" cols="50"><?php echo $res['reply_content']?></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
If you need more info let me know!
Update: The issue is that when I click submit, it sends me to a page which still lists the form. I noticed this isuee when I tried to print_r($_POST) because it didn't actually print $_POST, I believe there is something wrong with either the form or where it checks if isset submit.
Try with:
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
// if $content is mandatory, you should put a die("error") here
}
You should check your $_POST array with a simple
echo "<pre>";
print_r($_POST);
and ensure that POST has vars you are looking for (first of all: submit)
EDIT: put print_r($_POST) BEFORE using it just before:
if(isset($_POST['submit'])){
ERROR: you forgot to set form method type. Try with:
<form action="edit.php" method="post">
Without that, form will send parameters as $_GET.
Here's a simple php-form tutorial. http://php.net/manual/en/tutorial.forms.php

Categories