I am trying to redirect a to a new php page after the user has clicked on the submit button. I have got it to successfully send the form information to the MySQL database but then I cannot get a successful redirect.
I then changed some code and got it to successfully redirect but not send the form information to the database. My other php file is named nextForm.php and I have tried replacing the action="$_SERVER[PHP_SELF]" with the path to the nextForm.php file and I have tried using a require nextForm.php; line in the code where I want to redirect.
Here is the code I have currently:
<?php
//establish a connection to the MySQL db or terminate if ther is an error
$conn = mysqli_connect("localhost","root","mysql","covid_tech",3306) or die(mysqli_connect_error());
//HTML form to prompt user input
print <<<_HTML_
<FORM style="text-align:center" method="POST" action="$_SERVER[PHP_SELF]">
<div class="Customer_Name">
Enter Customer Name: <input type="text" name="Customer_Name" class="textbox">
</div>
<br/>
<div class="Contact_Name">
Enter Contact Name: <input type="text" name="Contact_Name" class="textbox">
</div>
<br/>
<div class="Contact_Phone">
Enter Contact Phone Number: <input type="text" name="Contact_Number" class="textbox">
<br/>
</div>
<button class="btn btn-1" style="text-align:center" onclick='disappear(this)' name="name_submit" method="POST" type="submit" value="find_cusName"><span>Enter Customer Name</span></button>
</FORM>
_HTML_;
//check to make sure the POST request was sent and check to make sure that there is a vlaue in the System POST variable
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['Customer_Name'])){
//SQL string to find the name that was input on the page
$find_name_sql = "SELECT cusName,cusID from customer where cusName = '$_POST[Customer_Name]'";
//run the query on the db
$result_find_name = mysqli_query($conn, $find_name_sql);
//Check to see if the query returned any rows
if(mysqli_num_rows($result_find_name) > 0){
//If it did, it should only be 1 row and we fetch it
$row = mysqli_fetch_row($result_find_name);
//set our current_id variable to the value in $row[1] which is the cusID attribute from the db
$current_id = $row[1];
}
else{
//sql statment to insert a new customer into the customer table of the db
$insert_first_customer = "INSERT INTO customer (cusName,contactName,contactNo) values('$_POST[Customer_Name]','$_POST[Contact_Name]','$_POST[Contact_Number]')";
//run the insert query
$add = mysqli_query($conn,$insert_first_customer);
}
//redirect to next form page here
}
mysqli_close($conn);
?>
The action attribute simply works as a way to direct your GET/POST requests. If you would like to redirect after running your PHP code, you should use the header() function or use a meta tag.
Example:
header('Location:'.$_SERVER['SERVER_NAME'].'/nextForm.php');
or
echo '<meta http-equiv="refresh" content="0;url=nextForm.php">';
and finish your code with the exit() function so an attacker could not bypass your redirect.
Related
I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.
This is the delete code which isn't working:
<?php
if (isset($_POST['deleteSubmit'])) {
$details = $conn->real_escape_string($_POST['deleteNum']);
$deleteSQL = "DELETE FROM userName WHERE id = '$details'";
$result = $conn->query($deleteSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>DELETE NAME (DELETE)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="num">Enter User Reference to be Deleted:</label><br>
<input num="deleteNum"type="number"><br>
<input num="deleteSubmit" type="submit" value="Delete">
</form>
For reference, this is the post code which is working (it's being used to add names to the database):
<?php
if (isset($_POST['nameSubmit'])) {
$details = $conn->real_escape_string($_POST['newName']);
$insertSQL = "INSERT INTO userName (name) VALUES ('$details')";
$result = $conn->query($insertSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>ENTER NAME (POST)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="fname">Enter Name:</label><br>
<input name="newName"type="text"><br>
<input name="nameSubmit" type="submit" value="Submit">
</form>
The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.
The database has one table called userName which contains two columns id (which is auto incremented) and name.
I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.
I see no error messages when enter an id and click the delete button.
For anyone who reads this in future, the query was solved by #kenlee;
(1) Change num="deleteSubmit" to name="deleteSubmit"
(2) change num="deleteNum" type="number" to name="deleteNum" type="number"
(3) Please use paratemerized prepared statement in your queries
I am trying to create a query screen for reports. I have created a php code by getting support from here and other sites. But the problem is; when a user input report serial number and submits it, the page only reload. After reload; when the user enters serial again to the field and hits submit, this time the code works but only for the 1st serial entered, no matter the second serial is.
I have tried to change the parts of my code but could not find a solution.
I am trying to create a system like, user will enter a serial to the field and when hits to submit button; a new window pop out and directs user to a link which has been created based on user input.
For example, user entered "234" as the serial number and hit submit button. The new window will go to the; "example.com/reports/report234.pdf"
Here is the code I have problem with;
<?php
if(isset($_POST['submit']))
{
$seri = $_POST['seri'];
$url = "https://www.example.com/wp-content/uploads/Rapor/".$seri.".pdf";
}
?>
<form method="post" action="<?php echo $url; ?>">
<input type="text" name="seri"><br>
<input type="submit" name="submit" value="Sorgula"><br>
</form>
That's because you're setting the redirect $url as the form action. That results in the following:
Form action is empty, thus the form will be sent to the page itself
The serial number and the $url is created and set as the form action
Now when the user submits the form again it will be directed to the $url set, regardless of what he has filled in the seri field this time
Here is an example of a more correct approach to your problem:
<?php
if(isset($_POST['submit']))
{
$seri = $_POST['seri'];
Header("Location: https://www.ozguncicek.com.tr/wp-content/uploads/Rapor/$seri.pdf");
}
?>
<form method="post">
<input type="text" name="seri"><br>
<input type="submit" name="submit" value="Sorgula"><br>
</form>
Note there's no need to set an action to the form since you're going to redirect the user when he submits the form.
Another important point is checking if seri isn't empty before redirecting the user. That could be accomplished as simple as:
<?php
if(isset($_POST['submit']) && $_POST['seri'])
Redirect after form submit,
<?php
if(isset($_POST['submit']))
{
$seri = $_POST['seri'];
$url = "https://www.example.com/wp-content/uploads/Rapor/".$seri.".pdf";
header("Location: ".$url);
}
?>
<form method="post" action="<?php echo $url; ?>">
<input type="text" name="seri"><br>
<input type="submit" name="submit" value="Sorgula"><br>
</form>
I am having trouble understanding handling variables that are passed through pages when a form submit button is clicked. Basically i have a text area where a user writes an sql query. Then clicks submit. Then on the same page (x.php) , i have to display the results in a table. I figured, when the user clicks the button, i call a function that connects to the database, then runs the query, and outputs the result in a table. The code i have below is a mock, and isnt quite working.But above is essentially what i am trying to do.
In my code, I call the page, and check to see if the proper submit button has been clicked, is that how i am suppose to do it?
Also, I am trying to post the metadata in the code below, but how does the table replace what is already on the page?
<html>
<head>
<title>CNT 4714 - Project Five Database Client</title>
</head>
<body style="background-color:white">
<center>
<h1 style="color:red">CNT 4714 - Project Five Database Client</h1>
<hr>
<div style="float:left; text-align:left;padding-right:80px; padding-left:80px; ">
<font color="yellow">
<?php
?>
Welcome Back!<br>
<?php echo $_POST["user"];?>
</font>
</div>
<font color="yellow">
<div style="float:left; text-align:left">
<center>
<h2 style="color:green">Enter Query</h2><br><br>
Please enter a valid SQL Query or update statement. You may also just press<br>
"Submit Query" to run a defualt query against the database!
<form action="" id="sql" method="post">
<br>
<textarea rows="10" cols="50" name="query" form="sql">Enter text here...</textarea><br><br>
<input type="submit" name="submit" color="red">
<input type="submit" name="" color="red" value="Submit Update">
</form>
<?php
if(isset($_POST['submit'])){
echo "hello";
query(); //here goes the function call
}
function query()
{
echo "hello";
$conn = mysqli_connect("localhost:3306", "root", "*******", "project4");
$query = $_POST["query"];
$result = mysqli_query($conn, $query);
$metadata = mysqli_fetch_fields($result);
print("<tr>");
for($i=0; $i<count($metadata);$i++){
print("<tr");
printf("%s",$metadata[$i]->name);
print("</tr>");
}
}
?>
</center>
</div>
</font>
</center>
</body>
</html>
You are trying to get the values of the global variable $_POST while you are posing it to $_GET. The way to fix this is assigning the method into your form element.
Example:
<form id="sql" action="" method="POST">
There are many ways for checking or the form is submitted, one of this ways (the one I am always using) is checking or the $_SERVER['REQUEST_METHOD'] is equal to "POST". This way you can tell the different between a GET, POST, or PUT request.
Example:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['sql']))
{
....
}
}
If you're using $_POST, your form request method should be POST.
<form action="" id="sql" method="post">
Otherwise, it will submit it with a GET request by default.
In that case, you will have to access the variable using $_GET instead.
I used a sample I found here with a HTML page calling a PHP script, both are listed below.
It all works well - BUT, I end up with the PHP scrip page and I want to avoid it - I want to stay on the HTML page and NOT move anywhere. I read in some places that I will need JS or AJAX but can't see any actual example.
I am working on my PC under Windows 7 with IIS version 7.5 installed, PHP 5.3.28.
and executing the HTML file inside c:\inetpub.wwwroot
HTML
<div id="contact">
<h2>Enter your First and Last Name</h2>
<form action="frm_script.php" method="post" target="_parent">
<p><strong>First Name:</strong><br /> <input type="text" name="firstName" /></p>
<p><strong>Last Name:</strong><br /> <input type="text" name="lastName"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</div>
PHP Script
<?php
if(isset($_POST['submit']))
{
//get the name and comment entered by user
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//connect to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'mdpdata') or die('Error connecting to
MySQL server');
$check=mysqli_query($dbc,"select * from clients where firstname='$firstname' and
lastname='$lastname'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0)
{
print "customer exists";
}
else
{
//insert results from the form input
$query = "INSERT INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')";
$result = mysqli_query($dbc, $query) or die("Sorry, Duplicate Record.'$php_errormsg'");
mysqli_close($dbc);
}
print '<script type="text/javascript">';
print 'alert("The Customer is NOW registered")';
print '</script>';
};
?>
A html document containing a form with an action="" statement results to change to the assigned page. Like yours, to frm_script.php
If you don´t want this to occure, you need an AJAX-request, as you mentioned above, or you can add a
header(location: 'FPRM.HTML');
to the bottom of the php script. So after processing, which should be very fast, the original page is loaded again.
Or you don´t use two pages at all. Just put the html code from FPRM.HTML to the bottom, after the php code, so the page just will be reloaded once the form values are saved. In this case, call the concatenated document simply FPRM.php, and the form action must be set to action="FPRM.php" or is simply not needed, as the form without action statement loads the same page anyway.
I am creating my own website just to get some experience. I've been working on it for 3 days and am at the point where I can sign up and sign in.
When signing in, if the combination of the username and password is not found in the database, my code displays an error message telling the user that either he didn't sign up yet or he is entering a wrong user email or password.
But, the message is displayed in a new page, instead of the sign in page.
I looked at some tutorials online, but didn't find a good explanation for it. Could someone please give me some advise?
I am using PHP for the database connection.
I just typed a very basic example:
<?php
//login.php
$msg = ''; //to store error messages
//check whether the user is submitting a form
if($_SERVER['REQUEST_METHOD'] == 'POST') //check if form being submitted via HTTP POST
{
//validate the POST variables submitted (ie. username and password)
//check the database for a match
if($matchfound == TRUE) //if found
{
//assign session variables and other user datas
//then redirect to the home page, since the user had successfully logged in
header('Location: index.php');
}
else
{
$msg = 'Error. No match found !'; //assign an error message
include('login_html.php'); //include the html code(ie. to display the login form and other html tags)
}
}
else //if user has not submitted the form, just display the html form
{
include('login_html.php');
}
//END of login.php
?>
login_html.php :
<html>
<body>
<?php if(!empty($msg)) echo $msg; ?> <!-- Display error message if any -->
<form action="login.php" method="post">
<input name = "username" type="text" />
<input name = "password" type="password" />
<input name = "submit" type="submit" value="Submit" />
</form>
</body>
</html>
This is not a complete code. But I just created it for you to understand how this can be done. :)
Good luck
Your opening form tag should look like this: <form action="" method="post">. The empty "action" attribute will cause the page to post back to itself. Just check the $_POST for username and password to determine whether to test for a match or just show the form.
And please be sure to hash your passwords and sanitize your inputs!
you can do it without going to a new page.
<?php session_start(); ?>
<?php
if(isset($_POST) && isset ($_POST["admin_login"])){
$user_data_row = null;
$sql="SELECT * FROM table_name WHERE <table_name.field name>='".mysql_real_escape_string($_POST['email'])."'
and <table_name.field name='".mysql_real_escape_string($_POST['password'])."'
;
$result=mysql_query($sql);
$user_data_row=mysql_fetch_assoc($result);
if(is_array($user_data_row)){
$_SESSION['user_id'] = $user_data_row['id'];
header("Location: <your page name>");
}else{
$_SESSION['message'] = "Valid email and password required";
}
}
?>
<?php if(isset($_SESSION['message'])){
echo "<li>{$message}</li>";
?>
<form action="" method="post" id="customForm">
<label>Email:</label>
<input type="text" id="email" name="email">
<label>Password:</label>
<input type="password" id="password" name="password">
<input type="submit" value="Login" id="send" name="admin_login">
</form>
may be its helps you....
Basically what you need to do, is post the form to the same page.
Once you have that, at the type just check for the $_POST: if($_SERVER['REQUEST_METHOD'] == 'POST')
If it is a post, check the username and password and either show an error or redirect to the signed in page. After this, display the login form.
So, if it's an error, they'll get the error and then the login form. If it's not posted, they'll get just the login form, and if it's a valid login, they'll get redirected to the proper page before the login form is shown.