PostgreSQL INSERT statement not working in PHP with PDO - php

This one is leaving me scratching my head. I'm sure I'm missing something simple, but for the life of me I can't see what when I compare it to other INSERT statements I've written that work just fine. The parameters are being passed when I check the network tab in developer, but it won't forward to the page specified in the header, and the table is not updated with information when I fill in the form.
Here is the function I wrote in the model layer:
function add_yarn($yarnbrand, $yarnamount, $yarnweight, $yarncolor) {
global $db;
$query = 'INSERT INTO yarn
(yarnbrand, yarnamount, yarnweight, yarncolor)
VALUES
(:yarnbrand, :yarnamount, :yarnweight, :yarncolor)';
$statement = $db->prepare($query);
$statement->bindValue(':yarnbrand', $yarnbrand);
$statement->bindValue(':yarnamount', $yarnamount);
$statement->bindValue(':yarnweight', $yarnweight);
$statement->bindValue(':yarncolor', $yarncolor);
$statement->execute();
$statement->closeCursor();
}
Here is the control layer in for the action associated with that function in index.php:
case 'yarn_add' :
$yarnbrand = filter_input(INPUT_POST, 'yarnbrand');
$yarnamount = filter_input(INPUT_POST, 'yarnamount', FILTER_VALIDATE_INT);
$yarnweight = filter_input(INPUT_POST, 'yarnweight');
$yarncolor = filter_input(INPUT_POST, 'yarncolor');
if ($yarnbrand == NULL || $yarnamount == NULL ||
$yarnweight == NULL || $yarncolor == NULL) {
echo 'Empty or invalid data input.';
} else {
add_yarn($yarnbrand, $yarnamount, $yarnweight, $yarncolor);
header('Location: index.php?action=view_yarn');
}
break;
and here is the view layer with the add form:
<?php include '../view/header.php'; ?>
<main>
<h1>Add Yarn</h1>
<form action="index.php" method="post" id="add_yarn_form">
<input type="hidden" name="action" value="yarn_add">
<label>Brand:</label>
<input type="text" name="yarnbrand"> <br>
<label>Weight:</label>
<input type="text" name="yarnweight"><br>
<label>Amount:</label>
<input type="text" name="yarnamount"><br>
<label>Color:</label>
<input type="text" name="yarncolor"><br>
<label> </label>
<input type="submit" value="Save Changes"><br>
</form>
<div class="bottomtext">
View Yarns
View Supplies
</div>
</main>
<?php include '../view/footer.php'; ?>
I appreciate any help!

Maybe a variable with an illegal caracter ? You don't use filters in your filter_input, expected for the integer variable.
Take a look on the manual :
If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.
Not really secure :/

Related

How do I update a row of data in mysql using PHP?

I'm attempting to create a form where the user can update their profile details but it just doesn't seem to work.
I'm quite the beginner in server side programming so I'm piecing together code from different tutorials viz. from http://www.codingcage.com/2015/04/php-login-and-registration-script-with.html
The class.user.php file, which originally only had the code for login, and signup. I copied the signup function and changed some stuff to update instead:
public function update($id,$uname,$umob,$uaddr,$uacc,$upass) {
try {
$upass = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->conn->prepare(
"UPDATE users
SET
id = :id,
name = :uname,
mobile = :umob,
address = :uaddr,
accNo = :uacc,
password = :upass
WHERE id = :id"
);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":upass", $upass);
$stmt->bindParam(":uacc", $uacc);
$stmt->bindParam(":uname", $uname);
$stmt->bindParam(":uaddr", $uaddr);
$stmt->bindParam(":umob", $umob);
$stmt->execute();
return $stmt;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
and in view_account.php: (edit 3, whole file including code corrections by #e_i_pi):
<?php
ini_set("error_log", "/path/to/error.log");
require_once("session.php");
require_once("class.user.php");
$auth_user = new USER();
$stmt = $auth_user->runQuery("SELECT * FROM users WHERE consumer-no=:cno");
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$session->is_loggedin()){
// session no set redirects to login page
$session->redirect('index.php');
}
if(isset($_POST['submit']) && $_POST['submit'] === 'save') {
$uname = strip_tags($_POST['full-name']);
$umob = strip_tags($_POST['mobile']);
$uaddr = strip_tags($_POST['addr']);
$uacc = strip_tags($_POST['bank-acc']);
$id = strip_tags($_POST['id']);
$upass = strip_tags($_POST['password']);
if($uname=="") {
$signuperror[] = "Please Enter Your Full Name!";
}
else if($umob=="") {
$signuperror[] = "Please Enter Your Mobile No.!";
}
else if($uaddr=="") {
$signuperror[] = 'Please Enter Your Address!';
}
else if($upass=="") {
$signuperror[] = "Please Enter a Password!";
}
else if(strlen($upass) < 6) {
$signuperror[] = "Password must be atleast 6 characters";
}
else {
try {
// I commented out these for some weird reason I can't even rememebr
// $stmt = $auth_user->runQuery("SELECT id FROM users WHERE id=:id");
// $stmt->execute(array(':id'=>$id));
// $row = $stmt->fetch(PDO::FETCH_ASSOC);
$auth_user->update($id,$uname,$umob,$uaddr,$uacc,$upass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gas Booking</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>gas booking</h1>
<nav>
<ul>
<li>home</li>
<li>booking</li>
<li>payment</li>
<li>ticket</li>
<li>view account</li>
<li>bank</li>
<li>logout</li>
</ul>
</nav>
</header>
<div class="content">
<h2>Edit Your Profile Details</h2>
<form method="post" action="view_account.php">
<input type="hidden" id="id" name="id" value="<?php echo $_SESSION['id']; ?>">
<label for="full-name" class="input-info">
<div class="label">full name</div>
<input type="text" id="full-name" name="full-name" value="<?php echo $_SESSION['name']; ?>">
</label>
<label for="mobile" class="input-info">
<div class="label">mobile number</div>
<input type="text" id="mobile" name="mobile" value="<?php echo $_SESSION['mob']; ?>">
</label>
<label for="addr" class="input-info">
<div class="label">address</div>
<input id="addr" name="addr" value="<?php echo $_SESSION['addr']; ?>">
</label>
<label for="bank-acc" class="input-info">
<div class="label">bank account number</div>
<input type="text" id="bank-acc" name="bank-acc" value="<?php echo $_SESSION['accNo']; ?>">
</label>
<hr>
<label for="password" class="input-info">
<div class="label">password</div>
<input type="password" id="password" name="password">
</label>
<button type="submit" name="submit" value="save">
Save Changes
</button>
</form>
</div>
</body>
</html>
and my table is as follows:
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`consumerNo` varchar(15) NOT NULL,
`password` varchar(255) NOT NULL,
`accNo` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`mobile` bigint(10) NOT NULL,
`balance` bigint(10) NOT NULL,
`joining_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I'm sure I've done something stupid. I'd really appreciate pointing me in the right direction, I sat with it till 5:00am and am feeling frustrated with myself.
The connection with the db is working, classes are properly included. Let me know if you need more information. Thank you!
The project can be downloaded here: https://www.dropbox.com/s/9v69m18l82n1t46/gas.zip?dl=0. Warning the code's kind of a mess.
Update
You seem to be doing the following in view-account.php:
try {
$auth_user->update($id,$uname,$umob,$uaddr,$uacc,$upass);
} catch(PDOException $e) {
echo $e->getMessage();
}
Yet you're already try/catch'ing within your update() method. I assume it never gets to this as an error in your if/elseif/elseif/else/etc checks is picked up. Could you modify it to look like this for testing purposes:
$errors = [];
if ($uname == "") {
$errors[] = "Please Enter Your Full Name!";
}
if ($umob == "") {
$errors[] = "Please Enter Your Mobile No.!";
}
if ($uaddr == "") {
$errors[] = 'Please Enter Your Address!';
}
if ($upass == "") {
$errors[] = "Please Enter a Password!";
}
if (strlen($upass) < 6) {
$errors[] = "Password must be atleast 6 characters";
}
// check errors
if (!empty($errors)) {
print_r($errors);
return false;
}
// otherwise try the query:
$obj = $auth_user->update($id, $uname, $umob, $uaddr, $uacc, $upass);
and let us know what comes up!
I assume you'd have an error thrown, something along the lines of;
SQLSTATE[HY093]: Invalid parameter number
This is because you're trying to bind on :id twice. You have to remember that a users ID is unique and should never change (right?).
Modify your query to look like this:
$stmt = $this->conn->prepare(
"UPDATE users
SET
name = :uname,
mobile = :umob,
address = :uaddr,
accNo = :uacc,
password = :upass
WHERE id = :id"
);
Notes
You're best to modify your "password change" functionality to have the user confirm their password (if(PASSWORD == PASSWORD_REPEAT) { .... SET PASSWORD...)
Don't pass the user ID inside the form. It's insecure. Since it's in $_SESSION already, simply access it like that within your view-account.php file!
Why the above you ask? Simple. If I inspect your <form... element, I could easily modify that hidden input to be some other users ID, allowing me to change their passwords/information/etc.
And since it looks like you're dealing with "Bank" related information, I'd suggest doing this asap! Imagine If I could change "Barack Obama's" bank password and access his account.
Your form also doesn't have any action attribute...so it does nothing.. Best change that to your view-account.php page
I suggest removing your use of strip_tags(). It could ruin some fields (i.e. passwords). You're also already binding/preparing your statements (Props to you on that, good work!)
While we're at it, you might want to look at your view-account.php file, It could be modified to stop the use of all those if / elseif / elseif / else statements. You're essentially checking all your fields and if it fails, you're adding an error message to an array, but if it passes you're running the query, this is bad practice. You should look at doing something similar to (pseudo code):
$errors = [];
if (!check_fields()) {
$errors[] = THE FIELD ERROR MESSAGE;
}
// now check if your errors are empty or not
if(!empty($errors)) {
// this means we have errors in the form.
// return the errors array to the front end and handle it appropriately.
return $errors;
}
// otherwise we can try the query here now!
try {
// YOUR SQL UPDATE QUERY
} .....`
Righto, you have a few problems with things not matching up etc., which is to be expected if you are starting out.
Let's start with the HTML form. There are two issues here:
The form has no action property, so it doesn't get submitted anywhere
The submit button is given a specific name and no value. (While some will consider this okay, maybe we can try a different approach which is a little more sensible)
I would suggest your HTML form be changed to this:
<form method="post" action="view-account.php">
<input type="hidden" id="id" name="id" value="<?php echo $_SESSION['id']; ?>">
<label for="full-name" class="input-info">
<div class="label">full name</div>
<input type="text" id="full-name" name="full-name" value="<?php echo $_SESSION['name']; ?>">
</label>
<label for="mobile" class="input-info">
<div class="label">mobile number</div>
<input type="text" id="mobile" name="mobile" value="<?php echo $_SESSION['mob']; ?>">
</label>
<label for="addr" class="input-info">
<div class="label">address</div>
<input id="addr" name="addr" value="<?php echo $_SESSION['addr']; ?>">
</label>
<label for="bank-acc" class="input-info">
<div class="label">bank account number</div>
<input type="text" id="bank-acc" name="bank-acc" value="<?php echo $_SESSION['accNo']; ?>">
</label>
<hr>
<label for="password" class="input-info">
<div class="label">password</div>
<input type="password" id="password" name="password">
</label>
<button type="submit" name="submit" value="save">
Save Changes
</button>
</form>
Now, once this form is submitted to view-account.php, we want to make sure that the submit button is "save" mode, so we change the first line of view-account.php to this:
if(isset($_POST['submit']) && $_POST['submit'] === 'save') {
This approach means we can have different submit buttons on the same form - we may in future want actions for save, delete, archive, etc.
Lastly, I notice that the id field in your database table is declared AUTOINCREMENT. Great, exactly what you want, database id fields are internal unique identifiers that we let the database determine (in 99% of cases - there are edge cases where we like to define our own UIDs). This means that there is a problem with your UPDATE statement. You cannot update an auto-incremented field. In your class.user.php file, change the declaration of $stmt to this:
$stmt = $this->conn->prepare(
"UPDATE users
SET
name = :uname,
mobile = :umob,
address = :uaddr,
accNo = :uacc,
password = :upass
WHERE id = :id"
);
This should fix your code issues, I think I got everything. BUT, there may be other problems. If your code still does not work, I would suggest checking your error logs. If you're not sure where they are, either check your php.ini file to see what the error log location is, or override the default location by putting this at the top of the page you're trying to debug:
ini_set("error_log", "/path/to/error.log");

PHP Server Side Form Validation.Empty Form fields are inserted into database

I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}

undefined index error while trying to get value returned from the link?

I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

PHP $_POST strange behavior, only works 2nd time form is posted

I'm genuinely stuck on something VERY irritating. After a couple of hours of trying everything I know I've ended up here to see if anyone can help. Here's the general idea.
I want one certain page to be available with a password sent via a form. There is no user, and the password will not change. This should be easy, right!
I've got a form which submits with the method set to post, and the action set to $_SERVER['PHP_SELF']. The plan is, when the password variable I've pre-defined matches what is typed in the form, one set of content shows on the page, when it doesn't you get a different set of content (a form).
Here's what's weird. When looking at a print_r I see whatever I submit in the form in the array, but when I put the right password in the array fills, then empties quickly. I see this on the page reload. It completely empties itself. Even stranger, the 2nd time I do this, it works. What am I missing here? I'd love to know!
Many thanks, and Merry Christmas.
---- some code ----
The form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
Some PHP from the top of the file;
$pass = '12846565488374';
if($_POST['pass']){ $login = $_POST['pass']; } else { $login = 'empty'; }
if($login != $pass) { $show = 0; } elseif($login == $pass){ $show = 1; }
----- solved ------
Turns out this was a JS plugin reloading the page without me knowing.
Try:
if(isset($_POST['pass']) AND $_POST['pass'] == $pass) {
$show = 1;
} else {
$show = 0;
}
Copied from the comment below:
PHP can't update anything after the page is loaded from the server... You can only use refresh or JS/AJAX to change the content. It would be much easier if you uploaded the whole page somewhere.
Try:
<?PHP
if(isset($_POST['pass'])
{
$pass = '12846565488374';
($_POST['pass'] == $pass)? $show = 1 : $show = 0;
echo $show;
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
<?PHP
}
?>
<?php
if (isset($_POST['pass']))
{
if ($_POST['pass'] == $pass)
{
$show = 1;
echo $show;
}
else
{
$show = 0;
echo $show;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
perhaps something like this?
the purpose for the echo is to show when the correct password is entered, $show changes to 1 and when wrong, changed to 0
Edit:
Your Parameters Checking for $show
<?php
if (isset($show) AND $show === 1)
{
echo "The Variable Is Set To 1";
}
elseif (isset($show) AND $show === 0)
{
echo "The Variable Is Set To 0";
}
?>
This is tested and working with your code.
Thank you for your help everyone - as Matanya said, it was indeed a Javascript issue that was reloading the page. It's a music player and it was placed the "true" part of the IF statement. I don't understand why it has this effect, but at least I know. I thought the error would be in my PHP. Here's the player in question: SCM Music Player http://scmplayer.net
Thanks again.

Categories