HTML Form is not sending variables to PHP/MySQL - php

My problem is that when I enter data into my html form and click submit, it calls my php file but it doesn't send the parameters.
I have even tried using working code to test it, and even the working code is not passing through variables. I am unsure as to why this is doing this, bad php install? No idea.
Here it is, if you want to see if it works at least for you. But I am not getting anything passed into my variables on my php file. Thanks for the help.
<html>
<head>
<title>Home</title>
</head>
<body>
<form method="get" action="reg.php">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
</body>
</html>
And here is the php file:
<?php
echo $_SERVER['REQUEST_METHOD'];
if(isset($_GET['firstname'])){
$firstname = $_GET['firstname'];
}
else{
$firstname = 'null';
}
if(isset($_GET['lastname'])){
$lastname = $_GET['lastname'];
}
else{
$lastname = 'null';
}
if(isset($_GET['age'])){
$age = $_GET['age'];
}
else{
$age = 'null';
}
$con = mysqli_connect("127.0.0.1","root","", "my_db");
$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
$result = mysqli_query($con, $sql);
if ($result)
{
echo "1 record added";
}
else{
echo "Did not work";
}
error_reporting(E_ALL);
mysqli_close($con);
?>
When I look at the error report, it says Undefined Index every time, for each piece of working code I tested. I tested 4 files of working code and neither worked but was proven they did. I am starting to think I have a bad php install or something deeper is the problem. Thanks again.

Three things:
I would recommend you to use POST instead of GET.
Give your input fields an id and it should work.
You need to sanitize your data before writing them into the database.

Related

How to stay on HTML form page and not navigate to php form action page

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; ?>

PHP_SELF displays errors on first run

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"])){ }

PHP form submission with refreshing

first time posting on here so I apologise for any bad habits.
I recently started an online youtube tutorial on php and how to create a blog.
I ended up getting occupied with other things and have come back to try an finish what I started and 2 things have happened. 1: my tutorials have been deleted off youtube(must of been a copyrright issue) and second I've completely forgot the method used. I assume if I was a seasoned coder this would be easy to decipher but I'm having no luck after trying for days now.
This code is for the submission form for my blog. The blog is working in the sense of if I manually input my HTML into the SQL database but all I seem to get if I use this form is a refresh of the submission page with all the information gone. No information is added to the database.
Anybody have an idea?I had a good search around the site but I ran into a dead end due to my lack of knowledge on what I was actually searching for (lots of solutions regarding javascript)
All help will be appreciated.
Sincerely
SGT Noob
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit']))
if ($_POST['submit']) {
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
include_once("../admin/connection.php");
$sql = "INSERT INTO `posts` (Post_Title, Post_Content, Post_Date)
VALUES ('$title','$content','$date')";
mysqli_query($dbcon,$sql);
echo "Post has been added to the database";
}
else {
header('Location: index.php');
die();
}
?>
<html>
<div>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<title> Insert Post </title>
</head>
<div>
<body>
<div id= 'cmssubmissionform'>
<form action="" method="post">
<p>
<h1> Post Title</h1>
<input type="text" name= "Post_Title"/>
</p>
<h1> Post Date</h1>
<input type="text" name= "Post_Date"/>
</p>
<p>
<h1>Post Content </h1>
<textarea name="Post_Content"></textarea>
<script>
CKEDITOR.replace( 'Post_Content' );
</script>
</p>
<p>
<input type = "submit" value="submit" />
</p>
</form>
</div>
</div>
</div>
</body>
try this
in your from change to
<input type = "submit" value="submit" name="submit"/>
You forgot to put the name attribute
The php
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
include_once("../admin/connection.php");
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit'])){
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
$sql = "INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date')";
if(mysqli_query($dbcon,$sql)){
echo "Post has been added to the database";
}else{
header('Location: index.php');
die();
}
}
?>
Note I also changed your SQL statement to
INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date
Notice the back ticks for the table fields
Replace
if (isset($_POST['submit']))
if ($_POST['submit']) {
with
if (isset($_POST['submit'])) {
and then replace
<input type = "submit" value="submit" />
with
<input type ="submit" name="submit" value="submit" />
However, at this stage I would highly suggest starting over with a different tutorial.
Also, as has been mentioned in the comments, whenever you take arguments from a user and put them into a database query, you must absolutely make sure that the strings do not manipulate the query (imagine someone wrote 0'; DROP TABLE `blog`; -- in the date field (and "blog" were the name of your blog post table). That would be quite catastrophic, wouldn't it?
So when you handle input data, either use the prepare and bind methods of the mysqli package, or pass the strings through the mysqli_real_escape_string() function first.

variables go into db without being retrieved through $_POST

This works but How are the values of the variables being put into the db without retrieving them through the $_POST?
Is this something new in php5 or have I just never seen it used this way before?
<!doctype html>
<html>
<head>
<title></title>
</head
<body>
<form action="insert.php" method="post">
First Name: <input type="text" name="fname" /><br>
Last Name: <input type="text" name="lname" /><br>
Username: <input type="text" name="uname" /><br>
<input type="submit" name="submit" value="Register"/><br>
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO traders (fname, lname, username)
VALUES
('$fname','$lname','$uname')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added " ;
mysqli_close($con);
?>
because you use here register globals option in php which is now deprecated/removed in new versions of php (mainly because of security issues) which translates $_POST['fName'] into $fName
you should always use $_POST/$_GET instead
read more: http://php.net/manual/en/security.globals.php
No, this is called Register Global and is DEPRECATED long time ago, one should never use this !
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier.
For more information:
http://php.net/manual/en/security.globals.php

PHP: Using POST on a dynamic page redirects me to index.php and does not post the values

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
?>

Categories