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
}
}
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?
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 :)
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);
}
?>
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