PHP - Form error alerts displays on page load - php

i am a newbee and just learning along the way. I have two forms on a page (I have only shown one of them as the other form is the same code with different variables). Both their error messages display on page load. How can I stop this?
I have read multiple posts regarding this but I still cannot find a solution.
<?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
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$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('Saved')</script>";
}
} else {
echo "<b>Oops! we have an issu </b>";
}
?>

You have an else after your if (isset($_POST['Update'])). Inside that else you are displaying errors as if the user tried to submit the form. $_POST['Update'] will only be set if the user tried to submit the form. Move that else inside your if:
if (isset($_POST['Update'])) {
/* a bunch of code to insert into the DB */
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}else{
echo "<b>Oops! we have an issu </b>";
}
}
In Addition:
The commenter is right. You are at risk for SQL Injection. Please use prepared statements instead.

The problem is your else statement is running every time the variable $_POST['Update'] is not set.
One way to fix this is to move your error message inside your form checking code. Something like this would work:
if (isset($_POST['Update'])) {
/* unchanged code snipped */
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
Hope that helps!

Related

Having problems retrieving from mysql to populate form

I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>
To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">
Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>

Form and SQL Validation using PHP

When user clicks on the Save, check whether the data is successfully inserted record to the table, and display a proper message accordingly. If forms are empty then the error message should be shown and database should not have any record.
//SAVE
if (isset($_POST['SAVE'])) {
$Name = $_POST['name'];
$City = $_POST['city'];
$query = "Insert Into Info Values('$Name','$City')";
$result = mysqli_query($con, $query) or die ("query is failed" . mysqli_error($con));
$Name = '';
$City = '';
if(mysqli_affected_rows($con)>0) {
echo "record is saved";
}else {
echo "record is not saved";
}
I can only do validation through php. I am not sure if I am doing this right. So far I can get the "record is saved" message on my form, but I cannot get the latter if the form are empty. It just make an empty record in my database.
Untested Code:
if (!isset($_POST['SAVE'], $_POST['name'], $_POST['city'])) { // avoid Notices
echo "Missing required submission data";
} elseif (!strlen(trim($_POST['name']))) { // validate however you wish
echo "Name data is not valid"; // explain however you wish
} elseif (!strlen(trim($_POST['city']))) { // validate however you wish
echo "City data is not valid"; // explain however you wish
} elseif (!$con = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $con->connect_error <-- never show actual error details to public
} elseif (!$stmt = $con->prepare("INSERT INTO Info VALUES (?,?)")) {
echo "Error # prepare"; // $con->error; // don't show to public
} elseif (!$stmt->bind_param("ss", $_POST['name'], $_POST['city'])) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
echo "Error # execute"; // $stmt->error; // don't show to public
} else {
echo "Insert Successful";
}
The validation conditions on the submission data ensure that the values are not empty and they are not completely comprised of whitespace characters. If you wish to refine the validation requirement further, just update the conditions.
If you want to simply ensure that $_POST['name'] and $_POST['city'] are not empty, you can replace the first three conditionals with
if (empty($_POST['SAVE']) || empty($_POST['name']) || empty($_POST['city'])) {
echo "Submission data is missing/invalid";
}...
If you don't use a prepared statement, then name values like Paul O'Malley will break your query. Worse, if someone wants to try to run some injection attacks, your query is vulnerable.
Checking affected_rows() is unnecessary. If there is no error message from the query execution, the INSERT query was a success.
The above suggestions are all best practices which I urge you to adopt.
Checking isset($_POST['SAVE']) only tells you if "SAVE" is set. It does not tell you if the fields have values.
To do the validation in PHP, use something like the following:
if (isset($_POST['SAVE'])) {
$Name = $_POST['name'];
$City = $_POST['city'];
if ($Name && $City)
{
//...
//code to insert data into the database goes here
//...
if(mysqli_affected_rows($con)>0) {
echo "record is saved";
}else {
echo "record is not saved (error saving)";
}
} else {
echo "record is not saved (input was empty)";
}
}
The key being the if ($Name && $City) check.
Alternately, if you want to rely on mysql to reject the insert on blank values, then make sure the fields in the mySql table are not nullable and then change this part of your code: (but this would be moving the validation to MySql)
$Name = $_POST['name']?$_POST['name']:null;
$City = $_POST['city']?$_POST['city']:null;

Updating SQL with form and PHP. Values resetting to 0 on submit?

I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning PHP.
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: index.php");
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");

How to use inform users of form submission errors if header is used to redirect the user to another page

When the user submits the form, the form information is posted to a php file and the php file redirects the user straight away to the next webpage once the form is submitted by using the header function. I have already validated the form using HTML and Javascript however the PHP has validation in it so that any errors that get past the Javascript and HTML are identified and the user is notified, however this is not possible at the minute as the user is redirected before they are notified.
How would I identify the user if the PHP locates an error?
Is it necessary as will the only errors be by people who are intentionally trying to be malicious?
My code is:
<?php
header("location: (next webpage)");
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['email_banned'])){
// Adds name to array
$data_missing[] = 'Email';
} else {
// Trim white space from the name and store the name
$email_banned = trim($_POST['email_banned']);
}
if(empty($_POST['notes'])){
// Adds name to array
$data_missing[] = 'Notes';
} else {
// Trim white space from the name and store the name
$notes = trim($_POST['notes']);
}
if(empty($data_missing)){
require_once('mysqli_connect.php');
$query = "INSERT INTO banned_emails (id, email_banned, created_on, notes) VALUES ( NULL, ?, NOW(), ?)";
$stmt = mysqli_prepare($dbc, $query);
//i Interger
//d Doubles
//s Everything Else
mysqli_stmt_bind_param($stmt, "ss", $email_banned, $notes);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
mysqli_stmt_close($stmt);
mysqli_close($dbc);
} else {
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
} else {
echo 'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
}
?>
Thanks :)
You can use $_SESSION to store errors, and retrieve them later.
$_SESSION['errors'] = array('an error message', 'a second error message');
Then in the script the user has been redirected to :
while($err = array_shift($_SESSION['errors'])){
?>
<p class='p_error'><?=$err?></p>
<?php
}

HTML form inserts data into SQL using PHP while going to another webpage

I want my form to insert the data into an SQL database using PHP which is a separate file while, going to another webpage once the form has been submitted.
<form action="http://localhost:8888/phpv1/studentadded.php" method="post">
<input type="submit" name="submit" value="Send">
Currently I use the following code which works in the sense that it invokes the PHP and causes it to submit the data into the SQL database. However it goes to a blank webpage (the page of the PHP) instead of going to an alternate webpage. What code should I add so that when submitted it goes to an alternate web page?
Thanks :)
Here is my full php script:
<?php
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['email_banned'])){
// Adds name to array
$data_missing[] = 'Email';
} else {
// Trim white space from the name and store the name
$email_banned = trim($_POST['email_banned']);
}
if(empty($_POST['notes'])){
// Adds name to array
$data_missing[] = 'Notes';
} else {
// Trim white space from the name and store the name
$notes = trim($_POST['notes']);
}
if(empty($data_missing)){
require_once('mysqli_connect.php');
$query = "INSERT INTO banned_emails (id, email_banned, created_on, notes) VALUES ( NULL, ?, NOW(), ?)";
$stmt = mysqli_prepare($dbc, $query);
//i Interger
//d Doubles
//s Everything Else
mysqli_stmt_bind_param($stmt, "ss", $email_banned, $notes);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
header("Location: http://localhost:8888/phpv1/test2.php");
mysqli_stmt_close($stmt);
mysqli_close($dbc);
} else {
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
} else {
echo 'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
}
?>
Have I placed the header in the right place? (I will obviously change the content of the header)
You should edit studentadded.php so it redirects to the desired destination after processing the data.
header("Location: http://example.com/");
I would do it something like this:
if(isset($_POST['submit'])) {
//Your insert into the DB etc
header("location: http://www.google.com");
}

Categories