How to insert array data to mysql table - php

I have two tables called op_group and options .These two tables are filled by array values. For example, I want to insert pizza details into my tables.
It look like this:
Cheese pizza and Sausage pizza will get inserted into the op_group table.
Other data will get inserted into the options table. These options should be inserted based on the relevant foreign key op_group id.
This is what i have tried. All details are inserted but not for the relevant op_group.
$opg_name=$_POST['opg_name'];
$price=$_POST['price'];
$itemCountz = count($opg_name);
$itemValues=0;
$queryValue1 = "";
for($i=0; $i<$itemCountz; $i++) {
$itemValues++;
if($queryValue1!="") {
$queryValue1 .= ",";
}
$queryValue1 = "INSERT INTO op_group
(opg_id,ml_id,cat_id,res_id,res_name,op_grp)
VALUES(NULL,'".$ml_id."','".$cat_id."','".$res_id."','".$res_name."','".$_POST["opg_name"][$i]."')";
$result1= mysql_query($queryValue1)or die(mysql_error());
$query6= "SELECT * FROM op_group ORDER BY opg_id DESC LIMIT 1" ;
$result6= mysql_query($query6);
while($row6 = mysql_fetch_assoc($result6)){
$opg_id=$row6['opg_id'];
}
$itemCount2 = count($price);
$itemValues1 = 0;
$queryValue2 = "";
for($j=0;$j<$itemCount2;$j++) {
if(!empty($_POST["op_name"][$j])||!empty($_POST["price"][$j])) {
$itemValues1++;
if($queryValue2!="") {
$queryValue2 .= ",";
}
$queryValue2 = "INSERT INTO options (op_id,opg_id,ml_id,cat_id,res_id,res_name,opt,price) VALUES (NULL,'".$opg_id."','".$ml_id."','".$cat_id."','".$res_id."','".$res_name."','".$_POST["op_name"][$j]."','".$_POST["price"][$j]."')";
}
}
$result2=mysql_query($queryValue2)or die(mysql_error());
}
This code give result like this
options table inserted data looks like this
how to solve this?

The reason why you are seeing options being duplicated for each option group is because your $queryValue2 is being repeatedly executed for each option group inside your outer most for($i = 0; $i < $itemCountz; $i++) loop.
As it stands, your current way of organizing the $_POST inputs are quite messy (and so are your duplicated row attributes). I will suggest you group your HTML inputs fields by each option group. You can try something like this:
<div>
<input type="text" id="first_order" name="orders[0][name]" /><br />
<input type="text" name="orders[0][options][0][price]" /><br />
<input type="text" name="orders[0][options][0][size]" /><br />
<input type="text" name="orders[0][options][1][price]" /><br />
<input type="text" name="orders[0][options][1][size]" /><br />
</div>
<div>
<input type="text" id="second_order" name="orders[1][name]" /><br />
<input type="text" name="orders[1][options][0][price]" /><br />
<input type="text" name="orders[1][options][0][size]" /><br />
<input type="text" name="orders[1][options][1][price]" /><br />
<input type="text" name="orders[1][options][1][size]" /><br />
</div>
Notice how I use the HTML name attribute to group the food options by the food. Then if you submit this form, you will see that the $_POST array appears to look something like this:
Array
(
[orders] => Array
(
[0] => Array
(
[name] => "Cheese Pizza"
[options] => [0] => Array([size] => "8'"
[price] => "12")
[1] => Array([size] => "12'"
[price] => "14")
)
[1] => Array
(
[name] => "Sausage Pizza"
[options] => [0] => Array([size] => "8'"
[price] => "13")
[1] => Array([size] => "12'"
[price] => "16")
)
)
)
Now you can tidy up your backend PHP codes with something like this:
foreach ($_POST['orders'] as $orders) {
// .. some codes
foreach($orders as $order) {
// .. add codes to insert into op_groups where $order['name'] will give you the pizza name
foreach($order['options'] as $details) {
// .. add codes to insert into options where $details['size'] and $details['price'] will give you the corresponding values
}
}
}
Also, you can use mysqli.insert-id to get the row ID of the last inserted row. Then you can get rid of that silly $query6 and its while loop.
Of course, don't forget to sanitize your $_POST inputs before using them!
I am getting a bit tired, if there are mistakes, I will fix them up tomorrow. Hope it helps!

Related

Show only the specific indexed array

How can I show only the specific index? For example, here's my UI.
As you can see in the picture I have 3 checkboxes and 3 textboxes with array value.
Let's say these are the name of the element.
<input type="checkbox" name="check[]">
<input type="text" name="textbox[]">
Then print the array:
$check = $_POST['check'];
$total_rec = $_POST['textbox'];
echo 'Check Array<br>';
print_r($check);
echo '<br<br><br><br>';
echo 'TextBox Array<br>';
print_r($textbox);
Result:
Check Array
Array ( [0] => 2 )
TextBox Array
Array ( [0] => [1] => 2 [2] => )
As you can see in textbox array all index showed, all I want is to show only the specific index with value and that is the 1 => 2 only.
use empty(), return true if contain value, example :
//iterate each $total_rec's member
foreach($total_rec as each){
//if $each not empty, do something
if(!empty($each)){
echo $each;
}
}
You are using $total_rec for post values of both checkbox and text. You can filter the array of text input like this:
$total_rec_text = $_POST['textbox'];
$total_rec_text = array_filter($total_rec_text, function($arr){
return !empty($arr) ? true : false;
});
You need to loop over $_POST array and check if checkbox is checked.
If checked, then only, get/print value.
Also, in HTML, you need to add specific counters to both checboxes and
textboxes.
As only checked checboxes get posted and texboxes get posted by
default.
<input type="checkbox" name="check[0]">
<input type="text" name="textbox[0]">
<input type="checkbox" name="check[1]">
<input type="text" name="textbox[1]">
<input type="checkbox" name="check[2]">
<input type="text" name="textbox[2]">
if (isset($_POST['check'])) {
foreach ($_POST['check'] as $idx => $value) {
echo "<br/>" . $_POST['check'][$idx] . ' ' . $_POST['textbox'][$idx];
}
}

How to iterate through $_POST to update multiple recordsets in DB via PDO

I'm new to PDO and associative arrays but am making good progress. I've set up this code to save a html form to a single recordset:
$str_sql = "UPDATE tbl_benutzer SET ";
foreach($_POST as $key=>$value){
if($key=='id'){continue;}
$str_sql .= $key." = :".$key.", ";
}
$str_sql = substr($str_sql,0,-2)." WHERE id = :id";
///////SAVE DATA TO DB///////
$stmt = $conn->prepare($str_sql);
$stmt->execute($_POST);
Now I want to adapt the same code to save the contents of a html form to multiple recordsets. Here's the HTML:
<input name="id[]" value="1">
<input name="tarif[]" value="A">
<input name="mitgliedschaft[]" value="X">
<input name="gebuehr[]" value="100">
<input name="id[]" value="2">
<input name="tarif[]" value="B">
<input name="mitgliedschaft[]" value="Y">
<input name="gebuehr[]" value="200">
<input name="id[]" value="3">
<input name="tarif[]" value="C">
<input name="mitgliedschaft[]" value="Z">
<input name="gebuehr[]" value="300">
And here's the $_POST array:
Array ( [id] => Array ( [0] => 1 [1] => 2 [2] => 3 )
[tarif] => Array ( [0] => A [1] => B [2] => C )
[mitgliedschaft] => Array ( [0] => X [1] => Y [2] => Z )
[gebuehr] => Array ( [0] => 100 [1] => 200 [2] => 300 ) )
This is what I've tried so far but my head's just not getting around it!:
$str_sql = "UPDATE tbl_stamm_tarif SET ";
foreach($_POST as $key=>$value){
if($key=='id'){continue;}
$str_sql .= $key." = :".$key.", ";
}
$str_sql = substr($str_sql,0,-2)." WHERE id = :id";
echo $str_sql;
///////SAVE DATEN TO DB///////
$stmt = $conn->prepare($str_sql);
foreach($_POST as $key=>$value){
foreach($value as $key2=>$value2){
$stmt->execute(array($key=>$value2));
}
}
Thanks in advance for any help!
I'd consider changing your HTML structure to something like:
<input name="**model_name**[**id1**][tarif]" value="A">
<input name="**model_name**[**id1**][mitgliedschaft]" value="X">
<input name="**model_name**[**id1**][gebuehr]" value="100">
<input name="**model_name**[**id2**][tarif]" value="B">
<input name="**model_name**[**id2**][mitgliedschaft]" value="Y">
<input name="**model_name**[**id2**][gebuehr]" value="200">
(for an UPDATE page you shouldn't really be allowed to change the id)
That way you can just iterate through the models as:
foreach($_POST['**model_name**'] as $id=>$model){}
and perform the UPDATE on each iteration as before.
UPDATE
I'd also be wary of your code as it is hugely vulnerable to SQL injection.. you should really check the value of each $key against the known columns before spanking straight it into a statement. Otherwise the user can submit their own $key and open up your database.
UPDATE 2
Either pull the columns from the database, or hard code them into whatever PHP model class you are using as an array (saves a trip, but needs doing if you change the schema).
I'd probably assign the values to a keyed array in the model class from the $_POST array before running the SQL, as you may need them later.
N.B.
A lot of these issues have already been solved in the various frameworks out there; no idea what your project is (could be writing a framework) but for anyone stumbling across this frameworks can save a lot of work and security vulnerabilities!

PHP $_SESSION ARRAY INTO MYSQL

I am wanting to do an array for the same user where multiple form data for the same item would be entered into the same table in MySQL.
Page 1
<form method="post" action="order-check-out.php">
<div>Country</div><div><input type="text" name="ef_country[]"></div>
<div>State</div><div><input type="text" name="ef_state[]"></div>
<div>City</div><div><input type="text" name="ef_city[]"></div>
<div>Country</div><div><input type="text" name="ef_country[]"></div>
<div>State</div><div><input type="text" name="ef_state[]"></div>
<div>City</div><div><input type="text" name="ef_city[]"></div>
<input type="submit" value="Order Services">
And the above could be more than 10 inserts.
Check Out page
$_SESSION['ef_country'] = $_POST['ef_country'];
$_SESSION['ef_state'] = $_POST['ef_state'];
$_SESSION['ef_city'] = $_POST['ef_city'];
$db->insert('as_user_addr', array(
"ef_client_id" => $userInfo['user_id'],
"ef_country" => $_SESSION['ef_country'],
"ef_state" => $_SESSION['ef_state'],
"ef_city" => $_SESSION['ef_city'],
));
However, if I have one set of input boxes, the data will insert into MySQL db without any issue. However, I cannot figure out how to do it for multiple form data. Many of the examples found on here seem to echo data, which does not help me. I am needing help with inserting data. I am not sure if it requires a count or loops, etc. I can write PHP the old way, but not this new type of programming.
for($i = 0; $i < count($_SESSION['ef_city']; $i++){
$db->insert('as_user_addr', array(
"ef_client_id" => $userInfo['user_id'],
"ef_country" => $_SESSION['ef_country'][$i],
"ef_state" => $_SESSION['ef_state'][$i],
"ef_city" => $_SESSION['ef_city'][$i],
));
}

Looping through $_POST

I have a MySQL database with the table "chapters". The table "chapters" has three columns: (1) id, (2) name, (3) password.
I am using PHP to dynamically output the data from "chapters" into text boxes. The result looks something like this:
<form name="current_chapters" method="post" action="UpdateChapters.php">
<input type = 'text' name='id' value='{$row['id']}'>
<input type = 'text' name='name' value='{$row['name']}'>
<input type = 'password' name='password' value='New Password'>
<input type = 'submit'>
</form>
Note that this page is used to reset (not display) passwords, hence the "New Password" default value.
I am looking for the best way to loop through all of that $_POST data and then update the original "chapters" table that this data originally came from.
I tried playing around with looping through $_POST via foreach and changing the input names to "id[]", "name[]", and "password[]", but it doesn't seem to be the most elegant approach, especially with the id part...you end up with things like id[0] = 133, which just seems messy.
Any recommendations on how to go about doing this?
Thanks in advance!
You can pass in structured data using $_POST. Which eases handling multiple fields of the same type:
<input name="book[12][name]" value="name of book 12">
<input name="book[12][password]" value="password for book12">
<input name="book[99][name]" value="name of book 99">
<input name="book[99][password]" value="password for book99">
Which will create data structure in $_POST like the following:
[book] => Array
(
[12] => Array
(
[name] => name of book 12
[password] => password for book 12
)
[99] => Array
(
[name] => name of book 99
[password] => password for book 99
)
)
Which you can then iterate as follows:
foreach ($_POST['book'] as $book_id => $book) {
// Watch out for SQL injection
$sql = "UPDATE book SET name = '{$book['name']}', password = '{$book['password']}' WHERE id = $book_id";
}

How to fetch dynamically generated input field's value in php?

I'm working on a form where I have 2 fields which can be added N number of times. I have 2 fields called "fieldA" and "fieldB" and a button called "addrow" . So as many times I click on addrow I add fieldA and fieldB beneath previous fieldA and fieldB. So I can have unlimited fieldAs and unlimited fieldBs. I use jquery to add rows and append new fields with number behind each field's name attr to make it unique. So first set of fields will be named as fieldA1, fieldB1 and second set will be named as fieldA2 , fieldB2 and so on.
This is how my part of my form looks
And here's my jquery
$(document).ready(function(){
var $i = 1;
$('body').on('click','#addrow',function(){
$('#fieldset').append(
"Your Friends Name: <br /><input type='text' name='fieldA"+$i+"' /><br /><br />Your Friends Email: <br /><input type='text' name='fieldB"+$i+"' /><br /><br />"
);
$i++;
});
});
Now since these fields are generated automatically using jquery I'm not sure how to fetch field's value in php.
also after fetching field's values I would also like to create an array.
This is how I expect to save values of all my fields in php array.
$fieldset = array(
array("fieldA" => "value of fieldA1","fieldB" => "value of fieldB1"),
array("fieldA" => "value of fieldA2","fieldB" => "value of fieldB2"),
array("fieldA" => "value of fieldA3","fieldB" => "value of fieldB3"),
...
);
You inputs must be array [], otherwise you will not be able to receive them as array fieldA[]
Your jQuery should be like this:
$(document).ready(function(){
var $i = 1;
$('body').on('click','#addrow',function(){
$('#fieldset').append(
"Your Friends Name: <br /><input type='text' name='fieldA["+$i+"]' /><br /><br />Your Friends Email: <br /><input type='text' name='fieldB["+$i+"]' /><br /><br />"
);
$i++;
});
});
HTML
Your Friends Name: <br /><input type='text' name='fieldA[0]' class='name'/><br /><br />
Your Friends Email: <br /><input type='text' name='fieldB[0]' class='email'/><br /><br />
and in your PHP you will receive them as
[fieldA] => Array (
[0] =>
[1] =>
[2] =>
)
[fieldB] => Array (
[0] =>
[1] =>
[2] =>
)
you can convert them as you want
$newArray = array();
for($i=0; $i<count($_POST['fieldA']); $i++){
$newArray[$i]['fieldA'] = $_POST['fieldA'][$i];
$newArray[$i]['fieldB'] = $_POST['fieldB'][$i];
}
if you're using POST to submit those fields in your form, you can do:
foreach ($_POST as $key => $value) {
$fieldset[$key] => $value;
}

Categories