Using an array to populate other variables using a foreach - php

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) {

Related

Insert data of multiple form fields by foreach loop

I have four fields. Two name fields and two email fields. I have to insert all fields data by foreach loop but when I insert data through foreach loop, a blank entry also inserts in database.
sample code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post">
Name : <input type="text" name="name[]"><br>
Email : <input type="text" name="email[]"><br>
Name : <input type="text" name="name[]"><br>
Email : <input type="text" name="email[]"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
[![<?php
if(isset($_POST['submit']))
{
$conn = mysqli_connect("localhost", "root", "", "practice");
$i=0;
foreach($_POST as $val)
{
$name=$_POST['name'][$i];
$email=$_POST['email'][$i];
$sql = "insert into interview (Name, Email) values ('$name', '$email')";
$result = mysqli_query($conn, $sql);
$i++;
}
}
?>
Can anybody help me ?
First, see here How can I prevent SQL injection in PHP? Do your query differently or you're screwed.
Since name and email are indexed the same, just loop one and reference the other by key:
foreach($_POST['name'] as $key => $val) {
$name = $val;
$email = $_POST['email'][$key];
// prepared statement query
}
Or you could do inputs like this to get arrays more like database rows:
Name : <input type="text" name="data[0][name]"><br>
Email : <input type="text" name="data[0][email]"><br>
Then loop it easily:
foreach($_POST['data'] as $val) {
$name = $val['name'];
$email = $val['email'];
}
#Simple Answer!
foreach($_POST['name'] as $index => $val) {
$name = $val;
$email = $_POST['email'][$index];
$sql = "insert into interview (Name, Email) values ('$name', '$email')";
$result = mysqli_query($DB_Connection, $sql);
}
We note that 'submit' is also a value in $_POST.
It looks like the code will go through the loop three times, one time for each of 'submit', 'name' and 'email'. (It might be going through the loop five times, not sure? I'd just echo $val in the loop to see what's going on.)
It looks like you are attempting to loop through either $_POST['name'] or $_POST['email'], rather than just $_POST.
As long as you get an equal number in each of those, it shouldn't matter which.
Code appears to be vulnerable to SQL Injection.
If there is some (unfathomable) reason you can't use prepared statement with bind placeholder, any potentially unsafe values need to be properly escaped. PHP has a mysqli_real_escape_string function which is expressly designed for this purpose.
Also, there doesn't appear to be any check for an error being returned from mysqli_query. It looks like the code is putting its figurative pinky finger to the corner of its mouth, Dr.Evil style, and saying "I just assume it will all go to plan. What?"

Increment double-bracket PHP arrays to SQL

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
}

POST checkbox name even if its not checked

Is it possible to POST checkbox name even if its not checked?
<input type='checkbox' class='tinyField' name='alert_by_email' value="1" <?PHP echo $alert_by_emailChecked ?> />
foreach ($_POST AS $field => $value)
$sql[] = $field." = '". $value."'";
$sql = implode(' , ',$sql);
$query = "UPDATE user_setup SET ".$sql." WHERE (userID = ".$userID.") " ;
$res = mysql_query($query);
So when I PRINT_R the POST i will get the field, but it will be empty
Array ( [alert_by_email] => '' )
Add this before your checkbox.
<input type='hidden' name='alert_by_email' value="" />
The straight forward answer is no.
The HTML form wont send the checkbox if it's not checked.
However, there are some workarounds:
use js to Generate a hidden input for each checkbox you have, set the value to 0 or '', and whenever you check them, remove the hidden input.
you could simply test if the key exist in the post like so:
if (isset($_POST['alert_by_email']))
In Short, No this is not possible if you are posting FORM without using any Javascript.
Also, Your code may be injected easily as you are relying on user provided column names without validating those. I am posting alternative way to do that. Hope that helps:
Suppose you have this HTML Form:
<form method="POST">
First name:<br />
<input type="text" name="firstname" />
<br />
Last name:<br />
<input type="text" name="lastname" /><br />
<input type="submit" />
</form>
Now, if you want to update values using PHP, your code should be:
<?php
$columnArray = array('firstname' => NULL, 'lastname' => NULL); // This is list of columns which can be updated using form input values (NULL is default value here)
$submittedValues = array_intersect_key($_POST, $columnArray);
// Above code will produce an array like `array('firstname' => 'anyname', 'lastname' => 'anylastname')
//--> Now you can generate your SQL using `$submittedValues`
$sql = array();
foreach ($submittedValues as $field => $value)
{
$sql[] = $field." = '". $value."'";
}
$sqlString = implode(' , ',$sql);
Using this way, hacker will not be able to add extra columns which shouldn't be updated by user i.e. last_login_date or something.

send array[] from php to mysql

im working on a project but first i would to understand one thing.
i have 2 input type text field with name="firstname[]" as an array (in the example im working with no jquery but it will be generated dinamically with it) and cant make it to mysql.
here is what i have: index.php
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname[]"> <br>
Firstname 2: <input type="text" name="firstname[]">
<input type="submit">
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("localhost","inputmultiplicad","inputmultiplicado","inputmultiplicado");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO input_field (firstname)
VALUES
('$_POST[firstname]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
the question is: how can i send the firstname[] array to the mysql database?
thanks for your time
This should work:
//Escape user input
$names = array_map('mysql_real_escape_string', $_POST[firstname]);
//Convert array to comma-delimited list
$names = rtrim(implode(',', $names), ',');
//Build query
$sql="INSERT INTO input_field (firstname) VALUES ('$names')";
Note: In general, it's better to use parameterized queries than mysql_real_escape_string(), but the latter is much safer than no escaping at all.
The following should generate the SQL statement you need. Remember to use mysql_escape_string before putting it into your database, though! Or even better, use PDO and bind the values. :)
$values = array();
$sql = "INSERT INTO table (firstname) VALUES ";
foreach ($_POST['firstname'] as $name) {
$values[] = "('".mysql_real_escape_string($name)."')";
}
$sql .= implode(",", $values);

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.

Categories