So say I have a form like so:
<form action="submit2.php">
<input name="name" type="text" />
<input name="age" type="text" />
<input type="submit" />
</form>
I using this code to insert the values of the form into a database table called "example" after the user clicks the submit button.
mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
However, all I get is a blank entry in the table. Am I wrong in assuming that an input's value becomes a variable if if is giving a name(e.g. name="age") in the html code?
Access the variables through the $_POST global variable.
if(isset($_POST['name']) && isset($_POST['age'])){
$name = mysql_real_escape_string($_POST['name']);
$age = mysql_real_escape_string($_POST['age']);
mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
}
An input named "name" will create a variable $name in submit2.php only if register_globals is enabled, which is a security issue. You should never have register_globals turned on (it will be removed in PHP6, by the way).
I'm not sure what the default method attribute is, but it should create a variable named either $_GET['name'] or $_POST['name']. If it doesn't create any of them, add a method attribute to your form :
<form action="submit2.php" method="post">
However, this does not assure you that those variables exist (what if someone access submit2.php without using your form?). You have to use either isset or !empty (I prefer the latter, because it also checks if it's not empty).
Last thing : don't forget to escape your variables. Never trust user input. In this case, since you're inserting a variable in a query, you should use mysql_real_escape_string function.
you need to change the data from the form to usable values
<form action="submit2.php" method="post">
<input name="name" type="text" />
<input name="age" type="text" />
<input type="submit" />
</form>
and change database query portion to:
$name=mysql_real_escape_string($_POST['name']);
$age=mysql_real_escape_string($_POST['age']);
mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
The mysql_real_escape_string helps security for not having script injected into your database and having someone change or remove entries.
Related
views/registration.php
<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>
classes/registration.php
if(isset($_POST['submit']))
{
// Define form variables
$username = $_POST['username'];
$password= $_POST['password'];
// Insert form data into database
$query = "INSERT INTO users (username, password)
VALUES ('$username', '$password')";
if(mysqli_query($conn, $query))
{
echo "Registration successfull.";
}
}
The problem is, when I click submit, I get a blank page. The query isn't being executed.
I thought the problem might be because my values aren't setup correctly, so I did the following:
VALUES ('$_POST['password']', '$_POST['password']')";
but that gives me an error, presumably because I am using ' inside of '
So now I am back to square one, unsure of why my query isn't being executed
You are getting a blank page because you don't echo something if $_POST submit isn't set.
if(isset($_POST['submit']))
is never true as your $_POST['submit'] is never set. You need to give your submit a name, this (the name) is what get's POSTed / what you can access within $_POST[' /*name of input*/ ']
Change your form to the following, then you should see your
echo "Registration successfull.";
HTML:
<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit"> <!-- <<<<<<<<<<< here -->
As a sidenote, you should absolutely consider using a prepared statement. Running a registration form with your insert query is like an invitation for people keen on ruining your server. You might want to try the query like this:
$query = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$query->bind_param('ss',$username,$password);
$query->execute;
This way, you will be secured against mysql injection.
Your file naming and paths seem to be mismatching(as per the file names you provided).
No matter if you keep:
views/registration.php
views/classes/registration.php
But if you follow:
--/classes
/registration.php
--/views
/registration.php
[Note: '--/' is the path of your root directory]
Then the form action classes/registration.php won't go anywhere.
So change it:
<form action="../classes/registration.php" method="post">
I suggest to follow the naming convention:
filename- for pages with HTML forms, and
filename_action- for action pages
Also notice the possible error cases mentioned by user baao in the other answer.
This is a "best practice"/"most efficient" question. I have a large form (20+ fields). Form post into one large MySQL table.
No I can't break up the form and no, I can't break up the table (its being used to hold measurements); used by admin sales reps. Also, I don't want to use Javascript.
I know I can do this:
HTML
<form action="etc.php" method="post">
<input type="text" name="neck" value="">
<input type="text" name="arm" value="">
<input type="text" name="back" value="">
<input type="text" name="chest" value="">
<input type="text" name="legs" value="">
<submit button>
PHP
<?
$_POST['neck'];
$_POST['back'];
$_POST['arm'];
$_POST['chest'];
$_POST['legs'];
$postMeasurements = "INSERT INTO measurements (etc, etc, etc,) VALUES (etc, etc, etc) WHERE etc='etc'; query ($postMeasurements);
?>
But is there a faster way? Instead of having to declare each individual post, simply just run a loop that takes all the data post and inserts into the table. Even if the data has be in the same order of the columns of the table or if the input names have to be the same as the table column names is fine by me; I am just getting tired have to keep writing all these $_POST variables into.
Second question: What is the best way to hold this data in case of an error? As it stands now, I hold everything in $_SESSION (one session variable for each input), then redirect back to the form page if there is an error with an error message. then echo each $_SESSION variables as that inputs value.
Thanks,
if the fields as the exact names as the field names. post can only have the fields and nothing else
//if $_POST has the form then, also this is very unsafe because there is no injection prevention too
$sql = "INSERT INTO table (" . implode(",", array_keys($_POST)) . ")"
. "VALUES ('" . implode("','", array_values($_POST)) . "')";
You can directly use $_POST['foo'] inside your query, and need not declare :) .
holding the data could be in session, or inline cache, if you have huge data, its better to use some cache in server, and onload of the form, it retrieves the data from server based on SESSION_ID
Have the page post to itself.
Then do something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
// validate and insert post data
header("Location: $successUrl");
exit();
}
?>
<form action="etc.php" method="post">
<input type="text" name="neck" value="<?= $_POST["neck"]?>">
<input type="text" name="arm" value="<?= $_POST["arm"] ?>">
....
I have a variable number of fields in a form.
The number of text fields are defined by the user with a function in jquery, but the final code of the form (example) is this:
<form id='form_educ' name='form_educ' method='post' action='form/educ.php'>
<div id='educ'>
<input type='text' name='date1' id='date1'/>
<input type='text' name='date2' id='date2'/>
<input type='text' name='date3' id='date3'/>
<input type='text' name='date4' id='date4'/>
....
</div>
<input type='submit' name='form_educ' value='Refresh'/>
</form>
These text fields when added by the user is create a sql INSERT TO (in another file):
$date = clean($_GET['date']);
"INSERT INTO educ (index_of_form, date, email) VALUES('$index', '', '" .mysql_real_escape_string($_SESSION['SESS_EMAIL']). "')";
$date is date1, or date2, or date3 or date4 (example).
Now in the file educ.php I want to update all text fields in the mysql database.
Usually it is a
$example = clean($ _POST ['example']);
I can do an update in the table and is resolved.
But in my case how can I get all the values โโof the text field on the form and set the $_POST var if the number of fields is variable (could be date1, date2, date3, date4)?
I can think of no reason why form field name should be a unknown variable. Unless you're dealing with repeatable fields, in which case you would use an array like dates[], and you'd know what to expect in the process script.
For additional info see for example: http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/
Word of warning for future. When you make the field repeatable, allow users also to delete the fields they might have accidentally insertet. Watch out in the process script missing array keys (numerical index from 0โ10 might be missing some values if the user deleted some form fields before submitting). You can reset the array keys with the array_merge function. Missing keys is an issue if you have two arrays you are trying to add into database as syncronized.
Updated to answer the comment.
Sorry, I don't undestand your question. You don't necessarily have to use hidden field. What you need is a database structure to match your forms function: to support one to many relationship. After all you are inserting multiple dates that relate to one person, or some specific event type, or what ever. Lets assume one user wants to add his three favorite dates in the world. Your form's source code looks like:
<input type="text" name='dateLover' id='dateLover'/>
<input type="text" name="dates[]" id="date1" /> //you need a increasing variable for these id numbers (or dont't put the id at all)
<input type="text" name="dates[]" id="date2" />
<input type="text" name="dates[]" id="date3" />
In addition you could have more fields such as <input type="text" name="extra" />. In submitted $_POST array there would be variables and arrays like: $_POST['dateLover'], $_POST['date'][0], $_POST['date'][1], $_POST['date'][2], $_POST['extra']. You'd take the non-repeatable values straight out of the $_POST array but you need a foreach (or some else loop) to handle the dates array.
Your database has to contain two tables (structure simplified):
person: id, dateLover
date: id, dateLover FK to person.dateLover, date
In your process script you have to:
insert a new dateLover to person and use last_insert_id to get his id
use a foreach to insert new dates to table date (with a dateLover's id as FK)
This all is pretty well demonstrated in the link I supplied earlier. For now, it's hard to give an complete example without undestanding the actual problem.
Update 2.
You are serializing the form, not the div's. So your (dynamically generated) could look like this:
<form id="form_educ" name="form_educ" method="post" action="form/educ.php">
<div id="educ">
<div><!--This is for layout only-->
<input type="text" name="dates[]" id="date0" />
<input type="text" name="names[]" id="name0" />
</div>
<div>
<input type="text" name="dates[]" id="date1" />
<input type="text" name="names[]" id="name1" />
</div>
<div>
<input type="text" name="dates[]" id="date2" />
<input type="text" name="names[]" id="name2" />
</div>
</div>
<input type="submit" name="form_educ" value="Refresh" />
</form>โ
And in your process file you take these arrays from $_POST array and insert them into database maybe like this (with properly escaped and checked values of course...):
//dynamic part of the query
$qEnd = '';
$i = -1;
//this is static part of the query
$qBeginning = "INSERT INTO `date` (`id`, `date`, `name`) VALUES ";
foreach ($_POST['dates'] as $key => $date){
$i++;
$qValues[$i] = "(null, '{$date}', '{$_POST[names][$i]}')"; //never do this, always check values...
//value sets are concatenated one after another to the $qEnd
$qEnd .= $qValues . ',';
}
//combine the query parts and remove extra "," from the end
$q = $qBeginning . rtrim($qEnd, ',');
//now the (single) query ($q) is ready to be executed, echo it just for the fun of it
id should be auto increment field, or this kind of stuff doesn't work on the fly.
Again, this all should be clear in the jQuery link example so please read it carefully.
You should know all of the possible columns that could be updated before hand. Just check to see if those are set in the $_POST variable, then if they are append the insert or update statement with those values.
DANGER: Just looping on the $_POST variable looking at all params may end up inserting not database related POST fields into your insert statement and breaking.
Also when using these methods, be aware of SQL Injection, and use parameterized queries and never directly insert POST variable names or values into the SQL Statment.
having a bit of trouble adding some data to a database. I have the file new_entry.php which is a form, which posts the data added to insert_new.php.
Every time the fields are filled in and submitted the data does not go to the database with the error message "Could not add the data to table" appearing..any ideas?
NEW_ENTRY.PHP
<body>
<form method="post" action="insert_new.php"><!-- form sent to insert_new.php-->
Section: <input type="text" name="section"/><br />
Food: <input type="text" name="food"/><br />
Description: <input type="text" name="description"/><br />
Price: <input type="text" name="price"/><br />
<br />
<input type="submit" value="submit"/>
</form>
</body>
INSERT_NEW.PHP
<?php
include 'library/connect.php';//connect to databse
$section = $_REQUEST["section"]; // get data from the HTML form on new student form
$food = $_REQUEST["food"];
$description = $_REQUEST["description"];
$price = $_REQUEST["price"];
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', $price)")/* insert the data to the food_menu table*/
or die ("Could not add the data to table");//error message
header('Location:index.php');//auto redirect to view page
include 'library/closedb.php';
?>
It seems that you have a mistake at the end of your MySQL query near price.
Please replace the code below with existing line:
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', '$price')")
Tell me the result please.
First: Don't do this. You really need to research SQL Injection or you will be very sorry.
Secondly, your price has no numeric validation (assuming it's going into a numeric column)... this is also bad... what if someone put in a dollar sign or something?
Next, please post your table definition and connection code (not the connection values).
You can also get more feedback if you do something like:
or die (mysql_error());//error message
When users submit a form, they will sometimes click refresh or backspace then resubmit which causes multiple entries in mysql. How can i prevent mysql from allowing more than 1 of the same entry? People suggested a hidden field with a value, but how do I use that?
<label for="state" class="styled">State:</label>
<input type="text" id="state" name="state" value="<?php if (!empty($state)) echo $state;
?>" size="30" /><br />
//a hidden field of a certain value?
________________________________________
<input type="submit" value="Post Ad!" name="submit" />
//php to insert to mysql
$query4 = "INSERT INTO posting (state) VALUES ('$state')";
mysqli_query($dbc, $query4);
You can use this after insert query.
$query4 = "INSERT INTO posting (state) VALUES ('$state')";
mysqli_query($dbc, $query4);
header("Location: yourpage.php");
This was just asked yesterday
Relying on a client side validation is poor form. Do any checks server side and redirect the user appropriately.