I have this code:
Episode.php
<?$feedback = new feedback;
$articles = $feedback->fetch_all();
if (isset($_POST['name'], $_POST['post'])) {
$cast = $_GET['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$post = nl2br ($_POST['post']);
$ipaddress = $_SERVER['REMOTE_ADDR'];
if (empty($name) or empty($post)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO comments (cast, name, email, post, ipaddress) VALUES(?, ?, ?, ?, ?)');
$query->bindValue(1, $cast);
$query->bindValue(2, $name);
$query->bindValue(3, $email);
$query->bindValue(4, $post);
$query->bindValue(5, $ipaddress);
$query->execute();
} }?>
<div align="center">
<strong>Give us your feedback?</strong><br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="episode.php?id=<?php echo $data['cast_id']; ?>" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name" /> / <input type="text" name="email" placeholder="Email" /><small style="color:#aa0000;">*</small><br /><br />
<textarea rows="10" cols="50" name="post" placeholder="Comment"></textarea><br /><br />
<input type="submit" onclick="myFunction()" value="Add Comment" />
<br /><br />
<small style="color:#aa0000;">* <b>Email will not be displayed publicly</b></small><br />
</form>
</div>
Include.php
class feedback { public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM comments");
$query->bindValue(1, $cast);
$query->execute(); return $query->fetchAll();
} }
This code updates to the database as it is suppose to. But after submission it reloads the current page as mentioned in the form action.
But when I refresh the page to see the comment being added it asks to re submit. If I hit submit then the comment adds again.
How can I stop this from happening?
Maybe I could hide the comment box and display a thank you message but that would not stop a repeat entry.
Please help. Thank you.
Kev
You need to add a redirect in there. So at the bottom of your POST block add
if(isset($_POST['name'], $_POST['post'])) {
// Do POST stuff here
header('Location: your/url/here');
exit;
}
This sends a 302 redirect to the browser and it does a clean load of the page. Since this is a GET operation, there's no reload issues either.
After you have run
$query->execute();
you could unset your variables:
unset($name, $email, $post);
Related
I have a html form which includes a question involving three radio buttons. I want the word 'road', 'both' or gravel' to be saved to my database. This field is set up as a varchar in the database.
This is my html:
<div class="form-group">
<label>Do you prefer just road or gravel/trail cycling as well?</label>
<label for="road">Just road</label>
<input type="radio" name="bike_terrain" id="road" value="road" required/>
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="both">Both</label>
<input type="radio" name="bike_terrain" id="both" value="both" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="gravel">Just gravel/trail</label>
<input type="radio" name="bike_terrain" id="gravel" value="gravel" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
</div>
I am then using php to validate the input is not empty:
if(empty($_POST["bike_terrain"])){
$bike_terrain_err = "Please select a bike terrain.";
} else {
$bike_terrain = isset($_POST["bike_terrain"]);
}
And php to send it to my localhost database:
if(empty($username_err) && empty($email_err) && empty($bike_terrain_err)) {
// Prepare an insert statement
$sql = "INSERT INTO users (username, email, terrain) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_email, $param_terrain);
// Set parameters
$param_username = $username;
$param_email = $email;
$param_terrain = $bike_terrain;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Oops! Something went wrong. Please try again later.248";
}
}
}
(Note: I have cut out some of the other fields that I am inserting for simplicity)
$bike_terrain has previously been initialised as a string.
The problem is that nothing is being saved to the terrain field in my database and I don't know why!
Thank you very much! All suggestions, thoughts or ideas are very welcome.
Something like this (untested) should do the trick. you save the same radio with the same name so it would look like a selection somehow.
Had to quickly code from my mobile device XD
<?php
if(isset($_POST['submit'])){
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'people_db'
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot connect'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_POST['fullname']);
$gender = mysqli_real_escape_string($con,$_POST['gender']);
$q = "insert into employeedb (fullname, gender) values ('".$fullname."', '".$gender."')";
mysqli_result($con,$q);
echo 'Data Saved to Database!';
}
?>
<html>
<head>
<title>Save Radio to DB</title>
</head>
<body>
<form name="people" method="POST" action="index.php"
<input type="text" name="fullname" placeholder="Enter your name"/><br/>
<input type="radio" name="gender" value="Male"/>
<input type="radio" name="gender" value="Female"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
When I submit my form to add a comment reply, the entire div that surrounds the form disappears. The comment still get added to the database but the div just disappears and I have to refresh my page. Any ideas ?
<div id="comment_reply" class="reply_div">
<form action="reply_comment.php?comment_id=<?php echo $comment_id; ?>"
method="POST">
<input type='hidden' name='comment_id' value="<?php echo $comment_id ?>">
<textarea name='reply_comment' id='reply_comment'
placeholder='Reply...'></textarea>
<button id="reply_button" name="reply_button">Add</button>
</form>
</div>
reply_comment.php:
<?php
require 'config/connect.php';
$con = new mysqli(...$dbCredentials);
include 'includes/classes/User.php';
include 'includes/classes/Post.php';
include 'includes/classes/Notification.php';
$userLoggedIn = $_SESSION['user_session'];
$comment_id = $_GET['comment_id'] ?? 0;
if (isset($_POST['reply_button'])) {
if (empty($_POST["reply_comment"])) {
echo "Reply can't be empty. Try Again";
exit();
}
$reply_body = trim(strip_tags(filter_var($_POST['reply_comment'],
FILTER_SANITIZE_STRING)));
$stmt = $con->prepare("INSERT INTO comment_replies (reply_body, username, comment_id)
VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $reply_body, $userLoggedIn, $comment_id);
$stmt->execute();
header($_SERVER['HTTP_REFERER']);
exit();
}
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_REQUEST['teamname'];
$email = $_REQUEST['email'];
$password = (md5($_REQUEST['password']));
$query = "UPDATE users SET email = ?,password = ? WHERE name = ?";
$statemnt = $conn->prepare($query);
$statemnt->bind_param('sss',$email,$password,$name);
$statemnt->execute(); echo $name,$email,$password; var_dump();
$statemnt->close(); $conn->close(); } ?>
managed to get the SELECT Statement figured out before this one and still having issues with the UPDATE - a form above this php snippet and is suppose to fill out $email $password and $name
<form method="post" action="">Team Name:<br>
<input type="text" name="teamname" value="<?php echo $name;?>">
<br>Email:<br><input type="text" name="email" value="<?php echo $email;?>">
<br>Password:<br><input type="text" name="password" value="">
<br><br><input type="Submit" value="Update the Record" name="Submit">
</form>
EDITED TO THE FOLLOWING (there is code above this part and below dont expect u want to see the rest of my html code - the bottom is what i am have trouble with):SELECT STATEMENT and var_dump is working but when i enter a password into the form it doesnt trigger the Submit and ultimately the UPDATE Statement - i have worked on it today again to no avail. pls any help would be appreciated not sure what im doing wrong - also var_dump at the bottom is outputing all of the values now
<?php
if (isset($_POST['submit'])) {
$sql = $conn->prepare("UPDATE users SET email=? , password=? WHERE team=?");
$postedemail=$_POST['teamemail'];
$postedpassword= $_POST['teampassword'];
$sql->bind_param("ssi",$postedemail,$postedpassword,$_POST["mySelect"]);
if($sql->execute()) {
$success_message = "Edited Successfully";
} else {
$error_message = "Problem in Editing Record";
}
var_dump($postedpassword);
var_dump($postedemail);
}
$stmt = $conn->prepare("SELECT team, name, email, password FROM users WHERE team = ?");
$stmt->bind_param("i", $_POST["mySelect"]);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($rows = $result->fetch_assoc()) {
$name = $rows['name'];
$email = $rows['email'];
$password = $rows['password'];
}
var_dump($password);
var_dump($name);
var_dump($email);
var_dump($_POST['mySelect']);
$stmt->close();
?>
<?php if(!empty($success_message)) { ?>
<div class="success message"><?php echo $success_message; ?></div>
<?php } if(!empty($error_message)) { ?>
<div class="error message"><?php echo $error_message; ?></div>
<?php } ?>
<form name="frmUser" method="post" action="">
<label>NAME:</label>
<input type="text" name="teamname" class="txtField" value="<?php echo $name?>">
<label>EMAIL:</label>
<input type="text" name="teamemail" class="txtField" value="<?php echo $email?>">
<label>PASSWORD</label>
<input type="text" name="teampassword" class="txtField" value="">
<input type="submit" name="submit" value="Submit" class="demo-form-submit">
</form>
thanks
You have this at the begining of your script : $selectedOption = $_POST["mySelect"];
Nowhere in your code (especially in your <form></form>) I see any input named "mySelect"
Add this field in your form and the problem should be solved.
var_dump(); helps a lot debugging.
I have read multiple posts on this on here, but none seem to do the trick, maybe i am just misunderstanding as i new to this.
I have a form that inserts into a database and then echo's out the data, perfectly!, my problem is because the form is on a users accounts page, when you logout all the information disappears. I am aware that i will have to save my $_POST variables into a $_SESSION.
But even when saved into a session, the data echo'd out still disappears once logged out, when logging back in. What is the correct way to save a$_POST into a $_SESSION.
I am currently using :
// Save $_POST to $_SESSION
$_SESSION['fname'] = $_POST;
Is there a better way here is my code:
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=<?php echo $c_id ?>" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : '';?>" required>
<input type="text" id="lname" name="lname" value="<?php echo isset($_POST['lname']) ? $_POST['lname'] : '';?>" required>
<input type="text" id="email" name="email" value="<?php echo $_SESSION['Cus_Email']; ?>" required>
<input type="number" id="phone" name="phone" value="<?php echo isset($_POST['phone']) ? $_POST['phone'] : '';?>"required>
<input type="submit" name="Update" value="Update">
<br>
</form>
PHP
<?php
if (isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
// Save $_POST to $_SESSION
$_SESSION['fname'] = $_POST;
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone) VALUES (?,?,?,?)";
$stmt = mysqli_prepare($dbc, $insert_det);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
// if inserted echo the following messges
if ($r) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
?>
The $_SESSION['Cus_Email'] in the form is from another query.
Any help or suggestions would be much appreciated.
$_POST data should only be stored as a session variable temporarily. For example, if your user makes an error:
form.php
<?php
// This function should go in a config file, to escape data:
function html($str){
return htmlspecialchars($str, ENT_QUOTES);
}
$data = $_SESSION['form']['data'];
$errors = $_SESSION['form']['errors'];
?>
<form method="post" action="action.php">
<input type="text" name="fname" value="<?=html($data['fname'])?>" placeholder="First name">
<?php if(isset($errors['fname'])): ?>
<p>ERROR: <?=html($errors['fname'])?></p>
<?php endif; ?>
<input type="text" name="lname" value="<?=html($data['lname'])?>" placeholder="Last name">
<button type="submit">Go</button>
</form>
<?php
unset($_SESSION['form']); // You don't want to keep this data any longer.
action.php
<?php
$data = $_POST;
// Validate the data, for example:
if($data['fname'] == ''){
$errors['fname'] = "First name is required.";
}
if(!empty($errors)){
unset($data['password']); // Do not store passwords in session variables.
$_SESSION['form']['data'] = $data;
$_SESSION['form']['errors'] = $errors;
header("Location: form.php");
die;
}
// Put your database inserts here (no errors)
You should store things like first name, surname, etc, inside your database. Don't store these in $_SESSION other than in the example above.
First here is my code:
<?php
//establish connection to the database
require("database.php");
try{
// prepare and bind
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:phonenumber, :firstname)");
$stmt->bindParam(':phonenumber', $phonenumber, PDO::PARAM_STR);
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
// set parameters and execute
if(isset($_POST['phonenumber'])){ $phonenumber = $_POST['phonenumber']; }
if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; }
$stmt->execute();
}catch (Exception $e) {
echo "Could not insert data into the database $e";
exit;
}
//my attempt on checking if the data has been successfully entered in the database
$inserted = true;
?>
<h2>The Form</h2>
<hr />
<br />
<form action="" method="post">
Number: <input type="text" name="phonenumber" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />
</body>
</html>
Then I'm attempting to check if the form data has been successfully entered like this:
<?php
if($inserted = true){
echo "THE DATA HAS BEEN SUCCESSFULLY ENTERED IN THE DATABASE";
}
?>
Now as you can see I'm trying to set a variable named $inserted as true when the data is entered so that I can determine if the data has been entered successfully. But for some reason it is NOT working. It keeps giving me an error that $inserted is undefined so I wrapped it with isset() and even though that got rid of the error it however did not check to see if $inserted was set. In other words I always keep getting the echo message that it has been entered successfully even though it has not for some reason.
Help is greatly appreciated, thank you very much.
Instead of using a flag, you could use the ->lastInsertId method to check whether the last insertion was succesful.
<?php
if(isset($_POST['firstname'], $_POST['phonenumber'])) {
require('database.php');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$phonenumber = $_POST['phonenumber'];
$firstname = $_POST['firstname'];
try{
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:phonenumber, :firstname)");
$stmt->bindParam(':phonenumber', $phonenumber, PDO::PARAM_STR);
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->execute();
}
catch (Exception $e) {
echo "Could not insert data into the database $e";
echo $e->getMessage();
exit;
}
if($conn->lastInsertId() > 0) {
echo 'insertion was made';
}
}
?>
<h2>The Form</h2>
<hr />
<br />
<form action="" method="post">
Number: <input type="text" name="phonenumber" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />
</body>
</html>
Sidenote: You could also use ->rowCount() as well:
if($conn->rowCount() > 0) {
// do your thing
}