I have a registration form that allows a user to register as many people as they want. For example I don't know ahead of time if 1 person is registering or if 500 are. So on the server side if I have 3 people registering at once I need to access all the first names of a person by $_POST['first0'] $_POST['first1'] and $_POST['first2']. So here is my database query.
for ($i=0; $i < runners; $i++) {
$query = "INSERT INTO ".$usertable." VALUES (".$_POST['first'.$i].", ".$_POST['last'.$i].", ".$_POST['age'.$i].",
".$_POST['gender'.$i].", ".$_POST['email'.$i]." , ".$_POST['phone'.$i]." , ".$_POST['address'.$i]." ,
".$_POST['city'.$i]." , ".$_POST['state'.$i]." , ".$_POST['zip'.$i]." , ".$_POST['type'.$i]." , ".$_POST['tshirt'.$i].")";
My query is not working so I know my quotes and apostrophes are incorrect would anyone be able to show me the correct way to accomplish this. Any help is appreciated!
First of all, posted data is a lot easier to work with if your form entries use the array syntax, i.e.:
<label>First: <input name="first[]" value="" /></label>
<label>Last: <input name="last[]" value="" /></label>
<label>Age: <input name="age[]" value="" /></label>
<label>Gender:
<input type="radio" name="gender[]" value="m" />Male
<input type="radio" name="gender[]" value="f" />Female
</label>
Then, in your code, values like $_POST['first'] are an array of values.
Secondly, you should look at prepared statements. Observe:
$stmt = $db->prepare('INSERT INTO mytable (first, last, age, gender) VALUES (?, ?, ?, ?)');
foreach ($_POST['first'] as $index => $value) {
$stmt->execute(array(
$value,
$_POST['last'][$index],
$_POST['age'][$index],
$_POST['gender'][$index],
));
}
First of all, you should prevent SQL injection while interacting with database.
Use mysqli_real_escape_string. Here is the updated query.
for ($i=0; $i < runners; $i++) {
$firstname = mysqli_real_escape_string($_POST['first'.$i]);
$lastname = mysqli_real_escape_string($_POST['last'.$i]);
$age = mysqli_real_escape_string($_POST['age'.$i]);
$gender = mysqli_real_escape_string($_POST['gender'.$i]);
$email = mysqli_real_escape_string($_POST['email'.$i]);
$phone = mysqli_real_escape_string($_POST['phone'.$i]);
$address = mysqli_real_escape_string($_POST['address'.$i]);
$city = mysqli_real_escape_string($_POST['city'.$i]);
$state = mysqli_real_escape_string($_POST['state'.$i]);
$zip= mysqli_real_escape_string($_POST['zip'.$i]);
$type= mysqli_real_escape_string($_POST['type'.$i]);
$tshirt= mysqli_real_escape_string($_POST['tshirt'.$i]);
$query = "INSERT INTO ".$usertable." VALUES ('".$firstname."', '".$lastname ."', ".$age .",
'".$gender ."', '".$email ."', ".$phone." , '".$address ."' ,
'".$city."' , '".$state."' , ".$zip." , '".$type."' , '".$tshirt."')";
The better way to do this is instead of using user0, user1, user2, ...
You can actually past the html input text as an array.
e.g:
<!-- first user field -->
<input type="text" name="users[]" />
<!-- second user field -->
<input type="text" name="users[]" />
<!-- third user field -->
<input type="text" name="users[]" />
So your php will look something like this:
$users = $_POST['users'];
foreach ($users as $user) {
insertQuery = "INSERT INTO $userTable VALUES ('".mysqli_escape_string($user)."');
}
Of course the code above is only an example with 1 variable you can apply them to all other variables.
Cheers.
As suggested by #plain jane you are missing a lot of single quotes.
You can use PHP's variable replacement capability like the following. This is much more readable code.
$query = "INSERT INTO $usertable VALUES ('{$_POST['first'.$i]}', '{$_POST['last'.$i]}', '{$_POST['age'.$i]}',
'{$_POST['gender'.$i]}', '{$_POST['email'.$i]}', '{$_POST['phone'.$i]}', '{$_POST['address'.$i]}' ,
'{$_POST['city'.$i]}' , '{$_POST['state'.$i]}' , '{$_POST['zip'.$i]}' , '{$_POST['type'.$i]}' , '{$_POST['tshirt'.$i]}')";
Warning: Your code is vulnerable to SQL injection and can be easily broken with just a single quote in any posted field. even St'Mary as first name will break your code. To prevent this
Please validate/sanitize your posted values
Use Prepared statements instead of direct query string.
Related
Here is a example of what my form looks like.
<div>
<input name="address[1][name]" type="text">
<input name="address[1][street]" type="text">
<input name="address[1][city]" type="text">
<input name="address[1][phone]" type="text">
</div>
<div>
<input name="address[2][name]" type="text">
<input name="address[2][street]" type="text">
<input name="address[2][city]" type="text">
<input name="address[2][phone]" type="text">
</div>
...
I'd like to increment the data obtained from each block in PHP and increment it into my database with MySQL.
What is the best way to achieve this ?
I know it generates arrays, but I do not know how to deal with the "double-bracket" method (the form "aaa[x][bbb]" probably has a proper name, which I do not know, I'm sorry).
Thanks.
If you want to iterate over all fields using double brackets, the best structure to use are nested foreach's:
$formdata = $_POST['address'];
foreach($formdata as $group)
{
$SQLFields = array();
$SQLValues = array();
foreach($group as $field => $value)
{
// Here you have each individual field inside each group, so you can
// build the fields of the INSERT statement.
$SQLFields[] = $field;
$SQLValues[] = $value;
}
// Now assemble everything, and your INSERT is ready.
$SQL = "insert into table (".
implode(", ", $SQLFields).
") values ('".
implode("', '", $SQLValues).
"')";
// Run the SQL statement the way you want.
}
I think you are looking for something like this:
$data = $_POST['address'];
foreach($data as $address) {
//your address-object (name, street, city, phone)
var_dump($address);
//Add your sql-query in here and DO NOT forget to escape your received data
}
I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.
These two fields are inserted into a database. However, I want to give the user the ability to "Add another item". They should be able to, ideally, add as many items as they like. When they submit the form, the data would be inserted into a mysql table.
How can I go about doing this? Creating 10 extra columns in my database to accommodate extra items being added does not sound realistic nor ideal.
Thanks for the help!
Here is a snippet of my code, where I insert my data into the DB:
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
$stmt->close();
}
This is a pretty complex question, but there are some pretty straightforward solutions. First off, you'll need to change the back-end PHP script that you use to handle having a variable number of items.
For example, right now, you probably have something like:
$item_number = $_POST['item_number'];
$item_description = $_POST['item_description'];
add_item_to_db($item_number, $item_description);
You'll need to change your code to handle the processing of an array of items:
$item_numbers = $_POST['item_number'];
$item_descriptions = $_POST['item_description'];
// validate that count($item_numbers) == count($item_descriptions)
for ($i = 0; $i < count($item_numbers); $i++) {
add_item_to_db($item_numbers[$i], $item_descriptions[$i]);
}
There's quite a bit of error handling that you'll need to perform above that's not shown. If the user enters a different number of item_numbers than item_descriptions, you'll have to determine how to handle that. Also, any of the fields may be blank. Some cases may be errors, others perhaps not.
You'll have to change your HTML:
<input type="text" name="item_number[]" />
<input type="text" name="item_description[]" />
Note the [] in the name. That specifies an array of values for each.
Finally, you'll need to dynamically add a new set of input items on the screen when the user presses the Add another item link. I would recommend using jQuery for this. To accomplish this you would do something like:
jQuery('<input type="text" name="item_number[]" /><input type="text" name="item_description[]" />').appendTo('#someDiv');
Ensure that the new input elements are appended inside the form element. Obviously, there is a lot of code left to be written. This is just a basic example of the concepts.
Just use :
name="item[]"
for item # '
and
name="description[]"
<input type="text" name="item[]" /><input type="text" name="description[]" />
For item description field and in your server side iterate through both of them.
in the front end just create a script that duplicate that node many times.
EDIT
Based in the code you showed it should be something similar to the below code :
if(isset($_POST['item']){
for($i = 0; $i < count($_POST['item']); $i++){
$number = $_POST['item'][$i];
$description= $_POST['description'][$i];
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
$stmt->close();
}
}
In your javascript do like below:
function addRow(){
document.getELementById('container').el.innerHTML += '<input type="text" name="item[]" /><input type="text" name="description[]" />' ;
}
HTML Code:
<form name='myform' >
<div id="container">
<input type="text" name="item[]" /><input type="text" name="description[]" />
</div>
<p onclick="addRow() ;" >Add another item</p>
</form>
I hope this helps.
UPDATE
Try this one :
if(isset($_POST['item']){
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
for($i = 0; $i < count($_POST['item']); $i++){
$number = $_POST['item'][$i];
$description= $_POST['description'][$i];
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
}
$stmt->close();
}
Could someone tell how to write this insert into a database? The below code is an example of what I am trying to accomplish. I want to have a form for families with multiple children. They submit their family names and one id that they will share in the database. See code below...
FORM INPUTS
<input type="text" name="fname[]"/>
<input type="text" name="lname[]"/>
<input type="text" name="fname[]"/>
<input type="text" name="lname[]"/>
<input type="text" name="family_id"/>
This is where I am having troubles. I can submit the family names but only the first(row) "name" is storing the "family_id" as well.
PHP
foreach($_POST['fname'] as $key => $fname) {
$lname = $_POST['lname'][$key];
$family_id = $_POST['family_id'][$key];
$query = mysql_query("INSERT INTO Table (FName, LName, Family_ID ) VALUES ('{$fname}', '{$lname}', $_POST['family_id'])");
}
I appreciate any help!
Missing {} around $_POST['family_id'].
family_id insn't an array.
So the first iteration you get
$_POST['family_id'][0]; // gets the id
The second
$_POST['family_id'][1]; // gets undefined index
To fix it do the following.
Add the following code before foreach loop and concat $family_id to the query like you did with the others.
$family_id = $_POST['family_id'];
Try this:
extract($_POST);
$total=count($fname);
for($i=0;$i<count($total);$i++)
{
$fname=$fname[$i];
$lname=lfname[$i];
$query="INSERT INTO Table (FName, LName, Family_ID ) VALUES ('{$fname}', '{$lname}', $family_id)";
}
I have two fields
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
how to post name and lastname in one variable meaning in one field of database
is it
<?php
$name=$_post['firstname']['lastname'];
?>
Actually you have three fields. Use string concatenation (or implode):
$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
And don't forget to use mysql_real_escape_string (or what #ThiefMaster says) if you store the values in a database. Never trust user input.
Just concatenate the two values e.g.
<?php
$name = $_POST['firstname'] . $_POST['lastname'];
?>
keep an array, and serialize it to store it.
$name['firstname']=$_post['firstname'];
$name['lastname']=$_post['lastname'];
//storage and retrieval methods
$stored_name = serialize($name);
$name = unserialize($stored_name);
This way you don't lose the functionality of having the variables separate in an array, and you can always concatenate them later for display if you need to.
You can give the text inputs the same name with []
Firstname: <input type="text" name="name[]" />
Lastname: <input type="text" name="name[]" />
then you can
$name = $_POST['name'][0].$_POST['name'][1];
but i would prefer
$name=$_post['firstname'] . ' ' . $_post['lastname'];
This One will help You...! I also implemented this and it works...!
Firstname: <input type="text" name="firstName" />
Lastname: <input type="text" name="lastName" />
$fullname = $_post['firstName']. ' ' .$_post['lastName'];
$name = $firstname . " " . $lastname;
Then post $name in whatever field you want.
I had this same problem, i have a form with the name of the person reporting the issue and it takes the first name and the last name from my database of users and adds them together, but then when it came time to post both names to the database it would only post the first name.
my solution was to first of all call the first name and last name from the database of users, then i called just the first name and last name and concat them together to produce reportername.
so this is the first part of the code calling for the user details i require for the form:
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
// exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$first_name = $row["First_Name"];
$last_name = $row["Last_Name"];
$userlevel = $row["userlevel"];
}
Next i Concat the first name and last name:
$reporter_sql = "SELECT CONCAT (First_name,' ', Last_name) AS reportername FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$reporter_results = mysqli_query($db_conx, $reporter_sql);
while ($row = mysqli_fetch_array($reporter_results, MYSQLI_ASSOC)){
$reportername = $row['reportername'];
}
then you can post it to your database:
$reportername = mysqli_real_escape_string($db_conx, $reportername);
$sql = "INSERT INTO yourform (`reportedby`) Value ('$reportername')";
I have striped my code down so it gives you an idea and I'm sure coders with more experience could tell you a simpler way to do this i just know it worked for me.
A shortcut way to concatenate variables is this:
$name = "$_POST[first_name] $_POST[last_name]"
General comment. A good proportion of the world don't have first and last names.
Better practice is just to ask for "Name", and stick it in one field.
If you must split 'em, then "given name" and "family name" are better labels.