insert array value in database in php - 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);
}

Related

How to insert value of dynamic form fields in database iusing code in php

I have a problem in trying to store database values in their respective rows inside the database using dynamic form fields. I have provided here the screenshots of my codes and outputs.
This is my script in adding dynamic form fields in which the form is located in a separate file named load_work_experience_form.php
This is the html code for the form I have appended in the my script to add a dynamic form fields
This is the look of my dynamic form fields
This happens to be the wrong output inside the database in which data values do not store in their proper record. I am attempting to insert 2 records of work experience but it seems that it has created 4 records.
The source code for adding into the database is supplied below. Kindly help me in fixing this problem. Thanks. More power:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
foreach ( $_POST['employer'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (employer) VALUES ('$values')");
}}
if (isset($_POST['job_position'])) {
foreach ( $_POST['job_position'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (job_position) VALUES ('$values')");
}}
//some more codes here for Work From and To. This website does not accept alot of codes. But the codes here are just like the ones at the top.
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
In the case that you have every time the same fields with dynamic rows:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
for ($i = 0, $nCount = count($_POST['employer']); $i < $nCount; $i++) {
$employer = mysql_real_escape_string($_POST['employer'][$i]);
$job_position = mysql_real_escape_string($_POST['job_position'][$i]);
$query = mysql_query('INSERT INTO tbl_work_exp (´employer´, ´job_position´) VALUES (´' . $employer . '´, ´' . $job_position . '´)');
}
}
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
You must add there the other fields also...
The problem of your logic is that you do for every field a insert but you need only one insert for one row.
And please don't use mysql library in php, it is better to use mysqli
Your problem is that you pass each value separately. I strongly suggest to change your HTML markup to group each value, but that's not the goal here. As for your current problem, this is a quick solution that can help you through. Picking up from your current code:
<?php
if (isset($_POST['update_profile'])) {
$profileFields = array('employer', 'job_position');
$profiles = array();
foreach ($profileFields as $field)
{
if (isset($_POST[$field])) {
foreach ($_POST[$field] as $key => $value) {
if (!isset($profiles[$key])) {
$profiles[$key] = array();
}
$profiles[$key][$field] = mysql_real_escape_string($value);
}
}
}
foreach ($profiles as $profile) {
$tableCols = implode(",", array_keys($profile));
$profileValues = implode("','", array_values($profile));
$insertQuery = "INSERT INTO tbl_work_exp ({$tableCols}) VALUES ('{$profileValues}')";
}
}
?>
Give or take a few tweaks or special treatment for each field. This is very generic code just to give you a guide.
Hope this helps
<?php
if(isset($_POST['Button_name'])){
for($i=0; $i<count($_POST['employer_name']); $i++){
$query="INSERT INTO table_name(employer_name,employer_age) VALUES ('".$_POST['employer_name']."','".$_POST['employer_age']."')";
$result=mysql_query($query);}}
<?php
$count_post_value = $_POST['first_name'] //this is value of text box //
for($i=0; $i<$count_post_value; $i++)
{
if(trim($_POST["first_name"][$i] && $_POST["last_name"] && $_POST["remarks"]!= ''))
{
$sql = mysql_query("INSERT INTO Table_name(first_name,last_name) VALUES('".$_POST["first_name"][$i]."','".$_POST["last_name"][$i]."')");
if($sql)
{
echo "<script>alert('Inserted Successfully');</script>";
}
else
{
echo "<script>alert('ERROR');</script>";
}
}
}
?>

updating each row with previous values plus current values

sorry for the complicated heading.i am doing learning php and got stuck.i have a database table table_name
id(primary key) name ip
1 a 192.168.0.1,192.168.0.5,171.87.65 //separated by comma's
2 b 192.168.0.1,175.172.2.6,164.77.42
now i want to add an array of values ip[0] and ip[1] coming from a two different text-area to the end of the ip's of each name and just updating the ip column of each row.so it will just append new values with previous one.
name a<textarea rows="4" cols="40" name="ip[]"></textarea>
name b<textarea rows="4" cols="40" name="ip[]"></textarea>
<input type="submit" />
this is how its inserted
if(isset($_POST['submit'])) {
$ip_details = $_POST['ip'];
$values = array(
array('id' => '"1"', 'name' => '"a"', ip => '"'.$ip_details[0].'"'),
array('id' => '"2"','name' => '"b"', ip => '"'.$ip_details[1].'"'),
);
$columns = implode(', ', array_keys($values[0]));
foreach($values as $value) {
$value = implode(', ', $value);
$statement = "INSERT INTO `center_listt` (id,name,ip) VALUES ($value)";
$res=mysql_query($statement);
echo "success";
}
}
i need to update each rows of namea and b with new values coming from text-area with previous values.
i am thinking of array_push after fetching ip from table in while loop but could not really do it.warning: array_push expects parameter 1 to be array integer given its because the $row['ip'] fetched in while loop is not valid array which array_push expects.
and it will only add new values in different new rows each time which i don't want.can someone please help what to do.
<?php
if(isset($_POST['submit'])) {
//print_r($ips); die;
$i = 0;
foreach($_POST['ip_details'] as $ipaddr) {
$ips[$i] = $ips[$i].$ipaddr;
$i++;
}
$r = 1;
foreach($ips as $ip){
//echo "UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'"; die;
if(mysql_query("UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'")) echo "IP Address Updated <br />";
else echo 'error occurred';
$r++;
}
}
$sql="select * from center_listt";
$res=mysql_query($sql);
if(!$res) {
die('could not connect'.mysql_error());
}
while($row=mysql_fetch_assoc($res))
{
echo $row['ipdetails']; }
?>
its a bad practise to insert form values from array.you can fetch it from db bcoz if in future you want to add new form values you need to rewrite again with array values while fetching from db will only need you to insert new values in db.
my query will add ip's in your specific column in a single row only updating the ip with new values.
You could do this:
$values = array(...); // WARNING: escape `$ip_details` here!!
$to_insert = array();
foreach($values as $row) {
$to_insert[] = "(".implode(", ",$row).")";
}
$statement = "insert into `center_listt` (`id`, `name`, `ip`)
values ".implode(", ",$to_insert)."
ON DUPLICATE KEY UPDATE `ip`=concat(`ip`,',',values(`ip`))
";
mysql_query($statement);
This will perform a multi-insert (far more efficient than individual queries), and when you try to insert the same ID twice it will instead concatenate the values.
It should be noted that this is bad database design, though :p

Yii insert series of data

So, I got a series of data that I need to insert into a table. Right now I am using a for loop to iterate through each entry and save the model one by one. But that doesn't seem like a good way to do it, moreover using transaction would be an issue. What's a better way to do it to improve performance and also so I can use transaction.Here's the code I am currently using.
foreach ($sheetData as $data)
{
$newRecord = new Main;
$newRecord->id = $data['A'];
$newRecord->name = $data['B'];
$newRecord->unit = $data['C'];
$newRecord->save();
}
If you can skip validation, you can generate a simple sql insert and execute it once. like:
$count = 0;
$sql = '';
foreach ($sheetData as $data)
{
if(!$count)
$sql .= 'INSERT INTO tbl_main (id ,name ,unit) Values ('.$data['A'].','$data['B']','$data['C']') ';
else
$sql .= ' , ('.$data['A'].','$data['B']','$data['C']')';
$count++;
}
Yii::app()->db->createCommand($sql)->execute();

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

insert an array into mysql database

I have the following array which I would like to insert into mysql database.
Item[0] = Soccer
Item[1] = Rugby
Item[2] = Football
Item[3] = Netball
Item[4] = Hockey
I am using the following function to insert into the database, located in functions.php:
//Capture items
function item($register_data)
{
array_walk($register_data,'array_clean');
$fields = ' '.implode(',',array_keys($register_data)).' ';
$data = '\''.implode('\',\'',$register_data).'\'';
//Insert user Data into the database
$query = "INSERT INTO items ($fields) VALUES ($data)";
mysql_query($query);
}
Now this is how I insert:
for($i =0;$i<4;$i++)
{
$item = array($i = item[i]);
}
//Call the function to insert into the database
item($item);
This method doesn't seem to work. Please assist
PHP has a built in serialize & deserialize functions (http://php.net/manual/en/function.serialize.php) for that. You can pass any object or array to it, and it will return a serialized string, which you can store in a single field in the database.
Since your items table has two columns, one of which is id (auto increment) you're going to want to skip over it and only specify the second column ItemName. This is described in the mysql documentation on this page.
Lets say you want to insert 5 sports in this table:
$sports[0] = "Soccer";
$sports[1] = "Rugby";
$sports[2] = "Football";
$sports[3] = "Netball";
$sports[4] = "Hockey";
You'll want the query to look something along these lines:
INSERT INTO items (ItemName) VALUES ('Soccer'), ('Rugby'), ('Football'), ('Netball'), ('Hockey');
The code would look something like this:
function insert($insert_data)
{
$fields = implode(', ', $insert_data);
$data = '(\''.implode('\'), (\'', $insert_data).'\')';
//mysql_query("INSERT INTO items (ItemName) VALUES $data;");
echo "INSERT INTO items (ItemName) VALUES $data;";
}
$sports = array();
$sports[0] = "Soccer";
$sports[1] = "Rugby";
$sports[2] = "Football";
$sports[3] = "Netball";
$sports[4] = "Hockey";
insert($sports);
You may also want to sanitize the strings first and take a look at mysqli since mysql is pretty outdated.

Categories