I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.
The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.
If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.
The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.
I have attached my code, and commented out redundant parts.
<?php
include('php/connection.php');
//validates data for create user form
if( isset( $_POST["createUserBtn"])){
$createUsername = "";
$createUserPassword = "";
function validateFormData( $formData ) {
$formData = trim( stripcslashes( htmlspecialchars( $formData)));
return $formData;
}
if( !$_POST["createUsername"]){
$createUsernameError = "Enter a username <br>";
} else {
$createUsername = validateFormData( $_POST["createUsername"]);
}
if( !$_POST["createUserPassword"]){
$createUserPasswordError = "Enter a Password <br>";
} else {
$createUserPassword = validateFormData( $_POST["createUserPassword"]);
}
if( $createUsername && $createUserPassword) {
$query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";
// if( mysqli_query( $connection, $query)){
// echo "New User added";
// } else {
// echo "Error: ".$query."<br>".mysqli_error($connection);
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php require('static/header.php'); ?>
<?php
$createUsernameError = "";
$createUserPasswordError = "";
?>
<div class="col s8 m8 l5 valign-wrapper">
<div class="container">
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<div class="row">
<div class="col s12">
<span><h4>Create your user account - create user.php</h4></span>
<div class="row form-font">
<div class="col s12">
<div class="input-field">
<a class="red-text"><?php echo $createUsernameError; ?></a>
<input placeholder="Enter your username" type="text" name="createUsername">
<label for="email">Username</label>
</div>
<div class="input-field">
<a class="red-text"><?php echo $createUserPasswordError; ?></a>
<input placeholder="Enter your password" type="password" name="createUserPassword">
<label for="password">Password</label>
</div>
<div class="row left-align">
<div class="col s2"></div>
<div class="col s8">
<button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
</div>
<div class="col s2"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php require('static/footer.php'); ?>
</html>
Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.
If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.
However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.
So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.
An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.
So just move these lines:
$createUsernameError = "";
$createUserPasswordError = "";
to the top of your script.
P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.
Related
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
$_Get methods do not work because of how the login system is built and unsecured.I need mailuid value to bring them to their own profiles page after login.
Login Form since its's post method I should be able to grab the value on other pages and this one
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
Temporary check for the mailuid value. Supposed to grab the value form the login form a spit it back out, to check to see if it is recognized
<?php
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
?>
First I would clean this up:
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
Instead it can be written more concise:
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
if( $user ){
echo "{$user} is your username";
} else {
echo "no username supplied";
}
I prefer Boolean false over NULL, null just means it doesn't exist. Boolean false lets you know you checked it and it didn't exist. Generally should should access $_POST as few times as you can. This is because you should never trust $_POST.
$_Get methods do not work because of how the login system is built and unsecured.
Post is no more secure than get, it's quite easy to post anything to the page even without visiting the site by using something like PostMan etc. Once you assign it to a local variable you know you have at least normalized the data, even if you haven't sanitized it yet.
Also don't forget to call session_start before trying to access $_SESSION. Because of the vagueness of the question, it could be that the form works fine, just the session data isn't being maintained because you haven't started the session yet.. etc....
Hope it helps.
Personally I would clean up the HTML part that makes the form as well, so instead of this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
I would do something like this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php if (!isset($_SESSION['Id'])){ ?>
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>
<?php }else{ ?>
<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
<?php } ?>
</section>
</div>
</div>
See how much cleaner that is. Most of this is just readability issues. For example there is no need to check if isset($_SESSION['Id']) in the else if condition, because it's either set or not. This is one less place to maintain the session variable key, and it makes the code less convoluted.
As for the actual problem, as long as you are reaching the above code after submission of the form, it should work. So that leads me to believe that you have something wrong in the action.
You should get a clean page after going to includes/login.inc.php meaning there shouldn't be much in the way of HTML. One thing you can do that is real simple is just add at the top:
die(__LINE__.' of '.__FILE__);
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
//... other code
What this will do is die which kills PHP execution, but outputs the argument you passed in. In this case I'm just putting the line and file that the die is on, that way it's easier to find later. But the point is to see if you are even hitting the correct ending script or the forms action/endpoint.
I only suggest this because you are really vague in what it's current behaviour is
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
For example, this doesn't tell me if you are even hitting the right page. Now had you said something like "all it does is output no username supplied". Then I would at lest know that. As I said above it could be just an omission of sesion_start() which must be called before attempting to access any $_SESSION stuff. You should call it only once, at the top of each page that uses sessions.
Although it's not a solution, it was too much to post in a comment. I would really like to help you more, but there just isn't enough information to go on.
This is the first application I do that has a DB and PHP, so I'll expect some errors on it, but I couldn't figure what I'm doing wrong with this one.
I'm trying to pass the username from a login HTML form using JS/JQuery, into a PHP file that will verify the username and will store the content from the DB into some $_SESSION variables.
In other words, I just want to verify some content from the login page, so I can assign a variable that will hold the entire session, until the user logout.
It works correctly in the login page and I can print the variables to the console, but when I redirect using JS to a second page, after the PHP user verification, but the variables appear empty in the second page.
In the research I did, I found that both pages should have:
<?php session_start(); ?>
But even after that change, the array $_SESSION is empty.
I also confirmed the status of the session:
<?php session_status(); ?> //This result in a 2, meaning that it's working.
And the ID is the same in both pages.
As this is a larger project, I wanted to be sure that anything else was bothering with this, so I've recreated this as a smaller project and I'm still having the problem. This is what I have in the files:
Index.php
I stripped as much as possible and to verify if the problem persisted.
Here is the PHP/HTML form and also the JQUERY script that overrides the button functionality to do what I need.
This is the begining of the file:
<?php session_start(); ?>
Then the BODY:
<body class="bg-light">
<div class="flex-row d-flex justify-content-center">
<div class="col-xs-12 col-sm-8 col-md-6 col-lg-4" >
<form class="card" method="post">
<div class="card-body">
<div class="form-group">
<label for="username">User</label>
<input type="text" class="form-control" id="username" placeholder="" autocomplete="username">
</div>
<div class="form-group">
<label for="pssw">Password</label>
<input type="password" class="form-control" id="pssw" placeholder="" autocomplete="current-password">
</div>
<div class="d-flex justify-content-between">
<button class="text-center btn btn-primary" id="btn-login">Enter</button>
</div>
</div>
</form>
<div>
This is the ID of the session: <?php echo session_id(); ?>
</div>
</div>
</div>
JQuery script
$(document).ready(function () {
$("#btn-login").click(function(){
event.preventDefault();
$.ajax({
url: "mylogin.php",
type: "POST",
data: {
name: $("#username").val(),
pssw: $("#pssw").val(),
},
success: function(data){
if (data == true){
$(location).attr('href', '/page2.php');
}
}
});
});
})
Mylogin.php
Here I got the variables from the JQuery script, verify if the user and password are 'a' and then assign the $_SESSION variables.
<?php
$rawUser = $_POST['name'];
$rawPssw = $_POST['pssw'];
if($rawUser == "a" && $rawPssw == "a"){
$_SESSION["username"] = $rawUser;
$_SESSION["another"] = "New Test";
echo true;
} else {
echo false;
}
?>
Page2.php
The purpose of this one is just to print the variables, but they are empty.
Again this is the first line of the file:
<?php session_start(); ?>
And then the body:
<body class="bg-light">
<section class="container" id="login">
<div class="flex-row d-flex justify-content-center">
<div class="col-xs-12 col-sm-8 col-md-6 col-lg-4" >
<h1>This is the second page</h1>
<div>
<?php echo "Session status: " . session_status(); ?>
</div>
<div>
<?php echo "Name: " . $_SESSION["username"]; ?>
</div>
<div>
<?php echo "Role: " . $_SESSION["pssw"]; ?>
</div>
</div>
</div>
</section>
</body>
What I will expect is that the variables like $_SESSION['name'] will hold any value assigned to them by the PHP file, when the second page is loaded. That way I will be able to set up the display of some elements depending on the login of the user.
Thanks.
SOLVED: I was missing the session_start() in the begining of the mylogin.php file. Thanks to #Robot70 for noticing it.
This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
My HTML on my page is eliminated after running my PHP validation on the input form.
HTML: InsertUser.php
<?php
session_start();
require_once('File Below');
echo $errors; //Errors is local variable within insertBackend.php i know. i just wanted this example to be exact compared next to my code.
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" method="post" action="InsertUser.php">
<div class="form-group">
<label for="txtName" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" name="txtName" placeholder="Name" value="">
</div>
</div>
<div class="form-group">
<label for="txtPassword" class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" name="txtPassword" placeholder="Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnSubmit" name="insert_form" type="submit" value="Submit" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnCreate" onclick="location.href = 'createUser.php';" name="createUser" type="button" value="Create User" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnsame" onclick="location.href = 'InsertUser.php';" name="InsertUser" type="button" value="Insert User" class="btn btn-primary">
</div>
</div>
</form>
</div>
</body>
</html>
PHP Page: InsertBackend.php
<?php
session_start();
require_once('*DIRECTORY CONTAINING SQL CONNECTION*'); //works fine
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['insert_form']))
{
$_SESSION['InsertUser'] = "Insert User Pass"; //This ensures i make it INTO the method
$name= "";
$password = "";
$nameInsert = mysqil_real_escape_string($_POST['txtName']);
//^This right here. mysqli_real_escape_string();
$passInsert = mysqil_real_escape_string($_POST['txtPassword']);
//^This right here. mysqli_real_escape_string();
$errors = array();
if(empty($nameInsert))
{
array_push($errors, "Please enter your Name");
}
if(empty($passInsert))
{
array_push($errors, "Please enter your password");
}
if(count($errors = 0))
{
$name = mysqil_real_escape_string($con, $_POST['txtName']);
$password = mysqil_real_escape_string($con, $_POST['txtPassword']);
$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sqlInsert = "INSERT INTO Table (Name, Phash)
VALUES ('$name', '$hashPass')";
$_SESSION['VerifyHash'] = $hashPass; // Super security issue using a hashed password as a flag? I know. Just wanted visual representation of pass to compare next to my database
if ($con->query($sqlInsert) === TRUE)
{
header('location: InsertUser.php');
echo "New record created successfully <br>";
}
else
{
header('location: InsertUser.php');
echo "Error: " . $sql . "<br>" . $con->error;
}
}
}
echo "Connected"; //Flag to verify Database connection throughout usage. If it makes it here then its connected. End flag.
//CLOSE DATABASE CONNECTION
mysqli_close($con);
?>
When I run all of this together and enter test data. It arrives on: InsertUser.php. and directs properly. However it displays nothing. No code, no Sessions, no HTML. Nothing? However when I simply refresh the page without navigating anywhere it displays the entire insert form fine. And 2 of my flags display:
ConnectedInsert User Pass
I then proceed to eliminate session data. Then I just see
Connected
above the login form. After this all takes place there is no change in my Database? And no users are actually added.
Using this information I can deduce that:
my form submits to my InsertBackend.php file when called from the form.
is connected to my database appropriately.
And that my Backend script is:
Not correctly inserting into the database.
Not properly hashing my password input.
Not rendering the HTML when called back to the insert form.
I have tried really hard to figure out where exactly in this chain of events things are going awry. However I have been unable to figure out why it is not all calling properly, and why my inserts are not working at all.
I really tried finding something on here that would help me figure it out. Unfortunately I was unable to locate anything that gave me clarity. And after the last few hours i have decided to see if anyone here might have any helpful insight into my issue. Just to even have a second set of eyes on it.
This was just poorly built with no session checking. The session cannot be created if it already exists i suppose.
Using
print_r(error_get_last());
Provides me with
Array ( [type] => 8 [message] => session_start(): A session had already been started - ignoring [file] => *InsertBackend.php* [line] => 2 )
Maybe? I guess i have to test this theory. I will update code as i progress until page is all displaying and inserting into database in case anyone else runs into a similar issue down the road.
I have a register email page, which uses referral id, but if no user doesn't get referred by anyone, then by a redirect, I use default af id = 1
with following code::
if ( !isset( $_GET['af'] ) && empty( $_GET['af'] ) ){
header('Location: register-email.php?af=1');exit();
}
Next Here is the form code:
<form class="form-horizontal" role="form" method="post" name="register_email" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-6">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<div class="g-recaptcha" data-sitekey="somecode"></div>
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-warning" name="register-email">Register Email</button>
</div></div>
</form>
Here is the background PHP part:
if (isset($_POST['email'],$_POST['g-recaptcha-response'],$_GET['af'])) {
$test="OK";
}
It never prints "OK", I tested the GET part its working fine not empty or null value. But email & g recaptcha part is null. I am not sure why. Previously it used to work without bootstrap integration.
Note: I didn't use echo $test = OK because I am printing this on other pages with echo statement, whole process includes two files,
register-email.php ( Here I am using the echo $test;)
register-email.inc.php (which includes the isset POST sections)
Try to echo $test. You just have stored it, you didn't printed it. And your condition is not even in right syntax.
There are several mistakes here. You cannot mix $_GET and $_POST, in this case, it must be all $_POST. When testing isset(), you cannot just use commas. How about the following:
if (isset($_POST['email']) AND isset($_POST['g-recaptcha-response']) AND isset($_GET['af'])) {
$test="OK";
}
If the above code does not work, check this out.
if(!isset($_POST['email']) echo "Email not set";
if(!isset($_POST['g-recaptcha-response']) echo "Recaptcha not set";
if(!isset($_POST['af']) echo "AF not set";
Now you can see if any of them is not set. Do keep in mind, for $_POST['g-recaptcha-response'] to have a value, a user must correctly answer the reCaptcha image test (Human test), and reCaptcha must be correctly implemented.
form action remove and change submit button name register_email. after add this php code.
if(isset($_POST['register_email'])){header('Location: register-email.php?af=1');exit();}
I solved my problem by myself after lots of debugging. The form was not working because of the redirect. So remove the code of redirect, in fact, use another type of safe coding in order to check if GET is variable is empty or not internally.
if (isset($_POST['email']) AND isset($_POST['g-recaptcha-response'])) {
if ( !isset( $_GET['af'] ) || empty( $_GET['af'] ) ){
$af_code = 1;
}
else {
$af_code = filter_input(INPUT_GET,'af',FILTER_SANITIZE_STRING);
}
}
Now its working safe & sound
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.