sending form data to mySQL using get - php

I want to send user entered form data to mysql via php using get.
<form action="formtosql.php" method="get">
<div class="row">
<div class="form-group col-md-4">
<label for="001">Student name:</label>
<input type="text" class="form-control" id="001" name="sname">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="002">Status:</label>
<input type="text" class="form-control" id="002" name="sstatus">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
php code looks like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$name = $_GET['sname'];
$stat = $_GET['sstatus'];
// Connecting to the Database
$servername = "localhost";
$username = "root";
$password = "";
$database = "exam";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Die if connection was not successful
if (!$conn){
die("Sorry we failed to connect: ". mysqli_connect_error());
}
else{
$sql = "INSERT INTO `estatus` (`name`, `status`, `date`) VALUES ('$name', '$stat', current_timestamp())";
$result = mysqli_query($conn, $sql);
?>
In php im getting an error while using get:
Notice: Undefined index: sname in C:\xampp\htdocs\helloworld\formtosql.php
Notice: Undefined index: sstatus in C:\xampp\htdocs\helloworld\formtosql.php
This error does not occur if I am using Post.

I am assuming that you have both the generation of the form, and the processing of the submitted value, in the same script here?
This error does not occur if I am using Post.
You checked the REQUEST_METHOD to determine if you are dealing with the case, that the form was submitted.
When you use method="post" on your form, you can do that - the initial request that loaded the page containing the form was used making the GET method, submitting it will use POST - so these two cases can be distinguished between using that method.
But if you use method="get", then both requests - the one used to initialy load the page, and the one used to submit the form data - are of the same method, and therefor you can not use that any more, to differentiate between the two cases.
If you give your submit button a name, then you could check (using isset/empty), whether the corresponding parameter exists - and use that to determine, which of the two cases you are dealing with.
But as already mentioned in comments - for requests that create data on the server side, you should generally use POST, not GET. Under When do you use POST and when do you use GET? you can find a more in-depth explanation of that.

Related

php sql form submit on same page, but sql loads too early to give error

okay i have this first form which is used to get the input text and supposed to send them to sql table
<form action="" method="post">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3 col-sm-offset-3">
<input type="text" placeholder="ask your question!" class="assin assin-success assin-autosize" name="post_question">
<input type="submit">
</div>
</form>
and then i have this php below it
<?php
$connect = mysqli_connect("localhost","root","","dbname");
mysqli_query($connect,"INSERT INTO `as_questions`(`Qid`, `M_class`, `S_class`, `Question`, `Answer`, `Doctor`, `Time`) VALUES
('n','n','n','$_POST[post_question]','a','d',CURRENT_TIMESTAMP)");?>
it works once i enter a question and submit, but when i first load the page, the php query seems to run and give : Undefined index: post_question, because on load it is empty? and the query runs. how do i fix this?
Use isset OR !empty.
if(isset($_POST['post_question'])){
$connect = mysqli_connect("localhost","root","","dbname");
mysqli_query($connect,"INSERT INTO `as_questions`(`Qid`, `M_class`, `S_class`, `Question`, `Answer`, `Doctor`, `Time`) VALUES
('n','n','n','$_POST[post_question]','a','d',CURRENT_TIMESTAMP)");
}
Hope it will help you :)

Saving form input to a php variable?

I am writing a PHP script to take the contents of a variable and insert it into my MYSQL database, it works well when I define the values, but using variables just gives a error, can any one tell me the correct way to save form input to a variable. (the form is in the same file as the sql script excluding the logins, so using $_POST doesn't work)
mysqli_query($connect,"INSERT INTO news (news)
VALUES ('$email')");
if(mysqli_affected_rows($connect) > 0){
echo $good;
else
echo $bad
}
form:
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s6">
<input placeholder="Placeholder" id="email" type="text"
<label for="news">news</label>
</div>
You're asking for a lot of issues with that script. Lets walk through all of them:
1) Setting form attributes
It is important to tell the browser how to send the form data to your server. Otherwise you'll end up having to rely on the superglobal $_REQUEST. As quoted from the official PHP website:
The variables in $_REQUEST are provided to the script via the GET,
POST, and COOKIE input mechanisms and therefore could be modified by
the remote user and cannot be trusted.
So instead you should add the method attribute to your form. You might want to add character encoding as well, just to be sure your script won't get confused when someone uses non utf-8 characters:
<form method="POST" action="" accept-charset="utf-8">
2) A way to access your POST data
To be able to actually do something with POST data, you need a way to access it. This is where the name attribute comes into play:
<input placeholder="Placeholder" id="email" type="text" name="email" />
The superglobal $_POST will now be able to access the value of that input field using the name attributes value as a key: $_POST['email']. This will only work after the form is sent though.
3) Submit your form
You cannot magicly expect your server to have all the form data filled in by your website visitor. You need to submit it first:
<input type="submit" value="Register email" />
This will become a button with the text you've setup in the value attribute. When the visitor clicks on it, your form data will be submit to your server.
So your entire form should look like this:
<form method="POST" action="" accept-charset="utf-8">
<input placeholder="Placeholder" id="email" type="text" name="email" />
<input type="submit" value="Register email" />
</form>
4) Setting up PHP
Before we start working with the POST data, we need to be sure the user is giving us data:
if(isset($_POST['email']) && !empty($_POST['email'])){
//...
}
This will verify that $_POST['email'] exists and also makes sure it isn't empty.
5) Securely handling user data: Prepared Statements
One of the first things you learn as a developer is to never ever trust user data. Inputting data into a database submitted by a user without verifying it, is asking for a lot of trouble. Especially SQL Injection.
Using MySQLi Prepared Statements, you can protect yourself against this:
//$link will be the connection to your database
//For example: $link = mysqli_connect("localhost", "db_user", "db_pass", "db_name");
if ($stmt = mysqli_prepare($link, "INSERT INTO news (news) VALUES (?)")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_POST['email']);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
/* print success message */
echo "Email successfull registered!";
} else {
/* print errors */
printf("MySQL Error: %s\n", mysqli_error($link));
}
Wrapping it all together:
<?php
if(isset($_POST['email']) && !empty($_POST['email'])){
//$link will be the connection to your database
//For example: $link = mysqli_connect("localhost", "db_user", "db_pass", "db_name");
if ($stmt = mysqli_prepare($link, "INSERT INTO news (news) VALUES (?)")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_POST['email']);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
/* print success message */
echo "Email successfull registered!";
} else {
/* print errors */
printf("MySQL Error: %s\n", mysqli_error($link));
}
}
?>
<!-- Your HTML here -->
<div class="row">
<form class="col s12" method="POST" action="" accept-charset="utf-8">
<div class="row">
<div class="input-field col s6">
<input placeholder="Placeholder" id="email" type="text" name="email" />
<input type="submit" value="Register email" />
</div>
</div>
</form>
</div>
<!-- Your HTML here -->
Give your input a name
<input placeholder="Placeholder" id="email" name="email" type="text">
and get the value in php with
$email = $_REQUEST['email']; //to get both GET and POST methods.
then use the $email in your query

Html form to sql database with php

I am trying to make a site which users can upload phrases. Basically there is a text field and then it gets uploaded to the mysql database. Here is what I have tried so far.
HTML::
<form class="form-horizontal" action="drop.php" method="post">
<fieldset>
<!-- Form Name -->
<legend>Submit a Billboard</legend>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="textinput">What will your Billboard Say?</label>
<div class="controls">
<input name="text" type="text" placeholder="What you going to say?" class="input-xlarge">
</div>
</div>
<br>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button id="singlebutton" name="singlebutton" class="btn btn-primary">Drop Your Billboard</button>
</div>
</div>
</fieldset>
</form>
PHP::
<?php
//Connecting to sql db.
$connect = mysqli_connect("localhost","mod","","bill");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')
?>
Besides your SQL injection, your button doesn't do anything really, not without any JS which if you're using, you haven't shown it. Therefore, this answer is based on what you posted
It would require an type="submit" in order for your button to fire up anything.
I'm taking a blind stab at this, but I'm prrrrretty sure that's what's "not" going on here.
Plus and more importantly (and not a blind stab), you're missing a closing bracket, a quote and semi-colon in: (a major syntax error)
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')
^^^ missing bracket/quote/semi-colon
so do
mysqli_query($connect,"INSERT INTO submit (submission)
VALUES ('".$_POST['text']."')");
^^^ missing/added
Escape your data:
if(!empty($_POST['text'])){
$text = mysqli_real_escape_string($connect, $_POST['text']);
mysqli_query($connect,"INSERT INTO submit (submission) VALUES ('".$text."')");
}
However, you really should use a prepared statement for that SQL injection:
https://en.wikipedia.org/wiki/Prepared_statement
Check for errors.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
If your entire code is inside the same page, you will receive undefined index notice.
Error reporting will tell you that.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As well as or die(mysqli_error($connect)) to mysqli_query().
If so, then you will need to use !empty() for the POST array.
http://php.net/manual/en/function.empty.php
You could have also used:
$connect = mysqli_connect("localhost","mod","","bill")
or die(mysqli_error($connect)); // check if successful or not
if(!empty($_POST['text'])){
$text = mysqli_real_escape_string($connect, $_POST['text']);
$query = "INSERT INTO submit (submission) VALUES ('".$text."')";
$result = mysqli_query($connect, $query);
if (!$result)
{
throw new Exception(mysqli_error($connect));
}
else{ echo "Success."; }
}
You can try isset() function to insert the input into your database.
if(isset($_POST['singlebutton']))
{
$text= $_POST['text'];
$query= $connect->prepare ( "INSERT INTO submit(submission) VALUES (?)");
$query -> bind_param("s",$text );
if ($query->execute())
{
echo"<center><strong>Text added! </strong></center>";
} // display when text is added
else{
echo"Error in adding text!"; // display when there is error
}
}

MySQL / PHP database connection to input text from a web form

I have a simple web form, which I want the user to fill out and when they click the submit button the information from the form should be inserted into the correct tables in the mySQL database for later use. I have a database called foundation_fitness with a table called Client.
The problem I am facing is this error message upon clicking submit:
Notice: Undefined index: exampleInputEmail1 in C:\xampp\htdocs\ffitness\dist\new_client.php on line 19
Notice: Undefined index: forname1 in C:\xampp\htdocs\ffitness\dist\new_client.php on line 20
Notice: Undefined index: surname1 in C:\xampp\htdocs\ffitness\dist\new_client.php on line 21
Notice: Undefined index: height1 in C:\xampp\htdocs\ffitness\dist\new_client.php on line 22
Notice: Undefined index: weight1 in C:\xampp\htdocs\ffitness\dist\new_client.php on line 23
Notice: Undefined index: bodyfat1 in C:\xampp\htdocs\ffitness\dist\new_client.php on line 24
Below is my code for new_client.php. EDIT: Changed Foundation_fitness to Client for the INSERT INTO
<?php
define('DB_NAME', 'foundation_fitness');
define('DB_USER', 'root');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value2 = $_POST['exampleInputEmail1'];
$value3 = $_POST['forname1'];
$value4 = $_POST['surname1'];
$value5 = $_POST['height1'];
$value6 = $_POST['weight1'];
$value7 = $_POST['bodyfat1'];
$sql = "INSERT INTO client (Client_email, Client_forename, Client_surname, Height, Weight, Body_fat) VALUES ('$value2',
'$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql);
mysql_close();
And the code for my html form is as follows: EDIT - Changed method mistake and id to name
<form action="new_client.php" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" name="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="forename1">Forename</label>
<input type="text" class="form-control" name="forname1" placeholder="Enter First Name">
</div>
<div class="form-group">
<label for="surname1">Surname</label>
<input type="text" class="form-control" name="surname1" placeholder="Enter Surname">
</div>
<div class="form-group">
<label for="height1">Height (cm)</label>
<input type="text" class="form-control" name="height1" placeholder="Enter Height">
</div>
<div class="form-group">
<label for="weight1">Weight (kgs)</label>
<input type="text" class="form-control" name="weight1" placeholder="Enter Weight">
</div>
<div class="form-group">
<label for="bodyfat1">Body Fat %</label>
<input type="text" class="form-control" name="bodyfat1" placeholder="Enter Body Fat Percentage">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Any help with the error and getting the php script working would be much appreciated!
EDIT: I am now not getting the error message as I changed the method mistake and id to name in the HTML form. I am still not able to get the information into the table on the mySQL database even with the additional change of the table name which should have been client as I do not have a table called foundation_fitness that is the database name.
It means that there are no such keys in the $_POST array. You should use name attribute (not id) for the form elements if you want to use them later as keys in the $_POST array. Also, you have a typo : mehtod should be method attribute in your form element.
Your INSERT statement uses foundation_fitness as the table name, which is the same as your DB name. Your answer to #notulysses comment suggests the table name should be client
INSERT INTO client ...
Can you confirm that you have a foundation_fitness table inside your foundation_fitness database.
EDIT:
If your table name is Client, your query might have to be INSERT INTO Client, since table names could be case sensitive, depending on the underlying file system. Also, the error seems to be happening at the mysql level, so you can change your code this way to actually see the error :
$result = mysql_query($sql);
if ($result !== false) {
// everything is fine, proceed with script
} else {
// Something went wrong :
die(mysql_error($link)); // to see the error from MySQL
}
The error output from MySQL should help you a lot, if not, post it here so we can further help you.
As a side note, mysql_connect is deprecated as of PHP 5.5, so perhaps looking into PDO would be a good start to refactoring your code.
Another thing (very important) : your query is exposed to SQL Injection, you are taking user input without validation and/or sanitization. If that is your production code, you absolutely need to fix it. You should use prepared statements to shield yourself from SQL injection.
You are getting these notices because of post request to same page. Once the page load it read your php code but couldn't find any post data.
As you are using single php file i.e form's 'action' is redirecting the page to itself. So once you fill the form and click submit these notices disappear, as data is sent via post.
You can hide these notices by usingerror_reporting(E_ALL ^ E_NOTICES). It hides all the notice error you are getting.
But I would recommend you to use a different page for form action redirect to insert data into database and then redirect that page back to you main page using header('Location:newclient.php').

MySQL stores only "1" (as a value) no matter what numbers I submit in the form

I am trying to create a simple bootstrap form in php and mysql (I use xampp with default settings). Everything is done in 1 file called index.php.
Here is my form:
<form class="form-horizontal" role="form" method="post" action="index.php" >
<div class="form-group">
<label for="inputLongitude" class="col-lg-2 control-label">Longitude</label>
<div class="col-lg-10">
<input type="number" class="form-control" id="inputLongitude" placeholder="longitude" name="inputLongitude">
</div>
</div>
<div class="form-group">
<label for="inputLatitude" class="col-lg-2 control-label">Latitude</label>
<div class="col-lg-10">
<input type="number" class="form-control" id="inputLatitude" placeholder="latitude" name="inputLatitude">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" name="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
The form is very simple, it takes 2 values and stores them in the db. And here my php code I use to store values in mysql (in the same file - index.php):
$conn = mysqli_connect('localhost', 'root', '', 'android_app') or die("bla");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$longti = isset($_POST['inputLongitude']);
$lati = isset($_POST['inputLatitude']);
$sql = "INSERT INTO `table`(`key_primary`, `lati`, `longti`) VALUES (`key_primary`,$lati,$longti)";
mysqli_query($conn,$sql);
Until now almost everything works fine. The both values are saved.
Here is my setting for db: http://i.imgur.com/hyuNJsj.jpg
NOW my problem: Values, which are supposed to be saved (= which I want to submit and store in the db) , are not stored. So instead of storing e.g. "50,5" mysql stores only "1" - always, no matter what I sent in the form. Take a look here http://imgur.com/brjFn5e.
What is really interesting is that if I use SQL in phpmyadmin and insert values there ("manual way") it is ok. No problem at all. Do you an idea how I can solve that? Is my db setting wrong ? Or it is somewhere in the code ?
Your problem occurs here:
$longti = isset($_POST['inputLongitude']);
$lati = isset($_POST['inputLatitude']);
This block is assigning the truth value of isset(...) to $longti and $lati instead of your intended values from $_POST. If you're completely assured of the security of these $_POST values (which you should not be), then you should have:
$longti = isset($_POST['inputLongitude']) ? $_POST['inputLongitude'] : null;
$lati = isset($_POST['inputLatitude']) ? $_POST['inputLatitude'] : null;
If these values are coming from untrusted sources (as $_POST values usually are) then you should also perform some validation on the values before outputting them to your db.
Edit: I just noticed $out = isset($in) ? $in : null; pattern looks (and is) redundant: $out = $in; would perform exactly the same. My usual is to include basic validation/filtering within this step. For instance, if all you're expecting/allowing is a numeric value (since your <input> type is 'numeric'):
$longti = isset($_POST['inputLongitude']) && is_numeric($_POST['inputLongitude'])
? $_POST['inputLongitude'] : null;
or integers only:
$longti = isset($_POST['inputLongitude']) ? (int) $_POST['inputLongitude'] : null;
These are simplistic examples that don't include feedback to the user of invalid form content, etc.
You are using the isset function
$longti = isset($_POST['inputLongitude']);
the above code does not set the value of $_POST['inputLongitude'] but rather whether $_POST['inputLongitude'] exists... 1 would mean that it exists.
You can simply use:
$longti = $_POST['inputLongitude'];
$lati = isset($_POST['inputLatitude']);
This is always 0 or 1 :isset or not.Use if isset blah=someotherblah
if (isset($_POST["inputLatitude"])) {
$lati = $_POST['inputLatitude'];
}else{
echo "N0, inputLatitude is not set";
}

Categories