I have 3 input that can be added dynamically. So the name of input is array, like:
<input type="text" name="qty1[]">
<input type="text" name="qty2[]">
<input type="text" name="qty3[]">
(Each of these input texts can be generated by javascript)
In my php file, I get them and want to insert to database (my controller in codeigniter):
$address = $this->input->post("qty1");
$LocX = $this->input->post("qty2");
$LocY = $this->input->post("qty3");
In my db part, where I want to use foreach and add to database:
Edit
foreach ($address as $key) {
// I want to add $LocX and $LocY to the table
// LocX and LocY are column names.
$query = $this->db->query("INSERT INTO address (Comp_ID, Value, LocX, LocY)
VALUES(?, ?)", array($Comp_ID, $key ,? ,?));
}
I want to add all of them into foreach as parameter. As I searched it's not possible. What shoud I do? Thanks.
Edit2
The result of arrays, for example for $LocX :
Array
(
[0] => test1
[1] => test2
[2] => test3
)
You can use the index in the foreach to get to the other elements. But you need to carefully check if the index value exists in the other arrays (isset check)
For example:
foreach ($address as $key => $value) {
if(isset($LocX[$key], $LocY[$key]) {
$a_LocX = $LocX[$key]; // This will be the locx of the address
$a_LocY = $LocY[$key]; // This will be the locy of the address
// Change your query to fit the table and fill in the locx and y.
$query = $this->db->query("INSERT INTO address (Comp_ID, Value)
VALUES(?, ?)", array($Comp_ID, $key));
}
You can also use a for loop for this.
$address = $this->input->post("qty1");
$LocX = $this->input->post("qty2");
$LocY = $this->input->post("qty3");
$n=count($address);
for($i=0;$i<$n;$i++){
$a=$address[$i];
$x=$locX[$i];
$y=$locY[$i];
//insert here
}
I will suggest you to use Codeigniter syntax, and this will make your insert work,
foreach($address as $k => $v)
{
$insert = array(
'Comp_ID' => $Comp_ID,
'Value' => $v,
); // insert array
if(in_array($LocX[$k], $LocX)) // existance check
$insert = array_merge($insert, array('LocX' => $LocX[$k]));
if(in_array($LocY[$k], $LocY)) // existance check
$insert = array_merge($insert, array('LocY' => $LocY[$k]));
$this->db->insert('address', $insert); // No need to write full query
}
Related
I have a list of serialized data that I unserialize and store into an array.
$employee_data = unserialize($entry, '63');
Which results in an expected output:
Array ( [0] =>
Array ( [First] => Joe
[Last] => Test
[Birth Date] => 01/01/2011
)
[1] =>
Array ( [First] => Mike
[Last] => Miller
[Birth Date] => 01/01/1980
)
)
Ive been trying, unsuccessfully, to insert these records into a table in MySQL using foreach() or something like:
$employee_array = array();
$k = 1;
for($n=0; $n<count($employee_data); $n++ ){
$employee_array['employee_first_name'.$k] = $employee_data[$n]['First'];
$employee_array['employee_last_name'.$k] = $employee_data[$n]['Last'];
$employee_array['employee_birthdate'.$k] = $employee_data[$n]['Birth Date'];
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'$employee_first_name.$k',
'$employee_last_name.$k',
'$employee_birthdate.$k'
)"
$k++;
};
Each employee in the array needs to be entered into a new row in the table, however the number of employees will vary from 1 to 10+
We've tried
foreach($employee_array as $key => $value)
with the same results.
The actual results we're hoping for is the SQL Statement to be:
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Joe',
'Test',
'01/01/2011');
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Mike',
'Miller',
'01/01/1980');
Keep in mind that your sql statement is not escaped. For example, a name with an apostrophe like "0'neil" will break your sql. I would also familiarise yourself with php's foreach: https://www.php.net/manual/en/control-structures.foreach.php.
I'm not sure exactly what you're trying to accomplish by adding the index to the name and sql value, but I would do something like this:
foreach($employee_data as $key => $value){
// $employee_array is not necessary
$employee_array[$key]['employee_first_name'] = $value['First'];
$employee_array[$key]['employee_last_name'] = $value['Last'];
$employee_array[$key]['employee_birthdate'] = $value['Birth Date'];
// Needs escaping
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'{$value['First']}',
'{$value['Last']}',
'{$value['Birth Date']}'
)";
echo $SQL;
};
The first implementation wont work as your calling a variable rather than the key in your array.
'$employee_first_name.$k',
Should be
$employee_array['employee_first_name'.$k]
You are also creating the SQL statement every iteration of the for loop, so in this implementation only the last employee will save.
Also I don't see the reasoning in doing it that way anyway you may as well just use the employee_data array and the $k variable can also be made redundant.
$SQL = "";
for($n=0; $n<count($employee_data); $n++ ){
$SQL .= "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
) VALUES (";
$SQL .= "'".$employee_data[$n]['First']."',";
$SQL .= "'".$employee_data[$n]['Last']."',";
$SQL .= "'".$employee_data[$n]['Birth Date']."'";
$SQL .= ");";
};
Ive not tested but it should give you an idea.
You will also have issues with the date formatted that way, Your database would likely require the date in yyyy/mm/dd format
Finally I would not recommend inserting values like this, look at the PDO library for placeholders.
I think I understand what you're trying to do here. You are using the = operator, effectively setting $SQL to a new value each time your loop iterates. If you adapt your code, you will be able to append to $SQL variable each time.
//I used this array for testing. Comment this out
$employee_data = array(
0 => array(
"first" => "test",
"last" => "tester",
"birth date" => "01/01/1970"
),
1 => array(
"first" => "bob",
"last" => "david",
"birth date" => "02/02/1972"
),
);
//Start SQL as a blank string
$SQL = "";
//Do your iteration
foreach( $employee_data as $key=>$value ){
$first = $value['first'];
$last = $value['last'];
$birthDate = $value['birth date'];
//append this query to the $SQL variable. Note I use `.=` instead of `=`
$SQL .= "INSERT INTO employee_test(
`employee_first_name`,
`employee_last_name`,
`employee_birthdate`)
VALUES(
'$first',
'$last',
'$birthDate'
);";
}
//output the query
echo $SQL;
There are much easier ways of doing this though. Look into prepared statements :)
got a problem.
I got form like this
<input name="product[sub_name][]">
<input name="product[price][]">
<input name="product[random][]">
<input name="product[just_field][]">
I can add many blocks of this form pressing "add more".
Recieving posta data i do the stuff.
$field = $_POST['product'];
foreach ($field as $key => $values) {
foreach($values as $value) {
$key.' - '.$value;
}
}
I need code to insert multiple rows in database depending on posted rows. Problem is that, i dont know how to get only, for example, "price". Goal is insert all data in database. Hope you guys understand my logic.
Here is print_r output. I can got more possibilities than two
Array (
[sub_name] => Array ( [0] => New car [1] => New bike )
[standart_price] => Array ( [0] => 100 [1] => 300 )
[cupon_price] => Array ( [0] => 50 [1] => 200 )
[max_purchases] => Array ( [0] => 1000 [1] => 100 )
)
You can get a more ordered result if you re-organize the array to contain the index first:
<input name="product[$index][sub_name]">
<input name="product[$index][price]">
<input name="product[$index][random]">
<input name="product[$index][just_field]">
Each time you add a new product change the index with javascript, in that way, when you recieve the data in php you can do something like:
$products = $_POST['product'];
foreach ($products as $product)
{
$sub_name = $product['sub_name'];
$random = $product['random'];
$just_field = $product['just_field'];
$sql = "Your SQL query"
$mysqli->query($sql);
}
Maybe need a little more work changing the html indexes with javascript but your code become more clear.
p.s. That's the general idea, i don't test it.
Try to use
print_r($_POST["product"]);
to output the whole array.
Are you sure the values transmitted by the formular are passed into $_POST ?
Could you please post the output.
Check this out..
<?
//Connect to DB.
$link = mysqli_connect("HOST","USERNAME","PASSWORD","DATABASE") or die("Error " . mysqli_error($link));
//Consider your table structure in MYSQL. Don't depend on this structure.
//CREATE TABLE TBL1(SLNO PRIMARY KEY AUTO_INCREMENT, DETAIL_VALUE VARCHAR(200));
foreach( $_POST['product'] as $key => $value )
{
//Get specific Tag.
if( $key == 'price')
{
//Creating Query to insert.
$query = "insert into TBL1('DETAIL_VALUE') VALUES('".addslashes($value)."')";
$mysqli_query($link, $query) or die;
}
}
?>
For more details on querys or php: Refer PHP.net.
$mysqli = new mysqli("localhost", "root", "password", "db name");
$field = $_POST['product'];
foreach ($field['price'] as $idx => $price)
{
$sub_name = $field['sub_name'][$idx];
$random = $field['random'][$idx];
$just_field = $field['just_field'][$idx];
$sql = "INSERT INTO table (sub_name, random, just_field, price) VALUES ('{$sub_name}','{$random}','{$just_field}','{$price}')";
$mysqli->query($sql);
}
I am super confused and have been searching. But as the title suggests I am trying to enter an array.
My question is how do I get this array to import into the database? As of now with the current script, it only imports the first record and not the rest. Here also, I am able to import other values within the same array this is a JSON call by the way and its already being decoded.
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["damage_given"]["vehicle"])) {
$damage_given[$key] = $output[$key]["stats"]["damage_given"]["vehicle"];
foreach ($damage_given[$key] as $vehicle_name) {
$vehicle_dmg_id = $vehicle_name['id'];
$vehicle_dmg_name = $vehicle_name['name'];
$vehicle_dmg_value = $vehicle_name['value'];
$vehicle_dmg_faction_nc = $vehicle_name['faction']['nc'];
$vehicle_dmg_faction_tr = $vehicle_name['faction']['tr'];
$vehicle_dmg_faction_vs = $vehicle_name['faction']['vs'];
}
}
}
$add_dmg_veh = "INSERT INTO damage_given(character_number, vehicle_id,
vehicle_name, total_value, vehicle_faction_nc, vehicle_faction_tr,
vehicle_faction_vs) VALUES ('$character_id[$key]', '$vehicle_dmg_id',
'$vehicle_dmg_name','$vehicle_dmg_value', '$vehicle_dmg_faction_nc',
'$vehicle_dmg_faction_tr','$vehicle_dmg_faction_vs')";
Although it is not recommended to store an array in a database, you could serialize() your array to store it in a database. Basically, PHP will convert the array into a specially crafted string, which it can later interpret.
Serialize to store it in the database, and unserialize it to work with it when you pull it out of the database
Note: I say serialization is not recommended, because your database is then not in First Normal Form, specifically because you are storing non-atomic values inside of a particular entry in the database. For this case, I would recommend creating a separate table which can store these values individually, and link the two tables together with a foreign key.
You should be looking about PDO_MySQL and your insert string is outside the loop and should be execute inside it.
You have to iterate through the array and insert every field of the array by it's own.
foreach($array as $value) {
// execute your insert statement here with $value
}
First of all you can't insert array in MySQL as you are doing .. Do as with iterating..
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["damage_given"]["vehicle"])) {
$damage_given[$key] = $output[$key]["stats"]["damage_given"]["vehicle"];
foreach ($damage_given[$key] as $vehicle_name) {
$vehicle_dmg_id = $vehicle_name['id'];
$vehicle_dmg_name = $vehicle_name['name'];
$vehicle_dmg_value = $vehicle_name['value'];
$vehicle_dmg_faction_nc = $vehicle_name['faction']['nc'];
$vehicle_dmg_faction_tr = $vehicle_name['faction']['tr'];
$vehicle_dmg_faction_vs = $vehicle_name['faction']['vs'];
// if you wants to use insert query then do here.
$add_dmg_veh = "INSERT INTO damage_given(character_number, vehicle_id,
vehicle_name, total_value, vehicle_faction_nc, vehicle_faction_tr,
vehicle_faction_vs) VALUES ('$character_id[$key]', '$vehicle_dmg_id',
'$vehicle_dmg_name', '$vehicle_dmg_value', '$vehicle_dmg_faction_nc',
'$vehicle_dmg_faction_tr', '$vehicle_dmg_faction_vs')";
}
}
}
try building your insert data in an array and then implode the results into a single query:
<?php
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["damage_given"]["vehicle"])) {
$damage_given[$key] = $output[$key]["stats"]["damage_given"]["vehicle"];
foreach ($damage_given[$key] as $vehicle_name) {
$sql[] = "
(
".$vehicle_name['id'].",
".$vehicle_name['name'].",
".$vehicle_name['value'].",
".$vehicle_name['faction']['nc'].",
".$vehicle_name['faction']['tr'].",
".$vehicle_name['faction']['vs']."
)";
}
}
}
$query = "
INSERT INTO damage_given
(
character_number,
vehicle_id,
vehicle_name,
total_value,
vehicle_faction_nc,
vehicle_faction_tr,
vehicle_faction_vs
)
VALUES
".implode(",",$sql)."
";
?>
here is what I got to fix the problem!
$stmt = $dbh->prepare(
"INSERT INTO kills_vehicle (character_number, veh_id, veh_name, veh_total, veh_faction_nc, veh_faction_tr, veh_faction_vs)
VALUES(:char_id, :id, :vehname, :total_value, :faction_nc, :faction_tr, :faction_vs)");
foreach ($output as $key => $value) {
if (isset($output[$key]["stats"]["play_time"]["vehicle"])) {
$character_id[$key] = $output[$key]["id"];
$score_hit_count[$key] = $output[$key]["stats"]["kills"]["vehicle"];
foreach ($score_hit_count[$key] as $row) {
$stmt->bindValue(':char_id', $character_id[$key]);
$stmt->bindValue(':id', $row[id]);
$stmt->bindValue(':vehname', $row[name]);
$stmt->bindValue(':total_value', $row[value]);
$stmt->bindValue(':faction_nc', $row[faction][nc]);
$stmt->bindValue(':faction_tr', $row[faction][tr]);
$stmt->bindValue(':faction_vs', $row[faction][vs]);
$stmt->execute();
}
}
}
I have a form with over 100 dynamically named fields, that post to a php file, I want to take all the fields that are posted to the php file which is currently:
Array ( [option_page] => plugin_options
[action] => update
[_wpnonce] => a51bfc281a
[_wp_http_referer] =>/wp-admin/options-general.php page=plug.php
[13939069] =>
[2171] =>
[3600645] =>
[2168] =>
[13937024] =>
[submit] => Save Changes
[__qca] => P0-1887521465-1334258158937
[s_vi] => )
From this I want to insert the data into a mysql table in the format:
id | option_name | value
--------------------------------------------
autonum | post data key | post data value
But the issue is I am only intrested in the post data value after: [_wp_http_referer]
but before [submit] so these can be used as reference points.
The part I am stuggling with is:
how would I get only that part of the post data dynamically?
How would I get the required array keys and insert it into the
table dynamically?
Many thanks!
You mat try this
$start = array_search("_wp_http_referer",array_keys($_POST))+1;
$end = array_search("submit",array_keys($_POST))-1;
$newArr=array_slice($_POST, $start, $end);
foreach($newArr as $k=>$v)
{
// $k is the key name and $v is the value of that key
//echo $k."=".$v."<br />";
$val=mysql_real_escape_string($v);
$sql="INSERT INTO table_name VALUES (null, ".$k.", ".$val.")";
mysql_query($sql);
}
$counter = 0;
foreach($_POST as $key=>$value)
{
if($key == "_wp_http_referer")
{
$counter = 1;
}
if($counter == "1")
{
if($key != "submit")
{
mysql_query("INSERT INTO table_name(id, option_name, value) VALUES ('','".mysql_real_escape_string($key)."','".mysql_real_escape_string($value)."')");
}
}
}
The keys you want seem to be all numeric, so you could only store those. Like others before me, I also suggest using PDO for added security and convenience.
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
foreach($_POST as $key => $value) {
if(preg_match("/^[0-9]+$/", $key) {
$stmt = $dbh->prepare('INSERT INTO table_name(option_name, value) VALUES (?, ?)');
$stmt->execute(array($key, $value));
}
}
You could do something like this:
$discard_array = array('option_page', 'action', '_wpnonce', '_wp_http_referer', 'submit', '__qca', 's_vi');
$good_array = array();
foreach ($_POST as $key => $val)
{
if (!in_array($key, $discard_array)) $good_array[$key] = $val;
}
// use $good_array to insert your data into db
print_r($good_array);
Or, if all of the "good" values have always numeric keys, here's a simplified variation:
$good_array = array();
foreach ($_POST as $key => $val)
{
if (is_numeric($key)) $good_array[$key] = $val;
}
print_r($good_array);
Hope that helps.
I use of codeigniter. how can insert several value (array) <input name="ok[]"> in database and get they of database. (what is the best way?)
type rows in database is "VARCHAR" and "utf-8".
<input type="text" name="ok[]">
Values: (This is just one example of what I want)
ok[1] => hi, how are you?, 5426, assd, 54568
ok[2] => what, your name?, 548568a, 684a45ade
ok[3] => asdwhasdat, fine, 85as454se, 4e748sd
ok[3] => 85as454se, George, asdwhasdat, 4e748sd
Etc. ....
Now after it, i want inputs ok[1], ok[2], ok[3] together insert in a row (column) on database.
NEXT:
I want get (the second part) they of database and each they in foreach as:
how are you? fine your name? George
how is it?
$inserts = array();
foreach ($_REQUEST['ok'] as $key => $val)
{
$parts = explode(',', $val);
$inserts[] = "('" . mysql_real_escape_string($parts[1]) . "')";
}
$inserts = implode(',', $inserts);
$sql = "INSERT INTO yourtable (fieldname) VALUES $inserts;";
$result = mysql_query($sql) or die(mysql_error());