I have just started learning PHP and I am facing this issue when using $_SERVER["PHP_SELF"] to redirect to the same page after user clicks Submit in the form. The problem are the $_POST[] variables I have used in my PHP script in the page, which I need to access AFTER user clicks Submit and the page reloads. But on the first run, when the the user hasn't clicked Submit, the $_POST variables are empty and I am getting errors displayed on the page itself. Of course, there are no errors after the user click Submit and page reloads. I don't want to redirect to another page after Submit. How do I circumvent these errors on the first run?
Is there a better approach for what I am trying to do?
The code for my page is here:
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h3> Welcome!</h3>
</br></br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
First Name: <input type="text" name="fname"> </br></br>
Last Name: <input type="text" name="lname"> </br></br>
Age: <input type="number" name="sage"> </br></br>
<input type="submit" value="Submit"></br></br>
</form>
<?php
$servername = "localhost";
$username = "user1";
$password = "abcd123";
$dbname = "myDbFromPhp";
$fname = $_POST["fname"]; /*Lines responsible for the errors, I think*/
$lname = $_POST["lname"];
$sage = $_POST["sage"];
if($fname != "" and $lname != "") /*Checking for empty vars*/
{
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
echo "<h4>Connected successfully</h4>";
$sql = "INSERT INTO Students
(fname, lname, sage)
VALUES
('".$fname."','".$lname."',".(string)$sage.");" ;
if($conn->query($sql) === TRUE)
{
echo "<h4>Value entered successfully</h4>";
}
else
{
echo "</br>Error creating record</br>".$conn->error;
}
$conn->close();
}
?>
</body>
</html>
The page simply takes some input from the user (Student: first name, last name, age), and when user clicks Submit, reloads and saves them to a database.
First time of page load post value not exists so use isset to check that like this
<input type="submit" name="submit" value="Submit"></br></br>
if(isset($_POST['submit']))
{
//all of your db insertion related codes all here
$fname = $_POST["fname"]; /*Lines responsible for the errors, I think*/
$lname = $_POST["lname"];
$sage = $_POST["sage"];
......................
......................
header('Location:samepage.php');
// redirect the page to avoid the duplicate insertion by pressing F5 or reload .
}
your code looks sql injection attack . try to use prepared statement or PDO
In your first loading, that variable does not have values, therefore php genarate a error, therefore you can use isset() to check whether data assigned or not
if(isset($_POST["fname"])){
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$sage = $_POST["sage"];
}
you can do all functionalities inside the if(isset($_POST["fname"])){ }
Related
I'm currently building a simple CRUD application and decided it would be a nice feature to directly query the database from the browser (i.e from an HTML table) and display ('Read') the results from that particular query.
However, I've been doing some reading and it seems this would essentially be an SQL injection and is something to be avoided. Apparently, it is NOT normal practice to ask a user to input an SQL statement.
Despite this, I've been trying to add this feature to experiment with my code but the SQL statement provided by the HTML form is not being executed.
To recap:
My form in index.php asks the user for an SQL statement.
This is then processed by read.php, which retrieves the SQL statement with the superglobal $_POST['submitsql'] ('submitsql' is just the name of the form's submit button) and queries the database with the query() method. It also displays a message with _$_SESSION[''] superglobal.
From index.php: (form where the user inputs SQL statement)
<form action ="read.php" method ="post">
SQL statement: <input type="text" name="sql_stat">
<button type= 'submit' name = 'submitsql'>Query</button>
</form><br>
read.php (retrieves SQL statement and queries the database)
<?php
include ('server.php');
if(!isset($_SESSION)){
session_start();
}
if(isset($_POST['submitsql'])){
$sql = $_POST['sql_stat'];
$results = $conn->query($sql);
$conn->close();
$_SESSION['message'] = "Query successfully sent: ".$sql;
header('location: index.php');
}else{
$sql = "SELECT * FROM `Students` ORDER BY `degree`";
$results = $conn->query($sql);
$conn->close();
}
?>
For some reason, the message containing the SQL statement is correctly displayed but the database is not queried and all the records are shown (in a table in index.php).
I hope I'm making sense here. My code was working fine when read.php was querying the database directly as opposed to retrieving the SQL statement from the HTML form in index.php. Apologies if I'm not expressing myself correctly.
If it makes any difference, here is the entire index.php:
<?php
include('server.php');
include('create.php');
include('read.php');
include('delete.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>CRUD PROJECT</title>
<meta charset="utf-8"/>
</head>
<body>
<h1>CRUD project</h1>
<h4>Query the database:</h4>
<form action ="read.php" method ="post">
SQL statement: <input type="text" name="sql_stat">
<button type= 'submit' name = 'submitsql'>Query</button>
</form><br>
<?php
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
session_unset();
session_destroy();
}
?>
<table border = '1' cellpadding = '10' >
<tr>
<th>Student ID</th><th>Degree</th><th>Grade</th><th>Graduation Year</th>
</tr>
<tr>
</tr>
<?php
if($results->num_rows>0){
while($row = $results->fetch_assoc()){
echo "<tr><td>".$row['student_id']."</td>";
echo "<td>".$row['degree']."</td>";
echo "<td>".$row['grade']."</td>";
echo "<td>".$row['graduation_year']."</td>";
echo "<td><a href = 'update.php?student_id=".$row['student_id']."'>Edit</a></td>";
echo "<td><a href = 'delete.php?student_id=".$row['student_id']."'>Delete</a></td>";
}
}else {
echo "NO RESULTS TO DISPLAY";
}
?>
</table>
<br>
<h2> Add new records </h2>
<form action ="create.php" method ="post">
Degree: <input type="text" name="degree"><br>
Grade: <input type="text" name="grade"><br>
Graduation year: <input type="text" name="graduation_year"><br>
<button type= 'submit' name = 'submit'>Submit</button>
</form>
</body>
</html>
And server.php where I connect to the database and initialise my variables:
<?php
//Define connection parameters
$db_server = 'localhost';
$db_user = 'root';
$db_password = 'therasmus1';
$db_name = 'University_records';
$conn = new mysqli($db_server,$db_user,$db_password,$db_name);
// Toggle error display
mysqli_report(MYSQLI_REPORT_ERROR);
// Check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
// Initialise your variables (optional - good practice)
$Degree = "";
$Grade = "";
$Graduation_year = "";
$sql = "SELECT * FROM `Students`";
$results = $conn->query($sql);
?>
All feedback is welcome. Thanks in advance.
I can see that there is an issue with your logic. You are submitting your form to read.php then preparing the $results in that file and then immediately redirecting to index.php so you never use the $results when you submit the form.
But you are also including the read.php in your index.php file. So what happens is that, you submit your form to read.php, create the $results(but never use it), redirect to index.php, in the index.php you have included read.php so now it checks if(isset($_POST['submitsql'])){ and since the request method now is not post it goes to else block:
$sql = "SELECT * FROM `Students` ORDER BY `degree`";
$results = $conn->query($sql);
$conn->close();
So the $results contains all the records of the Students table.
With this logic, no matter what you type in <input type="text" name="sql_stat">, you will always get the $sql = "SELECT * FROM Students ORDER BY degree";
The easiest way to fix this problem, is:
Submit your form to index.php. In index.php Change <form action="read.php" method="post"> to <form action="index.php" method="post">
Remove the header('location: index.php'); from read.php
This fix will solve your current problem.
I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>
I have 3 files.
1st one :
<html>
<form action="employeeDel.php" method ="post">
Enter Ssn To Delete Employee:<br>
<input type="number" name="ssnDel">
<br>
<br>
<input type="submit" value="Submit">
</form>
</html>
This form sends data to employeeDel.php.
employeeDel.php :
<html>
<form action ="employeeDelFinal.php" method="post">
<input type="hidden" name="ssn" value="ssnDel">
<?php
$ssnDel = $_POST ["ssnDel"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = mysqli_connect ( $servername, $username, $password, $dbname );
// Check connection
if (! $conn) {
die ( "Connection failed: " . mysqli_connect_error () );
}
$sql = "SELECT * from employee WHERE ssn=".$ssnDel;
<input type="submit" name="Delete?">
</form>
</html>
From here, when user clicks on submit button, I want html form to send ssnDel value to employeeDelFinal.php file.
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
That value never reaches here. I got an error on employeeDel.php file, it says value of ssnDel is null. I guess in the beginning of form in employeeDel file, I create ssnDel again, so it becomes null.
Is there a way to send a data from html form to employeeDel.php, from employeeDel.php to employeeDelFinal.php by using form? I tried hidden text but it didn't solve my problem as seen.
The line
<input type="hidden" name="ssn" value="ssnDel">
should be something like
<input type="hidden" name="ssn" value="<?php echo(intval($_POST['ssnDel'])); ?>">
(Assuming that ssnDel is an ID-Number.)
Otherwise that hidden variable will have the string-value ssnDel, not the value of the variable $_POST['ssnDel'].
And as already mentioned, echo ssnDel; should be echo $ssnDel; and you should use less spaces (e.g. no spaces after $_POST or function names).
There are couple of things I noticed. You have
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
You don't have a dollar sign in your echo statement ssnDel.
And why do you have spaces in between $_POST ["ssnDel"] make it
$_POST["ssnDel"]
This question already has answers here:
PHP Form not directing to correct pages
(4 answers)
Closed 9 years ago.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
$AdminChanges = "";
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php echo PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
I'm having a problem where the form, when submitted, is being directed to the wrong places. It's a user verification page. If the username and password don't match the ones stored in the database, it should go to the Invalid Login page. If they do, they should go to the next part of the user verification website.
The form tag, before entering values, looks like this in the page source:
However, when the username & password are correct, it goes to the InvalidLogin.html page. When it's incorrect, the form reloads again and when I check the page source, it's the exact same code except now the form tag shows:
Any suggestions?
I think u got it wrong, the action tag is where the form sends the request, not where to go after it sends it.
Try using header('location: '.$AdminChanges); right after the user verification in order to redirect the page.
EDIT: Also remove the action tag of the form. By removing it the request will be sent to the same file you are working on.
<?php
if($_POST['username'] && $_POST['password']){
$username = $_POST['username']; // Escape this
$password = $_POST['password']; // Escape this
$searchQuery = mysql_query("SELECT id FROM onlineformdata WHERE username = '$userName' AND password = '$password' ORDER BY id DESC LIMIT 1");
if(mysql_num_rows($searchQuery)){
header('location:/adminPage.php'); // Go to this page if row exists in DB
}
else{
header('location:/invalidLoginPage.html'); //Go to this page if row doesn't exist in DB
}
exit; // So that it quite this page and goes to the desired one set in the "headers"
}
else{
//Not strictly needed... But you could be useful in some circumstances
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action='' method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
This should get you started in the right direction. Don't forget to escape the username/password fields as you see fit.
The action part of the form is where the form is submitted to and so - in your case - that should be the same page. As Hristo said, you can leave it out/blank and it will default to submitting itself.
As for Marc B (he did ask a question after all); if you read the code you would see that the PrepSQL function actually adds single quotes around the string... As there are no quotes in the html this isn't wrong in anyway... So I don't see what the problem is there (aside from it not doing what he wanted it to).
With regards to multiple user accounts, so long as you don't allow the same username to be used by multiple users then there is only one record returned by the database... So again, there's no problem there.
I am trying to get a guest book to work using PHP. I have managed to make it function, the thing is that I don't want the guest book to be in my index.php. I want it to be on a dynamic page, index.php?=guestbook for instance.
The problem is that when I put the code on another page rather than index.php the thing that happends when I fill out the fields and press the submit button, I get redirected to index.php and nothing is submited to my database. This all works fine as long as the code is in the index.php.
My first question is: What is causing this?
Second question: How do I get the code to function properly eventhough I have it in index.php?=guestbook?
Thanks in advance!
I am using xampp btw.
See below for the code:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Guestbook</h1><hr>
<?php
mysql_select_db ("guestbookdatabase") or die ("Couldn't find database!");
$queryget = mysql_query ("SELECT * FROM guestbook ORDER BY id ASC") or die("Error witch query.");
$querygetrownum = mysql_num_rows ($queryget);
if ($querygetrownum == 0)
echo "No posts have been made yet. Be the first!";
while ($row = mysql_fetch_assoc ($queryget))
{
$id = $row ['id'];
$name = $row ['name'];
$email = $row ['email'];
$message = $row ['message'];
$date = $row ['date'];
$time = $row ['time'];
if ($id%2)
$guestbookcomment = "guestbookcomment";
else
$guestbookcomment = "guestbookcommentdark";
echo "
<div class='$guestbookcomment'>
<div class='postheader'>
<b>Posted by $name ($email) on $date at $time</b>
</div>
<div class='message'>
".nl2br(strip_tags($message))."
</div>
</div>
";}
echo "<hr>";
if($_POST['submit'])
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$date = date("Y-m-d");
$time = date("H:i:s");
if ($name&&$email&&$message)
{
$querypost = mysql_query ("INSERT INTO guestbook VALUES ('','$name','$email','$message','$date','$time')");
echo "Please wait... <meta http-equiv='refresh' content='2'>";
}
else
echo "Please fill out all fields.";
}
echo "
<form action='index.php' method='POST'>
Your name: <input type='text' name='name' class='name' maxlength='25' ><br> <br>
Your email: <input type='text' name='email' class='email' maxlength='35'><br><br>
<div class='your_message'>
Your message:<input type='textarea' name='message' class='messagetextarea' maxlength='250'><br><br>
</div>
<input type='submit' name='submit' value='Post'>
</form>
";
?>
</body>
</html>
1) The action property of your form should be the same as the name of the file where the code is in. :) You create a guestbook.php, for example, but the action still is 'index.php'. Hence the problem. You send the POST data to index.php but there's no code to process it.
2) The query string doesn't affect the form. Only the filename.
I hope I understood your problem correctly.
Have you tried updating your form's action parameter to:
index.php?=guestbook
instead of just index.php?
If the problem resides on the server end than the victim to your problem is .htaccess (mod rewrite);
Otherwise, what do you really mean by this line of code?
echo "Please wait... <meta http-equiv='refresh' content='2'>";
< meta > refresh tag requires location to be mentioned where the redirect otherwise according to you refreshes the current page..
<meta http-equiv="refresh" content="2;url=http://stackoverflow.com/">
First, I'm assuming the file you're showing is index.php
Second, don't use index.php?=guestbook. URL parameters work within a key => value structure. In you're case you've only defined the value and no key.
Try using index.php?page=guestbook. this way, in your index.php file you can do something like:
if($_GET['page'] == 'guestbook') {
// ... your guestbook php code.
}
Then try setting your forms action attribute like this: action="index.php?page=guestbook".
Third, I'm going to assume that you have mysql connection code that isn't shown here. If not, take a look at mysql_connect().
Fourth, NEVER use unescaped data in a SQL query. You MUST escape your data to protect your database from being destroyed. Take a look at this wikipedia article which describes SQL Injection in greater detail: http://en.wikipedia.org/wiki/SQL_injection
Then take a look at mysql_real_escape_string() to learn how to prevent it with PHP and MySQL.
Fifth, don't use <meta http-equiv='refresh' content='2'> for redirect. Use PHP's header() function to redirect users, like this:
header('location: index.php');
exit(); // be sure to call exit() after you call header()
Also, just so you know, you CAN close PHP tags for large HTML blocks rather than using echo to print large static chunks of HTML:
<?php
// ... a bunch of PHP
?>
<form action="index.php" method="POST">
Your name: <input type="text" name="name" class="name" maxlength="25" ><br> <br>
Your email: <input type="text" name="email" class="email" maxlength="35"><br><br>
<div class="your_message">
Your message:<input type="textarea" name="message" class="messagetextarea" maxlength="250"><br><br>
</div>
<input type="submit" name="submit" value="Post">
</form>
<?php
// ... some more PHP
?>