PHP $_SESSION ARRAY INTO MYSQL - php

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],
));
}

Related

How to insert array data to mysql table

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!

Associative array from form inputs

I'm building a calculator for a mmo guild. At this moment I'm looking for a way to make data more easy to access for calcules.
Basically, I have a form with 5 text fields (just for test, there will be a lot more), and a select list (for choose the proper equation).
Example code:
<input type="text" id="strength" name="strength" value="0">
<input type="text" id="dexterity" name="dexterity" value="0">
<select name="equation" id="equation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
So this form will be procesed through a php file.
<form action="file.php" method="post">
//inputs here
<input type="submit" value="calculate">
</form>
At this moment I'm receiving all data in php file with vars:
$strength = (int)$_POST['strength'];
$dexterity = (int)$_POST['dexterity'];
For start is ok, but when my script is complete there will be more than 20 fields... so I wanna store all data in an array, something like this:
$strength = array(
'fuerza' => 125,
'dexterity ' => 125,
//and more fields...
);
And use this data in various different functions for equations:
function equation1()
{
$damage = $stats['dexterity'] + $stats['strength'];
}
I have read several posts and tutorials about use name value from inputs for create an array somethin like this: name="name[]". But doesn't work for me how I want. This calculator will receive just 1 value for each "stat", and I need have all these values in an array so I can access them from different fuctions in my script.
Please ask me if my question is not clear, and sorry if my english is bad.
EDIT AFTER SOLVE
I let here my code after solve:
.html example:
<input type="text" id="strength" name="stats[strength]" value="0">
<input type="text" id="dexterity" name="stats[dexterity]" value="0">
<select name="operation" id="operation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
.php example:
function critOp($stat)
{
$result = $stat * 0.00725;
return $result;
}
switch($_POST['operation']){
case 'damage' :
$critical = critOp($_POST["stats"]["dexterity"]);
break;
//more case...
You can use brackets in the name field to direct PHP to stick them in an array. If you use [] it will form a numerical array, but you can specify an associative key in the brackets like [dexterity]
<input type="text" id="dexterity" name="strength[dexterity]" value="125">
<input type="text" id="fuerza" name="strength[fuerza]" value="125">
This will result in
$_POST['strength'] = array(
'dexterity' => 125,
'fuerza ' => 125,
);
Bonus points
You can continue to enforce integer values by using array_map:
$_POST['strength'] = array_map('intval', $_POST['strength']);
This will make sure all values are integers.

PHP Session Array Duplicating

I'm trying to set a session array with some pre-defined values, which the user can then add to using a simple html form. My problem is that on the page where the array is set, any refresh or revisit of the page just duplicates the pre-defined values within the array. Not only that, but it also overwrites the value coming from the form each time at the end.
So in this basic example, I have a list of animals and a user can add another animal to the list. But this outputs the pre-defined animals again each time i.e. if I submit the form twice (e.g. adding chicken and then dog) I get the output:
Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => pig[5] => cow[6] => sheep[7] => dog)
What I want is:
Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => dog[5])
What am I doing wrong?
index.php
<?php
session_start();
//pre-defined list of animals
$_SESSION['animals'][] = 'pig';
$_SESSION['animals'][] = 'cow';
$_SESSION['animals'][] = 'sheep';
?>
<!--form to add another animal-->
<form action="go.php" method="POST">
<p><input type="text" name="entry1"></p>
<p><input type="submit" name="submit"></p>
</form>
go.php
<?php
session_start();
//add form entry1 to the session array
$_SESSION['animals'][] = $_POST['entry1'];
//print session array
print_r($_SESSION['animals']);
?>
Only initialize the session variable if it's not already set:
if (!isset($_SESSION['animals'])) {
$_SESSION['animals'] = array('pig', 'cow', 'sheep');
}
Check
in_array('YOUR_VALUE',$_SESSION['animals'])
before re inserting it to avoid duplication.
Reference: in_array
I would suggest to not insert data in the session directly, but adding hidden input values like:
<input type=hidden name=extraValue[] value="pig">
<input type=hidden name=extraValue[] value="cow">
etc
In your PHP page, unset the previous session since you want a 'fresh' dataset based on the input, not on the old values.
unset($_SESSION['animals']);
You can access your extra values in $_POST['extraValue']. You then could merge both arrays like
$postValues = array_merge($_POST['extraValue'], $_POST['entry1']);
I havent tested this code yet, but I would use this 'way', rather than setting SESSION values before input.

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";
}

PHP, Submitting a two dimensional table with TextBox to proccess

I am building an application which has a dynamic table, everytime you open the page table`s row and columns changes based on data in database.
Each Row is a vendor company each colomn is a Item Title. All these vendors upply the same item, So this table has a textbox in each contains a TextBox so user can type the value, which represents the amount of fruit they want from that supplier. the following is the example.
So what I need to do now is, after entering these values, I'd like to process them through PHP, and then see 4 different reports at the confirm page, example: write the Company name and under that, what they have to supply for each item, then the next company, so on and so forth to the end.
I don't know if i should create different class for each textbox? or ID them!! SHould I Array them? I am confused.. If any of you guys can help, would be wonderful
Thanks a lot
I would suggest you just name the input elements as an array. something like:
<input type="text" name="fruits[company1][apple]">
<input type="text" name="fruits[company1][berries]">
<input type="text" name="fruits[company1][orange]">
<input type="text" name="fruits[company1][bannana]">
<input type="text" name="fruits[company2][apple]">
<input type="text" name="fruits[company2][berries]">
<input type="text" name="fruits[company2][orange]">
<input type="text" name="fruits[company2][bannana]">
or the same thing with the fruit being the first level and company name being second. It is really the same thing and generally just as easy to use either one. Just depends on how you want to loop over the data once you post the form. You might be better off also using ids for the company name and/or the fruit. Just makes it so, for example, company names with a space are still valid.
Using the above form, you can process the data with something like this:
<?php
foreach($_POST['fruits'] as $company=>$row){
foreach($row as $fruit=>$quantity){
if(!is_numeric($quantity) || $quantity < 0){
$quantity = 0;
}
echo "You selected {$quantity} {$fruit} from {$company}";
}
}
I would try creating a multi dim array with the ID of the item as the first dimension. Like this:
<input type="textbox" name="textbox[<?php echo $row['item_id']; ?>]["apple"]" value="<?php echo $row['apple']; ?>" />
Then, in your processing script:
foreach ($_POST['textbox'] as $row)
{
foreach ($row as $key => $val)
{
$q = "update `items` set `apple` = {$val['apple']} where `item_id` = {$key}";
mysql_query($q);
}
}

Categories