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.
Related
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.
I have a form that submits fields to a database using mysqli that was working perfectly; however, I pulled up the form page in Chrome and tried to submit a new row to the db, only for the page to go back to the previous page when I tried to click on the form's text-areas. I tried clearing all of my browser history (cache, cookies, etc.) and asked a friend to try it on their Chrome browser, with the same result.
The kicker? It works in Edge. Makes no sense.
I've gone through the code and can't find any missing <'s or quotes, etc. Everything was working fine and I can't imagine why it would suddenly start doing this in Chrome.
(Note: I know this code is clunky and vulnerable to SQL injection, but I don't have any users/sensitive data to protect, for the moment. Also, I made no changes to head.php or any code (that I can recall), just confused as to why it would suddenly start redirecting me back to notebook.php as soon as I click on a text area in Chrome but not in Edge.)
Notebook_add.php
$con = #mysqli_connect('localhost', 'root', 'pass', 'db');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
?>
<body>
<div class="wrapper">
<h1>Post Comments</h1>
<?php
include ('navbar.php');
?>
<br>
<form name="noteworthy" METHOD=POST action=<?php echo $_SERVER['PHP_SELF']; ?>>
<br>
Title: <input type="text" name="title" id="$title" size="50"> <br>
Link: <input type="text" name="link" id="$link" size="50"><br>
Description: <TEXTAREA NAME="description" id="$description" ROWS="5" COLS="30"></TEXTAREA><br>
<Input type="submit" name="enter" id="$enter" value="enter">
</form>
<?
echo $submitted = date("Y-m-d");
?>
<?
$title = $_REQUEST['title'];
$link = $_REQUEST['link'];
$description = $_REQUEST['description'];
$enter = $_REQUEST['enter'];
if(isset($_REQUEST['enter'])){
$submitted = date("Y-m-d");
$sql = "INSERT INTO notes (title, link, description, submitted) VALUES ('$title','$link','$description','$submitted')";
}
if(mysqli_query($con, $sql)){
echo "Records inserted successfully.";
print "<meta http-equiv='refresh' content='0; url=http:notebook.php' />";
}
// Close connection
mysqli_close($con);
?>
<div class="push"> </div>
</div>
<?php
include 'footer.php';
?>
</body>
So what happened was that I had added a new menu item in my navbar.php and forgot to close the link tag (e.g., " New menu item "). This made the entire php form into a link, so whenever I anywhere on it under my navbar I was returned to the previous page.
It is interesting that this didn't happen in Edge; perhaps there is some feature in Edge that automatically closes rogue tags.
Anyway, thanks for responding. #Smith, thanks for the tip, I'm using the php head featured/location function instead of meta-refresh now.
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; ?>
What is the correct/right code for uploading or inserting values from input html tag into mysql using php?
I have php file and html file, but when I try to click the submit button, it only display the php file. My phpMyAdmin connected to my web host, while the html page is not
Html code:
<form action="add.php" method="post" enctype="multipart/form-data">
<input type="text" name="contract_num"><br>
<input type="text" name="random_file"><br>
<input type="submit" value="Upload file">
</form>
PHP:
<?
$contract_num=$_POST['contract_num'];
$random_file=$_POST['random_file'];
mysql_connect("your.hostaddress.com", "username", "password")
or die(mysql_error());
mysql_select_db("contract")
or die(mysql_error());
mysql_query("INSERT INTO `contract` VALUES ('$contract_num', '$random_file')");
Print "Your information has been successfully added to the database.";
?>
I think you mean "What is the correct/right code for this one?"
Please call first the html page or including the php file.
Created a page add.php, which contains this.
<?
$contract_num=$_POST['contract_num'];
$random_file=$_POST['random_file'];
mysql_connect("your.hostaddress.com", "username", "password")
or die(mysql_error());
mysql_select_db("contract")
or die(mysql_error());
mysql_query("INSERT INTO `contract` VALUES ('$contract_num', '$random_file')");
Print "Your information has been successfully added to the database.";
?>
Then a page form.php, which includes the add.php
<?php
include "add.php";
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="contract_num"><br>
<input type="text" name="random_file"><br>
<input type="submit" value="Upload file">
</form>
You can call first the form.php in your browser.
When you submit your form the post request is send to your php file. That is when you submit your form all the data filled inside the form will send to post your php file and it is processed there. If you want to see the html file again try to redirect to html file like
header("Location: ".$_SERVER['HTTP_REFERER']);
You can send them via javascript, call a js function on 'submit' click , read all input and redirect to 'add.php' page with parameters ..
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
?>