Insert array into MySQL - php

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

Related

How to change my PHP foreach looped SQL-Insert into a prepared-statement SQL loop?

I have a looped query to do inserts into the MySQL database it works perfectly to do what I need it to do as in it takes all the users inputs in array and then loops them and inputs each into their own row in the database.
$sql_insert_race_history = "INSERT INTO inf_race_history
(`inf_id`,`race_history`, `results`)
VALUES ";
if ($vracehistory != '') {
foreach ($vracehistory as $kay => $value) {
// $sql .= '' | $sql = $sql . '';
$sql_insert_race_history .= "('$inserted_id','{$value}','{$results[$kay]}'),";
}
} else {
$vracehistory = '';
}
// remove last `,` into query;
$sql_insert_race_history = rtrim($sql_insert_race_history, ',');
$countRow = count($_POST['racehist']);
//INSERT INTO THE DATABASE VIA QUERY
$results_racehistory = mysqli_query($vconn, $sql_insert_race_history);
This code works and inserts everything as i need it However i have been told that it is vulnerable to SQL injections attacks, so i have been trying to prevent that by using prepared statements every version I try only so far loops the dont work and it only uploads the very last item in the array
$stmtrace = $conn->prepare("INSERT INTO inf_race_history
(`inf_id`,`race_history`, `results`)
VALUES (?,?,?)");
if ($vracehistory != '') {
foreach ($vracehistory as $kay => $value) {
$stmtrace->bind_param("sss", $inserted_id,$value,$results[$kay]);
}
} else {
$vracehistory = '';
}
// remove last `,` into query;
$sql_insert_race_history = rtrim($stmtrace, ',');
$countRow = count($_POST['racehist']);
//INSERT INTO THE DATABASE VIA QUERY
$stmtrace->execute();
I think it may have something to do with changing it from .= in the foreach loop to just ->bind_param as maybe that is taking away the opportunity to loop it ? tho im not too sure and also how would i echo that i try to echo $stmtrace tho it says method _tostring is not implemented
foreach ($vracehistory as $kay => $value) {
$stmtrace->bind_param("sss", $inserted_id, $value, $results[$kay]);
$stmtrace->execute();
}
You should place execute() inside loop.
bind the params outside the foreach loop, and assign and execute the query when you assign the variables inside the foreach loop. For example
$stmtrace->bind_param("sss", $insertId, $insertValue, $insertKey);
foreach ($vracehistory as $kay => $value) {
$insertId = inserted_id;
$insertValue = $value;
$insertKey = $kay;
$stmtrace->execute();
}
Another note, if you bind an integer, the value of the bind_param method should be 'i'.

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

How can i insert decoded json data using json string in php mysql database

I have this JSON string.
{"Challenges":[{"phoneNumber":"1234567809","name":"Test2 Test2"},{"phoneNumber":"1234567890","name":"Test1 Test1"},{"phoneNumber":"8733806964*","name":"Dennish Desouzs"}],"Message":[{"message":"testchallenge1"}],"Level":[{"level_name":"testchallenge1","level_design":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022200000000000080002000000000000000002000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000200000000000000000002000000000000000000220000000000000000002000000000000000000020000060000000000000200000000000000000002000000000000000000000000000000000000000000000000000000","win_time":3,"play_no":1,"top_user_id":"45","no_challenge":0,"user_id":"45","win_no":1}]}
code is as below:
mysql_select_db("hello") or die('Cannot select Database');
mysql_select_db("hello") or die('Cannot select Database');
$string=$_GET['records'];
$arr=json_decode($string);
$levelArray=array();
foreach ($arr['Level'] as $key=>$value)
{
$levelArray[] = $arr->Level;
print_r($levelArray);
$j = 0 ;
foreach($levelArray as $levelItem)
{
mysql_query("INSERT INTO level(user_id,level_name,no_challenge,level_design,play_no,win_no,win_time,top_user_id)VALUES('".$levelArray[$j]->user_id."','".$levelArray[$j]->level_name.'","'.$levelArray[$j]->no_challenge.'","'.$levelArray[$j]->level_design.'","'.$levelArray[$j]->play_no.'","'.$levelArray[$j]->win_no.'","'.$levelArray[$j]->win_time.'","'.$levelArray[$j]->top_user_id."'");
}
}
?>
Problem is that I cannot insert data in the database by getting the values and at first I have to get all the data from the above string and then level string have to insert level table and challenge record string array should be insert in challenge table so what I should do to get this above string output?
Another answer is , if you're familiar with array you can set
json_decode($string , true);
this will make your data in array structure
so instead of using $arr->level; , you can access it like $arr['level'];
You should change your $arr['Level'] to $arr->Level in your foreach.
$levelArray = array();
foreach ($arr->Level as $key => $value)
{
$levelArray[] = $arr->Level;
$j = 0 ;
foreach($levelArray as $levelItem)
{
$values = $levelItem[$j];
mysql_query("INSERT INTO level(user_id,level_name,no_challenge,level_design,play_no,win_no,win_time,top_user_id) VALUES('".$values->user_id."','".$values->level_name.'","'.$values->no_challenge.'","'.$values->level_design.'","'.$values->play_no.'","'.$values->win_no.'","'.$values->win_time.'","'.$values->top_user_id."'");
}
}

speed up execution by foreach loop in MySql command

I have a PHP foreach statement, looping through a large number of $icons.
For each icon, the DB-column sequence needs to be updated. As follows:
foreach ($icons as $key => $icon) {
// MySql pseudo-code:
UPDATE `tbl_icon2album`
SET `sequence`= $key +1
WHERE iconID= $icon['id']
}
My problem: this becomes very slow for a large number of icons.
My question: Can I speed this up by executing one MySql command that would somehow include the foreach loop?
Much obliged...
You could put all your updates in another table, and update using a single query, e.g.
UPDATE tbl_icon2album, some_other_table
SET sequence = some_other_table.new_key_value
WHERE iconID = some_other_table.icon_reference
How many keys are you updating? Is it the iteration that is slow, or are you doing this thousands of times?
You could use the "in" clause.
ie:
update table set key=key+1 where blah in ('1','2','3');
and you could iterate through the for loop to construct a variable passed to in:
ie:
$iconlist = "";
foreach ($icons as $key => $icon) {
if (!$iconlist) { $iconlist = "($icon" }
else
{ $iconlist .= ",$icon" }
}
if ($iconlist) {
$iconlist .= ")";
$query = "update table set key=key+1 where icon in $iconlist";
}
If you use prepared statements then you can prepare the query once, bind the parameters, and then execute within the loop. This could be faster as it is usually preparing the query that takes up time. For example:
$stmt = $mysqli->prepare("
UPDATE
`tbl_icon2album`
SET
`sequence` = ?
WHERE
`iconID` = ?
");
$stmt->bind_param('ii', $sequence, $icon_id);
foreach ($icons as $key => $icon)
{
$sequence = $key + 1;
$icon_id = $icon['id'];
$stmt->execute();
}

insert array value in database in php

I am working on insert array value in database in php using oops.I call a class on my form page .
<?php
$pid=$_POST['pid'];
$ecode=$_POST['ecode']; {these are my form value)
$rcode=$_POST['rcode'];
$dk=$_POST['dk'];
$qd=$_POST['qd'];
$tp=$_POST['tp'];
$vd=$_POST['vd'];
$valArr=array($pid,$ecode,$rcode,$dk,$qd,$tp,$vd);
if(isset($_POST['form_submit'])){
$requester=new performance();
$requester->addRow($valArr);
}
?>
and class performance code is
class performance extends DataAccess
{
{
$this->obj= new DataAccess;
}
function addRow($valArr)
{
foreach ($valArr as $key=>$value )
$sql= INSERT INTO employee_performance (id, empcode,review_emp_id,
subject_matter,quality_of_delivery, team_player,value_added)
VALUES $value
}
$sql=mysql_query($sql);
}
}
its can't insert all record in database.how I do this?
I want to know how can I insert this data in mysql database using foreach.
Your code had more errors than I was able to count. However, this is a striped down and ugly/quick (hopefully working) edit:
<?php
$pid = $_POST['pid'];
$ecode = $_POST['ecode'];
$rcode = $_POST['rcode'];
$dk = $_POST['dk'];
$qd = $_POST['qd'];
$tp = $_POST['tp'];
$vd = $_POST['vd'];
if(isset($_POST['form_submit']))
{
$query = "INSERT INTO employee_performance (id, empcode,review_emp_id,subject_matter,quality_of_delivery,team_player,value_added) VALUES ('$pid', '$ecode', '$rcode', '$dk', '$qd', '$tp', '$vd')";
$sql = mysql_query($query);
}
?>
Why would you insert it like a array like that? It does not make any sense? And your $sql is both the query and the execution of the query itself.
Dear you are using simple single dimensional array , there is no need for using foreach loop , because it will pick one value at a time, and only one value will be inserted in database , and then you can not insert value in same row.
just do this ...
if(isset($_POST['form_submit'])){
$requester=new performance();
$requester->addRow($_POST); // $_POST is itself an associative array
}
class performance extends DataAccess
{
{
$this->obj= new DataAccess;
}
function addRow($valArr)
{
extract($valArr);
$sql= INSERT INTO employee_performance (id, empcode,review_emp_id, subject_matter,quality_of_delivery, team_player,value_added)
VALUES('$pid' , '$ecode'...'$vd');
$sql=mysql_query($sql);
}
}
write like this
function addRow($valArr)
{
$values = implode(',',array_values($valArr));
$sql= "INSERT INTO employee_performance (id, empcode, review_emp_id, subject_matter, quality_of_delivery, team_player,value_added) VALUES($values)";
$sql=mysql_query($sql);
}

Categories