insert 100+ variables into query string - php

I have an online survey format with approx 200 input / select fields which I now want to write into my database. Now, since I dont want to go through the tedious process of writing out every single variable one-by-one in the query string, I was hoping that there would be an easier way, eg. using an array?

Here is a solution that I use. It requires that the database field names are the same as the <input> names:
$querystring1 = ""; $querystring2 = "";
foreach($_POST as $key => $var) {
$querystring2 .= "'".$var."',"; $querystring1 .= $key.",";
}
$insertquerystring = "(".$querystring1.") VALUES (".$querystring2.")";
mysql_query("INSERT INTO `mytablename` $insertquerystring") or die(mysql_error());

Related

PHP MySQL Where clause isn't working

I have a database like which has multiple columns and when querying it with a WHERE clause it won't get any results.
Here is the code I am using :
$columns = $_GET['var'];
$where = $_GET['where'];
$checkValue = $_GET['checkValue'];
$userInput = $_GET['userInput'];
$query = "SELECT ";
foreach($columns as $val)
$query .= "$val, ";
$query .= "FROM Email";
if($where === "yes")
$query .= " WHERE $checkValue = '$userInput'";
$columns is multiple checkboxes for the user to select which columns they wish to see. It works perfectly except when adding the where clause. When I've been testing it I made sure that the it was exactly the same as in the database. Also the $checkValue is a dropdown list which values are exactly the same as in the database. Also just to note later on I edit the query so the last comma is removed.
To print it out I use :
while($c = mysqli_fetch_assoc($results)){
foreach($columns as $val){
$header = ucwords($val);
echo "<b>$header</b><br>";
echo $c[$val]."<br>";
}
echo "-------------------------------<br>";
}
This is the query that is outputted when not using the where clause and works:
SELECT date, mediatype FROM Email
And here is the query that doesnt work:
SELECT date, mediatype FROM Email WHERE mediatype = 'Blog'
Any advice?
EDIT:
Here is the table with:
There is more columns but these are ones I want to focus on.
Your generate SQL request seems to have a syntax error. Just change the way you generate it.
Instead of
foreach($columns as $val)
$query .= "$val, ";
Try
$query .= implode(', ' $columns);
That will skip the last comma.
The blog column had an extra empty line that 'Blog%' wasn't working on. I went in the database and deleted the extra line and used the query again and it worked.
Thanks everyone for the help :)

PHP extract each record in variable for insert

Here is my PHP variable:
$container = $_POST['containerNumber'];
Inside $_POST['containerNumber'], there are multiple container numbers that are retrieved when a user checks a checkbox from a form. That code is not necessary to display. Just know that $_POST['containerNumber'] can have multiple container numbers assigned to it.
What I need to do is extract each container number from the POST so that I can run a mysql INSERT statement per each container number.
In the database table, there are multiple columns, with container_num being the column I'm trying to update (for now).
How can I turn $container into an array and retrieve each container number that has been assigned to the variable?
I know I need to utilize a FOREACH loop. With that said, there will more than likely be multiple INSERT statements that will automatically be created with the loop.
$SQL = "INSERT INTO myTable (container_num) VALUES ('$container')";
// times however many containers the variable $container had stored in it
Please help.
EDIT **
Once the user checks however many checkboxes, I can display each container like this:
<INPUT name="containerNumber" id="containerNumber" class="containerNumber" />
When I do this, it can be displayed to the screen like this:
CONT_ID001, CONT_ID002, CONT_ID003...
I hope this helps.
There are multiple ways of doing this.
1) Give the POST parameters you're sending a name that ends with [], PHP automatically assigns them to an array when parsing the POST data. If you're sending the data from an HTML form, this is an example of how to do it:
<form action="" method="POST">
<label>
First container number:
<input type="text" name="containerNumber[]" />
</label>
<label>
Second container number:
<input type="text" name="containerNumber[]" />
</label>
<input type="submit" />
In PHP you can just do
foreach($_POST["containerNumber"] as $container) {
...
}
(Note that this is a feature of PHP and not portable to other server-side langages. This is NOT part of the HTTP specification.)
2) Separate values using some separator, in PHP use explode() to split it.
3) Send the form as JSON or encode that one field as JSON (if sent from HTML, I suggest using jQUery to do either option, as it's the easiest way) and use json_decode() in PHP to extract the contents.
4) Sevaral other options that may be suitable, depending on what exactly you're doing.
If I get you, you have a $_POST variable with multiple values.
If the content of $_POST['containerNumber'] is CONT_ID001, CONT_ID002, CONT_ID003
You can do this:
$result = preg_split("/, /", $_POST['containerNumber']);
//the result dump will be:
//$result[0] = "CONT_ID001";
//$result[1] = "CONT_ID002";
//$result[2] = "CONT_ID003";
The insert code should looks like to (assuming that you have one column for each number):
$SQL = "INSERT INTO myTable ";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$columns .= "container_$id";
$values .= "'$out'";
if (count($result) < $id+1){
$columns .= ", ";
$values .= ", ";
}
}
$SQL .= "($columns) VALUES ($values)";
If you only have container_num column it should looks like:
$SQL = "INSERT INTO myTable (container_num) VALUES ('";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$values .= $out;
if (count($result) < $id+1){
$values .= ", ";
}
}
$SQL .= "$values')";

Inserting a variable with multiple values into a mysql database

I thought I would edit my question as by the comment it seems this is a very insecure way of doing what I am trying to acheive.
What I want to do is allow the user to import a .csv file but I want them to be able to set the fields they import.
Is there a way of doing this apart from the way I tried to demonstrate in my original question?
Thank you
Daniel
This problem I am having has been driving me mad for weeks now, everything I try that to me should work fails.
Basically I have a database with a bunch of fields in.
In one of my pages I have the following code
$result = mysql_query("SHOW FIELDS FROM my_database.products");
while ($row = mysql_fetch_array($result)) {
$field = $row['Field'];
if ($field == 'product_id' || $field == 'product_name' || $field == 'product_description' || $field == 'product_slug' || $field == 'product_layout') {
} else {
echo '<label class="label_small">'.$field.'</label>
<input type="text" name="'.$field.'" id="input_text_small" />';
}
}
This then echos a list of fields that have the label of the database fields and also includes the database field in the name of the text box.
I then post the results with the following code
$result = mysql_query("SHOW FIELDS FROM affilifeed_1000.products");
$i = 0;
while ($row = mysql_fetch_array($result)) {
$field = $row['Field'];
if ($field == 'product_name' || $field == 'product_description' || $field == 'product_slug' || $field == 'product_layout') {
} else {
$input_field = $field;
$output_field = mysql_real_escape_string($_POST[''.$field.'']);
}
if ($errorcount == 0) {
$insert = "INSERT INTO my_database.products ($input_field)
VALUES ('$output_field')";
$result_insert = mysql_query($insert) or die ("<br>Error in database<b> ".mysql_error()."</b><br>$result_insert");
}
}
if ($result_insert) {
echo '<div class="notification_success">Well done you have sucessfully created your product, you can view it by clicking here</div>';
} else {
echo '<div class="notification_fail">There was a problem creating your product, please try again later...</div>';
}
It posts sucessfully but the problem is that it creates a new "row" for every insert.
For example in row 1 it will post the first value and then the rest will be empty, in row 2 it will post the second value but the rest will be empty, row 3 the third value and so on...
I have tried many many many things to get this working and have researched the foreach loop which I haven't been familiar with before, binding the variable, imploding, exploding but none of them seem to do the trick.
I can kind of understand why it is doing it as it is wrapped in the while loop but if I put it outside of this it only inserts the last value.
Can anyone shed any light as to why this is happening?
If you need any more info please let me know.
Thank you
Daniel
You're treating each field you're displaying as its own record to be inserted. Since you're trying to create a SINGLE record with MULTIPLE fields, you need to build the query dynamically, e.g.
foreach ($_POST as $key => $value);
$fields[] = mysql_real_escape_string($key);
$values[] = "'" . msyql_real_escape_string($value) . "'";
} // build arrays of the form's field/value pairs
$field_str = implode(',', $fields); // turn those arrays into comma-separated strings
$values_str = implode(',', $values);
$sql = "INSERT INTO yourtable ($field_str) VALUES ($value_str);"
// insert those strings into the query
$result = mysql_query($sql) or die(mysql_error());
which will give you
INSERT INTO youtable (field1, field2, ...) VALUES ('value1', 'value2', ...)
Note that I'm using the mysql library here, but you should avoid it. It's deprecated and obsolete. Consider switching to PDO or mysqli before you build any more code that could be totally useless in short order.
On a security basis, you should not be passing the field values directly through the database. Consider the case where you might be doing a user permissions management system. You probably wouldn't want to expose a "is_superuser" field, but your form would allow anyone to give themselves superuser privileges by hacking up their html form and putting a new field saying is_superuser=yes.
This kind of code is downright dangerous, and you should not be using it in a production system, no matter how much sql injection protect you build into it.
Alright....I can't say that I know exactly whats going on but lets try this...
First off....
$result = mysql_query("SHOW FIELDS FROM my_database.products");
$hideArray = array("product_id","product_name","product_description", "product_slug","product_layout");
while ($row = mysql_fetch_array($result)) {
if (!in_array($row['Field'], $hideArray)){
echo '<label class="label_small">'.$field.'</label>
<input type="text" name="'.$field.'" id="input_text_small" />';
}
}
Now, why you would want to post this data makes not sense to me but I am going to ignore that.....whats really strange is you aren't even using the post data...maybe I'm not getting something....I would recommend using a db wrapper class...that way you can just through the post var into....ie. $db->insert($_POST) ....but if you ware doing it long way...
$fields = "";
$values = "";
$query = "INSERT INTO table ";
foreach ($_POST as $key => $data){
$values .= $data.",";
$fields .= $fields.",";
}
substr($values, 0, -1);
substr($fields, 0, -1);
$query .= "(".$fields.") VALUES (".$values.");";
This is untested....you can also look into http://php.net/manual/en/function.implode.php so you don't have to do the loop.
Basically you don't seem to understand what is going on in your script...if you echo the sql statements and you can a better idea of whats going....learn what is happening with your code and then try to understand what the correct approach is. Don't just copy and paste my code.

Passing multiple $_POST fields through MySQL search query

I have a search form with a possible 15 or so fields, however not all are required to carry out a search, for instance;
a user might search for a registered user in 'London' who works in 'Finance' but leave all other fields blank, such as $availability or $salary etc, so $_POST data may look something like:
$location = $_POST['location']; // Value - London
$sector = $_POST['sector']; // Value - Finance
$available = $_POST['available']; // Value - Any
$salary = $_POST['salary']; // Value - Any
Bearing in mind I may have another 12 or so 'Any' values from other fields, what is the best way to query the database (PHP/MySQL) to return results without looping through what would probably be dozens of queries.
To try and be a bit clearer, what i'd like is a query which would work something like (deliberate pseudo code):
SELECT * FROM table where location = 'location' AND if($availability !='Any') { available = '$available' } etc etc
Is something like this possible?
Or can I create a single string of all $_POST fields that !='Any' and then carry out a search on a row that contains all the words in the string (which I think would work in theory)?
I hope this makes sense to someone and you can point me in the right direction.
P.S. All $_POST is escaped and secured before interacting with database, just not included here :)
Try this:
$sql = "SELECT * FROM table where 1 ";
foreach ($_POST as $key => $post) {
if ($post != 'Any') {
$sql .= " AND $key = '$post' ";
}
}
// now you can run $sql against the database
Could you for argument sake collect all of the $_POST into a foreach($key=>$val) and then run the key through a switch or if statments that appends "AND x=x " to the statement?
Something like:
$sql = "SELECT * FROM table WHERE required='required'";
foreach($_POST as $key=>$val){
if(!empty($val)){ $sql .= " AND ".$key."='".$val"'"; }
}
Not sure if that works but in theory that is what i thought of first.
Thanks to those who offered answers, however I used the suggested answer found in the link above my question as it was clearer to me. Sample code pasted below FYI:
$tmp = "where ";
if($A and $A!="any" and $A!="not used")
$tmp .= "row1 = '".$A."'";
if($B and $B!="any" and $B!="not used")
$tmp .= "AND row2 = '".$B. "'";
if($C and $C!="any" and $C!="not used")
$tmp .= "AND row3 = '".$C."'";
$db_q = "Select * from table $tmp";
Thanks again, don't know where I'd be without SO.

Using $_POST in While PHP Question

I'm trying get some information via $_POST in PHP, basically at the moment i'm using this:
$item_name1 = $_POST['item_name1'];
$item_name2 = $_POST['item_name2'];
$item_name3 = $_POST['item_name3'];
$item_name4 = $_POST['item_name4'];
I want to insert each of the item names in a table field with mysql so i'm trying to experiment with the while php loop so i dont have lots of $item_name variables:
$number_of_items = $_POST['num_cart_items'];
$i=1;
while($i<=$number_of_items)
{
$test = $_POST['item_name'. $i''];
$i++;
}
The above code fails, its pretty tricky to explain but the code should find all the item_name $_POST and make it as a variable for mysql insertion.
The $_POST['num_cart_items'] is the total number of items.
The code is for a PayPal IPN listener for a shopping cart that is underway.
Help appreciated.
EDIT:
I have this further up the document which i just realised:
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
How can i insert $_POST['item_name1'], $_POST['item_name2'] as a variable for mysql insertion?
Your loop is effectively overriding the $test variable on each iteration:
$test = $_POST['item_name'. $i''];
If you want to put them in an array, change to $test[]. Also it contains the parse error as mentioned by brian_d.
It sounds a little scary to have a variable num_cart_items that is sent with the form. Are you setting it with JavaScript? The user can manipulate it. You should not rely on it. I belive what you need is to make the form feilds as:
<input type="text" name="item_name[]" />
Note the square brackets at the end of the name. This will create an array in the $_POST array: $_POST['item_name'] will contain the names of all the items.
Then, how is your DB structured? I guess you want to insert them in one query as:
INSERT INTO ORDERS VALUES (item_name_1, ...), (item_name_2, ...)
If so you can make a string out of the array:
$query = 'INSERT INTO ORDERS VALUES ';
foreach($_POST['item_name'] as $item_name){
$query .= '('.stripslashes($item_name). /*put other column values*/ '),';
}
$query = rtrim($query, ',');
Note that the use of addslashes is not enough to protect you from SQL injection.
$test = $_POST['item_name'. $i'']; is a syntax error.
remove the end '' so it becomes:
$test = $_POST['item_name'. $i];

Categories