Insert _POST data from a form into MYSQL dynamically - php

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.

Related

php: Use different arrays in foreach loop

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
}

How will PHP Web Service read JSON

My JSON is
{"users":[{"UserName":"user1","FullName":"Name One"},
{"UserName":"user2","FullName":"Name Two"}]}
My PHP is
<?php
include '../inc/connect.php';
include '../inc/class/mysql.class.php';
$data = file_get_contents('php://input');
$array = json_decode($data, true);
$rows = array();
foreach ($array['users'] as $parentvalue)
foreach ($parentvalue as $key => $value)
$rows[] = "('" . $value . "', '" . $value . "')";
$values = implode(",", $rows);
try
{
$count = mysql_query("INSERT INTO users (UserName, FullName) VALUES $values") or die(mysql_error());
}
catch(PDOException $e) { //later
}
?>
The structure of the array is
Array
(
[users] => Array
(
[0] => Array
(
[FullName] => Name One
[UserName] => user1
)
[1] => Array
(
[FullName] => Name Two
[UserName] => user2
)
)
)
Instead of inserting the data:
**user1 - Name One
**user2 - Name Two
to MySQL...
It inserts
**user1 - user1
**Name One - Name One
**user2 - user2
**Name Two - Name Two
Please help!
/********EDIT (prev answer below)*********/
Here is my new code. I have modified your JSON structure based on your comments.
//added addresses as an example (no the postcodes aren't real :P)
$json='{
"users":[
{"UserName":"user1","FullName":"Name One"},
{"UserName":"user2","FullName":"Name 2"}
],
"addresses":[
{"HouseNumber":"1","PostCode":"LS1 1PS"},
{"HouseNumber": "23", "PostCode": "LS1 2PS"}
]
}';
$data=json_decode($json);
//loop over each 'table'
foreach ($data as $table_name=>$data_array){
$table_name=mysql_real_escape_string($table_name);
//loop over each 'row' in table
foreach($data_array as $current_obj){
$current_sql="INSERT INTO ".$table_name." SET ";
$row=array();
//loop through 'row' data and get 'column' name and value.
foreach($current_obj as $name=>$value){
$row[]='`'.mysql_real_escape_string($name).'` = "'.mysql_real_escape_string($value).'"';
}
$current_sql.=implode(',',$row);
mysql_query($current_sql);
unset($current_sql,$name,$value);
}
}
Now, while this code will do what you asked I probably wouldn't use it myself. I would have different endpoints in your web service for the different tables (and use GET,POST,PUT etc http requests to determine action - see REST web services) - Although its more work, clearly defined actions make debugging easier and your application more secure (as you'll know exactly what its doing and what to).
As for authentication, thats a whole issue on its own that I can't really go into here. Please don't think I mean this in an offensive way, but as you're new to development I would advise spending more time learning before trying to make anything production ready - to protect you and your customers more than anything.
Anyway, I hope this helps.
Regards
Ryan
/******* OLD ANSWER - LEFT HERE FOR CLARITY****************/
I believe you don't need the second loop. This is what I have (modify to suit your needs):
$json='{"users":[{"UserName":"user1","FullName":"Name One"},{"UserName":"user2","FullName":"Name 2"}]}';
$data = json_decode($json);
$rows = array();
foreach ($data->users as $user_obj){
$rows[]='("'.$user_obj->UserName.'","'.$user_obj->FullName.'")';
}
$values = implode(",", $rows);
echo "INSERT INTO users (UserName, FullName) VALUES ".$values;
Also, I would advise that you make use of prepared statements or at the very least mysql_real_escape_string.
Hope this helps,
Ryan :)
(P.s I stopped json_decode converting objects to arrays as it feel it is helpful to know when a data structure is supposed to be iterable and when it is not - feel free to change it back if you like.)
I slightly improved your code, for readability's sake. The very first thing you'd realize is that you're dealing with two problems here : one is parsing JSON response, and the second one is inserting records into a table:
$json = '{"users":[{"UserName":"user1","FullName":"Name One"},
{"UserName":"user2","FullName":"Name Two"}]}';
$values = buildArray($json);
insertValues($values);
function buildArray($json) {
$result = array();
$array = array_values(json_decode($json, true));
foreach ($array as $index => $nestedArray) {
foreach($nestedArray as $index => $value) {
$result[] = $value;
}
}
return $result;
}
function insertValues(array $values) {
foreach($values as $index => $array) {
$query = sprintf("INSERT INTO `users` (`UserName`, `FullName`) VALUES ('%s', '%s')",
mysql_real_escape_string($array['UserName']),
mysql_real_escape_string($array['FullName']),
);
if (!mysql_unbuffered_query($query)) {
return false;
}
}
return true;
}

Create Array and print it into TXT file

UPDATE:
I get array values from $_POST['changed'].
The array structure looks like this:
Array
(
[0] => Array
(
[recid] => 1
[nachname] => Müller7777
)
[1] => Array
(
[recid] => 3
[vorname] => Maria123
)
)
I get on line #3 this error: Fatal error: Function name must be a string
$uarr=array();
foreach ($_POST['changed'] as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
$uarr[$y][]="$k='$v'";
}
foreach ($uarr as $k=>$v) {
$sql = "";
$sql .="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
file_put_contents('filename2.txt', $sql);
Before I do the final database UPDATE I want to check if the created array does its job. Thats why I want to write the $sql variable first into a txt-file.
------------------------------------------------
SOLUTION:
checking if $_POST['changed'] == null is the final answer for this question.
if ($_POST['changed'] == null) {
} else {
$uarr=array();
$b = $_POST['changed'];
foreach ($b as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
// $x contains the `recid` key
// $y ... value
$uarr[$y][]="$k='$v'";
}
foreach ($uarr as $k=>$v) {
$sql = "";
$sql .="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
file_put_contents('filename2.txt', $sql);
}
Before you run the individual UPDATE statements - yes, for each recid value you should send one statement - you could first collect all the affected values for each recid in an associative array like
$uarr=array();
foreach ($_POST['changed'] as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
// $x contains the `recid` key
// $y ... value
$uarr[$y][]="$k='$v'";
}
and then do another loop like
foreach ($uarr as $k=>$v) {
$sql="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
But, of course, this will only work correctly if the $_POST('changed') array adheres to the described format and order. And, finally, so far there is nothing in this code to protect you from SQL injection.
Try to do it like this:
$BigArray = $_POST['changed'];
$LengthOfArray = sizeof($BigArray);
for ($i = 0; $i < $LengthOfArray ; $i++) {
$SubArray = $BigArray[$i];
// Call the update/insert here
// $SubArray['recid'] is the ID
// $SubArray['vorname'] is the name
}

foreach multidimensional Array and insert database

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

Insert array into MySQL

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();
}
}
}

Categories