How to write dynamic queries indepandant to the HTML form - php

I have problem with the following code i am trying t write the dynamic query which will be independent to my html form. Like i don't want to write the name a every single name of field in my query i want to make it dynamic thats why using the following the approach but the problem is right after the foreach block of code just below that
any other best way kindly guide me it'll be highly appreciated.
foreach(){
}
sql.="";
problem is here this sqli like contains only the last key and values not all the keys and values
Results:
INSERT INTO Patient(patient_cell) values (033480779)';
whereas i want results like this
INSERT INTO Patient(patient_name,patient_address,patient_pass,patient_cell) values (Saba,Daska,12345,033480779)';
HTML Form
<form method="post" action="Patient_data.php">
<label>Patient name:</label>
<input type="text" name="patient_name" placeholder="Patient name">
<br>
<label>Patient Address:</label>
<input type="text" name="patient_address" placeholder="Address">
<br>
<label>Patient's Password:</label>
<input type="text" name="patient_pass" placeholder="Password">
<br>
<label>Patient Cell:</label>
<input type="text" name="patient_cell" placeholder="Enter cell no.">
<br>
<input type="submit" value="Create Record" name="Create">
</form>
code:
$record['patient_name'] = $_POST['patient_name'];
$record['patient_address']=$_POST['patient_address'];
$record['patient_pass']=$_POST['patient_pass'];
$record['patient_cell']=$_POST['patient_cell'];
$dbname= new Db();
$dbname->Add($record);
function
public function Add($record) {
$var= $record;
$sql.= "INSERT INTO Patient";
foreach ($var as $key => $value) {
$key = "{$key},";
var_dump($key);
$value = "{$value},";
var_dump($value);
}
$sql.="(".substr($key,0,-1).") values (".substr($value,0,-1).")";

function Add($record) {
$var= $record;
$sql.= "INSERT INTO Patient ([%keys%]) values ([%vals%])";
$keys = "";
$vals = "";
foreach ($var as $key => $value) {
if (!empty($keys)) {
$keys .= ",";
}
$keys .= $key;
if (!empty($vals)) {
$vals .= ",";
}
$vals .= $value;
}
$sql = str_replace("[%keys%]", $keys, $sql);
$sql = str_replace("[%vals%]", $vals, $sql);
return $sql;
}
Try this function
Note : if some field is string you should add single quote in that field.

Related

insert multiple rows to a table using foreach php

i need to insert multiple rows data into table
Date and inspection_id will remain same
but the input values are repeated.
Here is the script i have
<?php
if (isset($_POST["submit"])) {
$taskdate = date('Y:m:d');
$inspection_id = '1';
$post = $_POST['nfo'];
foreach ($post['point_id'] as $key => $value) {
$point_id.= $value.", ";
}
foreach ($post['point_comment'] as $key => $value) {
$point_comment.= $value.", ";
}
foreach ($post['point_value'] as $key => $value) {
$point_value.= $value.", ";
}
$query = "INSERT INTO `inspections` (`inspection_id`, `point_id`, `value`, `comment`)VALUES('$inspection_id', '$point_id', '$point_value', '$point_comment')";
$result = mysql_query($query);
HTML FORM i am USING
<form action="pentasks.php" method="post">
<select name="nfo[point_value][]">
<option selected>Chose</option>
<option value="1">Qualify</option>
<option value="2">Disqualify</option>
</select>
<input name = "nfo[point_comment][]" value = "" type="text">
<input type="hidden" name="inspection_id" value="<?= $task_id; ?>"> <!-- value From another query -->
<input type="hidden" name="nfo[point_id][]" value="<?= $spot_id3; ?>">
<input type="submit" name="submit" value="Submit">
</form>
Help please how i insert data
this is something in a table questions are defined
retrieved on form with input to answer
Try this
foreach ($post['point_comment'] as $key => $value) {
$point_comment=$post['point_comment'][$value];
$point_value= $post['point_value'][$value];
//run your query here
}
and mysql is depricated Learn mysqli_ function or PDO.
and change your select tag like this
<select name="point_value[]">
<select name="point_comment[]">
Arif thanks for your effort but your answer did not helped
spend few hours by ownself i got it working and here is the working solution for my question
HTML FORM
<input type = "text" name = "point_comment[]" />
<input type = "text" name = "point_value[]" />
Here is Foreach loop PHP
$my_comment = $_POST['point_comment'];
$point_comment = "";
foreach ($my_comment as $key => $value) {
$point_comment = $value;
$my_value = $_POST['point_value'];
$point_value = "";
foreach ($my_value as $key => $value) {
$point_value = $value;
// SQL INSERT or anything query here
} }
Hope this will help for those looking for similar

How to add multiple input same name to database MySQL

Hi I want to add a lot of inputs with same name to my database.
I am working on a recipe submit form, that adds in ingredients with form input text. I have multiple inputs with same name, and want them all to be added to the database. By array of some sort.
I have a jquery that makes it possible to add in more ingredients and amount, don't think it is important for this question. So won't add.
Till now I have this html/php:
<form id="opskriftReg" name="opskriftReg" action="opskriftRegSave.php" method="post">
*Ingredienser:<br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
<div id="InputsWrapper"></div>
<input type="button" id="AddMoreFileBox" value="Tilføj ingrediens"><br>
<input type="submit" value="Submit">
</form>
And this for php/database input:
$mysqli = new mysqli ("localhost","","","brugerreg");
//Add this php add to database:
$ingredients = $_POST['ingredients'];
$amount = $_POST['amount'];
echo $ingredients." ".$amount;
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,
`amount`) VALUES ('".$ingredients."', '".$amount."')";
$stmt = $mysqli->prepare($sql); $stmt->execute();
Make your jQuery print your inputs such as:
<input type="text" name="ingredients[]">
<input type="text" name="amount[]">
Note the [] in the name, these are called HTML input arrays.
Now you can access these inputs in your PHP as:
$ingredients = implode(',',$_POST['ingredients']);
$amount = implode(',',$_POST['amount']);
echo $ingredients."<br>".$amount; //you could comment this
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,
`amount`) VALUES ('".$ingredients."', '".$amount."')";
$stmt = $mysqli->prepare($sql); $stmt->execute();
You could use the implode() function to convert an array into a single string with a delimiter
Found here.
Every time you add new input with same name, append it with "[]", so in the end you get:
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
Ingrediens: <input type="text" name="ingredients[]">
Mængde: <input type="text" name="amount[]"><br>
And in php:
$ingredients = $_POST['ingredients']; // $ingredients is now an array
$amount = $_POST['amount']; // $amount is now an array
echo $amount[0];
echo $amount[1];
To insert it into database just prepare the query accordingly, for example iterate over the array and concatenate the "('".$ingredients."', '".$amount."')" for every pair.
$values = "".
for ($i = 0; $i < sizeof($amount); $i++) {
$values .= "('".$ingredients[$i]."', '".$amount[$i]."')";
if ($i != sizeof($amount) - 1) {
$values .= ", ";
}
}
$sql = "INSERT INTO `brugerreg`.`opskriftreg` (`ingredients`,`amount`) VALUES " . $values;

php: how to shorten many $_POST[];

I'm working on a page with many insert fields.
how can i shorten the following code?
$title_1 = $_POST['title_1'];
$content_1 = $_POST['content_1'];
$link_1 = $_POST['link_1'];
$img_link_1 = $_POST['img_link_1'];
$title_2 = $_POST['title_2'];
$content_2 = $_POST['content_2'];
$link_2 = $_POST['link_2'];
$img_link_2 = $_POST['img_link_2'];
$title_3 = $_POST['title_3'];
$content_3 = $_POST['content_3'];
$link_3 = $_POST['link_3'];
$img_link_3 = $_POST['img_link_3'];
You could loop through the $_POST array like this:
foreach ($_POST as $key => $value) {
${$key} = $value;
}
This will make your post variable like $_POST['title_1'] into $title_1
Remember your post names will have to be the exact names you want your variables to be referenced by.
I would do:
$howmany = 3; // How many sets of fields are submitted.
for($i=0;$i<$howmany;$i++){
$field[$i]['title'] = $_POST['title_'.$i];
$field[$i]['content'] = $_POST['content_'.$i];
$field[$i]['link'] = $_POST['link_'.$i];
$field[$i]['img_link'] = $_POST['img_link_'.$i];
}
Then you can access data in $field[1]['title'] form.
You can use extract (http://php.net/manual/en/function.extract.php): extract($_POST)
But you should be careful -- what if the client POSTs user_id, or something? At the least, you should specify that $_POST values won't overwrite already-defined variables: extract($_POST, EXTR_SKIP)
I redid this answer after you edited your post. Use variable variables.
foreach ($_POST as $key => $val)
{
if (preg_match('/^(([a-z]+_)+\d)$/', $key, $match)
{
$$match[0] = $val;
}
}
Use [a-z0-9] or [a-zA-Z0-9] as alternatives.
<?php
$key_prefixes = array (
'title',
'content',
'link',
'img_link'
);
$i = 1;
while (true) {
$post_values_missing = 0;
foreach ($key_prefixes as $key_prefix) {
$key = $key_prefix . '_' . $i;
if (!isset($_POST[$key])) {
$post_values_missing += 1;
continue;
};
$val = $_POST[$key];
// do something with $val
}
// did you get any values through this iteration?
$post_values_exist_bool = (count($key_prefixes) !== $post_values_missing);
// if not, you must've gotten them all
if (false === $post_values_exist_bool) {
break;
}
$i += 1;
}
The cleanest way to do this would be to use PHP's POST data processing capabilities to do the work for you.
Consider using your HTML form names as follows:
<form action="{url}" method="post">
<input type="text" name="data[0][title]" />
<input type="text" name="data[0][content]" />
<input type="text" name="data[0][link]" />
<input type="text" name="data[0][image_link]" />
<input type="text" name="data[1][title]" />
<input type="text" name="data[1][content]" />
<input type="text" name="data[1][link]" />
<input type="text" name="data[1][image_link]" />
...
</form>
In PHP extract the data as follows:
$data = $_POST['data'];
This shortens your PHP code to just one line. This statement will directly give you an array in PHP of the data form input. A var_dump will look as follows:
array (
0 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
1 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
...
)
You don't have to change your name, just make it array;
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
PHP:
extract($_POST);
$count=count($title);
for($i=0;$i<$count;$i++) {
//You can perform your any function on this loop, to get title use $title[$i]
}

php add multiple input fields to mysql

I have this code:
<html>
<body>
<form id="myForm" method="post" action="add-data.php">
<input type="submit">
<input type="text" name="pollquestion">
<input type="text" name="polloption1">
<input type="text" name="polloption2">
</form>
Add option
<script>
var optionNumber = 3;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "polloption"+optionNumber+""; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
</body>
</html>
If i add more inputs i will have something like this:
<input name="pollquestion" type="text">
<input name="polloption1" type="text">
<input name="polloption2" type="text">
<input name="polloption3" type="text">
<input name="polloption4" type="text">
<input name="polloption5" type="text">
<input name="polloption6" type="text">
The php code is something like this:
$qu = $_POST['pollquestion'];
$op1 = $_POST['polloption1'];
$op2 = $_POST['polloption2'];
$query = "INSERT into `".$db_table."` (question, option1, option2) VALUES ('" . $qu . "','" . $op1 . "','" . $op2 . "')";
How can i add this data to mysql for every added row? Thanks!
One way of many...
$query = "INSERT into `$db_table` SET `question` = '".mysql_real_escape_string($_POST['pollquestion'])."'";
foreach (range(1,6) as $idx) {
if (!empty($_POST['polloption'.$idx])) {
$query .= ", `option$idx` = '".mysql_real_escape_string($_POST['polloption'.$idx])."'";
}
}
of course the mysql_real_escape_string is important to avoid http://en.wikipedia.org/wiki/SQL_injection
First, you need to know how many options you're submitting so add another constant input to the form:
<input type="hidden" id="numOptions" name="numOptions"/>
In the addOption() function update its value (before incrementing optionNumber):
document.getElementById( "numOptions" ).value = optionNumber;
On the server side you need to create your query dynamically like so:
$options = array();
$values = array();
$numOptions = intval( $_POST[ "numOptions" ] );
for ( $i = 1; $i <= $numOptions; $i++ )
{
$options[] = "option$i";
$values [] = "'" . mysql_real_escape_string( $_POST[ "polloption$i" ] ) . "'";
}
$query = "INSERT INTO $db_table(" . implode( ',', $options ) . ") VALUES( '" .
implode( ',', $values );
Please mind the escaping of the received strings! very important to prevent SQL injections.
HTML
<input name="title" type="text">
<input name="descr" type="text">
<input name="question[1]" type="text">
<input name="option[1][1]" type="text">
<input name="option[1][2]" type="text">
<input name="option[1][3]" type="text">
<input name="right[1]" type="radio" value=1>
<input name="right[1]" type="radio" value=2>
<input name="right[1]" type="radio" value=3>
<input name="question[2]" type="text">
<input name="option[2][1]" type="text">
<input name="option[2][2]" type="text">
<input name="option[2][3]" type="text">
<input name="right[2]" type="radio" value=1>
<input name="right[2]" type="radio" value=2>
<input name="right[2]" type="radio" value=3>
PHP
$title = mysql_real_escape_string($_POST['title'])
$descr = mysql_real_escape_string($_POST['descr'])
$query = "INSERT into `polls` (title,descr) VALUES ('$title', '$descr')";
$id = $db->query($query);
foreach ($_POST['question'] as $num => $q) {
$q = mysql_real_escape_string($q)
$query = "INSERT into `poll questions` (poll,question) VALUES ($id,'$q')";
$db->query($query);
foreach ($_POST['option'][$num] as $i => $opt) {
$right = ($_POST['right'][$num]) == $i)?1:0;
$opt = mysql_real_escape_string($opt)
$num = intval($num);
$query = "INSERT into `poll options` (poll,num,option,right)
VALUES ($id,$num,'$opt',$right)";
}
}
You can iterate $_POST, matching keys with regular patterns, something like that:
foreach($_POST as $key => $value) {
preg_match('/(\w+)(\d+)/Uis', $key, $m);
if($m[1] == 'polloption') {
// concatenate new values to your query
}
}
Remembering relational databases, you have fixed number of attributes in your table. So you should add fixed number of options.

PHP: How to correctly loop through multi-dimen post arrays

If I have a form with fields like this.
THERE WILL BE MULTIPLE ROWS OF THESE FIELDS HENCE THE SQUARE BRACKETS
<input type="text" name="txt-receipt-number[]" value="" />
<input type="text" name="txt-stock-number[]" value="" />
<input type="text" name="txt-repair-code[]" value="" />
How do I loop through the $_POST variable to get the values because its getting the field names but not the values, what am I doing wrong please?
$fields = array();
$values = array();
foreach($_POST as $field => $value) {
$fields[] = $field;
echo $value;
}
Output:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Update:
Sorry, quick edit for correct output...
Further Update:
Lets ignore the insert, how do I get the values please?
Remove the [] of your text input, or you will get $value of array type.
<input type="text" name="txt-receipt-number" value="" />
<input type="text" name="txt-stock-number" value="" />
<input type="text" name="txt-repair-code" value="" />
And don't forget to quote your values.
foreach($_POST as $field => $value)
{
if(is_array($value))
{
foreach($value as $k => $val)
{
echo $val;
}
}
else
{
echo $value;
}
}
Works for regular fields and one-dimensional _POST fields.
You will have some other problems though, with column names like sales_receipt-number, etc. You should enclose those in backquotes, and you must also escape them since they are going directly into your SQL statement. They are just as vulnerable to SQL injection as the VALUES().
$fields[] = "`" . mysql_real_escape_string($field) . "`";
Update 2
To get the values and do the insert in a loop, the SQL needs to be reconstructed each time in the loop, using one set of array values.
// Find the number of loops necessary
// Unless all fields are always required, this will need to be the $_POST key with the most values
$numLoops = count($_POST['txt-receipt-number']);
fields = array();
$values = array();
for ($i = 0; $i < count($_POST); $i++) {
foreach($_POST as $field => $value) {
$fields[] = "`" . mysql_real_escape_string($field) . "`";
$values[] = mysql_real_escape_string($_POST[$field][$i]);
// Now build the SQL for this loop iteration.
$sql = 'insert into table(' . join(',', $fields) . ') values(' . join(',', $values) . ')';
}
}
To be honest, I see many problems in this code...
Using foreach to build dynamic list of fields that need to be inserted. Don't you have, for example, anything like <input type='submit' name='add_data'/>? It's common to have submit buttons, and, with your code, you would try to edit DB table's field named add_data. This is also unsafe, as it (a) reveals table structure and (b) gives possibility to make SQL errors by manually changing field names, which may lead to another security/stability issues.
Lack of escaping field names. May lead to SQL injections.
Using - sign in field names. insert into table(sales_receipt-number, ... just won't work.
As for handling posted arrays...
<form method='post' action=''>
<table border='1'>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td colspan='3'>
<input type='submit' name='add_items'/>
</td>
</tr>
</table>
</form>
<pre>
<?php
function handleAddingItem() {
if ( !isset($_POST['receipt_number'], $_POST['stock_number'], $_POST['repair_code']) ) {
trigger_error("Some field is undefined");
return false;
}
if ( !is_array($_POST['receipt_number']) || !is_array($_POST['stock_number']) || !is_array($_POST['repair_code']) ) {
trigger_error("Some field is not an array");
return false;
}
$keys = array_keys($_POST['receipt_number']);
if ( array_keys($_POST['stock_number']) !== $keys || array_keys($_POST['repair_code']) !== $keys ) {
trigger_error("Posted arrays have different keys");
return false;
}
foreach ( $keys as $key ) {
if ( empty($_POST['receipt_number'][$key]) && empty($_POST['stock_number'][$key]) && empty($_POST['repair_code'][$key]) ) {
continue;
}
$receiptNumber = mysql_real_escape_string($_POST['receipt_number'][$key]);
$stockNumber = mysql_real_escape_string($_POST['stock_number'][$key]);
$repairCode = mysql_real_escape_string($_POST['repair_code'][$key]);
$sql = "
insert into table_name set
receipt_number = '{$receiptNumber}',
stock_number = '{$stockNumber}',
repair_code = '{$repairCode}'
";
echo $sql;
}
return true;
}
function handlePost() {
print_r($_POST);
if ( isset($_POST['add_items']) ) {
handleAddingItem();
}
}
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
handlePost();
}
?>
Output:
Array
(
[receipt_number] => Array
(
[0] => 123
[1] =>
[2] =>
)
[stock_number] => Array
(
[0] =>
[1] =>
[2] =>
)
[repair_code] => Array
(
[0] =>
[1] =>
[2] =>
)
[add_items] => Submit Query
)
insert into table_name set
receipt_number = '123',
stock_number = '',
repair_code = ''
Common practice might be to pass additional field - row's ID. If it has a value, then action is "edit", if it is empty, action is "create".
This is a little bit strange but try it :
<?php
foreach($_POST['txt-receipt-number'] as $k=>$v){
$array[$k]['txt-receipt-number'] = $_POST['txt-receipt-number'][$k];
$array[$k]['txt-stock-number'] = $_POST['txt-stock-number'][$k];
$array[$k]['txt-repair-code'] = $_POST['txt-repair-code'][$k];
}
$fields = array();
$values = array();
foreach($array as $row) {
foreach($row as $field => $value) {
$values[] = $value;
$fields[] = $field;
}
}
var_dump($fields);
var_dump($values);
?>
<form method='post' action=''>
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
----
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
<input type="submit" value="go">
</form>

Categories