Increment double-bracket PHP arrays to SQL - php

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
}

Related

how to search array of checkboxes

Im building a search form but how do you search a array of checkboxes?
here is my html form
<form method="get">
<label>
<input type="checkbox" name="material[]" value="metal">metal
</label>
<label>
<input type="checkbox" name="material[]" value="plastic">Plastic
</label>
<label>
<input type="checkbox" name="material[]" value="carbon">Carbon
</label>
<input type="text" name="keyword">
<input type="submit" value="search">
</form>
and the php so far is. So how can i search the material for each checked.
<?php
if(isset($_GET['keyword'])){
$keyword = $_GET['keyword'];
// $material = $_GET['material'];
// $Search->search($keyword);
}
?>
ANd the query would be so far
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE `material` = ?');
When posted this will submit an array named material (accessible via $_GET['material']) that contains only the values that were checked.
You can then use those or output them like this:
foreach ($_GET['material'] AS $material) {
echo $material;
}
Addition after the question was edited:
You can also implode() the array values with ', ' as glue and use that as the search parameter in your SQL statement. Just change it to use IN instead of =, like #Prashant M Bhavsar suggested in his answer.
I think this will help you
Get your submitted material array in variable
$material_array = $_POST['material'];
You can implode array in select query to fetch related result
$selected_search_material = implode(',', $material_array);
SELECT * FROM `shop` WHERE `material` IN ($selected_search_material)
I haven't tested this yet, but since you receive an array ($_get['material'] is already an array), just use the following code with find_in_set;
<?php
$materials = array();
if (array_key_exists('material', $_GET)) {
$materials = $_GET['material'];
}
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE find_in_set(cast(material as char), :materials');
$query->execute(array('materials' => $materials));
?>
Implode $_GET['material'] and use a different query:
$where = implode(', ',$_GET['material']);
$query = $this->pdo->prepare('SELECT * FROM `shop` WHERE `material` IN ?');
Then use $where in your execute();
You can use $materialValue to store into Database.
<?php
if(isset($_GET['material'])){
$material = $_GET['material'];
foreach($material as $materialIndex){
$materialValue .= $materialIndex.',';
}
}
// use value to store into db
pass $materialValue variable to IN query also remove last "," from string
$materialValue.substring(0,$materialValue.length()-1);
?>

PHP foreach Construct Confusion

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.

scripting $_POST variable on the fly

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.

Textfield array and while loop

I if have inputs like this one, but those 2 inputs are repeating themselves multiple times. So it could be:
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
...
Is it possible to use while or foreach loop to get both values at the same time and insert it both in database like:
"INSERT INTO database (field1, filed2) VALUES ('$_POST["Gpodaciogolubu"]','$_POST["Gpodaciogolubu_godina"]')"
I'm coding in PHP/MySQL
First build an array of rows to insert:
$rows = []; // or array() in PHP 5.3 and older
$l = count($_POST['Gpodaciofolubu']);
for( $i=0; $i<$l; $i++) {
$rows[] = "("
."'".mysql_real_escape_string($_POST['Gpodaciofolubu'][$i])."', "
.intval($_POST['Gpodaciofolubu_godina'][$i]) // since you have `type="number"`
.")";
}
Then batch insert them:
mysql_query("insert into `database` (`field1`, `field2`) values ".implode(",",$rows));
This assumes, of course, that you're using the mysql extension. This assumption is based on the complete lack of any attempt to sanitize your input.

Using an array to populate other variables using a foreach

In simple terms I have a form which has three identical entry fields. The names are different; however, when posted they have the same structure just different name prefix (ie three systems have different name prefixes: they would be windowstitle, mactitle, linuxtitle etc).
Currently I have a process that will only work one namesake out ie windowstitle (if the form is filled out, of course)
The code looks something like this:
<?php
$title = $_POST['windowstitle'];
//validate info or redirect
if ($title != "" ) {
$title = mysql_real_escape_string($title);
$sql = "insert into newwindows (title) values ('$title');
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
?>
Also the form block looks something like this
<form action="newuserprocess.php" method="post" enctype="multipart/form-data">
<div class="form">
<h3>Windows</h3>
<!-- title of system name -->
<p><label for="windowstitle"> edition of system </lable></p>
<input type="text" name="windowstitle" size=20 /><br />
</div>
<div class="form">
<h3>Mac</h3>
<!-- title of system name -->
<p><label for="mactitle"> edition of system </lable></p>
<input type="text" name="mactitle" size=20 /><br />
</div>
<p><input type="submit" id="submit" class="bigbutton" value="Upload" /></p>
</form>
However, that leaves other forms left out with the only difference being the db I wanted entered and the post value prefix different.
So I came up with what I thought was a clever solution:
<?php
$arr = array('windows', 'mac', 'linux');
foreach ($arr as &$value) {
$title = $_POST['$valuetitle'];
//validate info
if ($title != "" ) {
$title = mysql_real_escape_string($title);
$sql = "insert into new$value (title) values ('$title');
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
}
?>
However, this does not work. I know partly why; because '' makes the variable appear as is, thus my $_Post will always come back as $value. Another reason is the same with my new$value database name. What is the proper format for this? How do I make this work?
you probably want
$title = $_POST[$value . 'title'];
and
$sql = "insert into new$value (title) values ('$title')";
Another reason is the same with my new$value database name. My question is what is the proper format for this?
I'd surround $value in brackets {$value} for clarity. Your format works but could be clearer. See some tests: http://ideone.com/A2kWU
Also, if you are not changing the values in array $arr then you should just use
foreach ($arr as $value) { //...
to prevent accidental changes. In this case it won't be a big deal, though, since you're just using the array once.
Edit your code like:
<?php
$arr = array('windows', 'mac', 'linux');
foreach ($arr as $value) {

Categories