how to insert the multiple array rows in the database? - php

i am working on dynamic array i need to insert these array in the database.when i insert dynamic array into the database instead of inserting all rows it only inserting one row in the database.
below is the array that contain result
$asma[]=GA::select($ga->population,'total',3);
below is code for inserting multiple array in database table ga
<?php
//code not tested check it
//Logic is changed instead of for looping many times
$data = array();
$j = 0;
foreach($asma as $key => $value)
{
$i = 0;
foreach ( $value as $ind => $hObject )
{
if($i==0)
{
$data[$j]['fe'] = mysql_escape_string($hObject->Voltage);
}else{
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Voltage);
}
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Duration);
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Number);
$i++;
}
$j++;
}// endforeach
//multiple array
foreach($data as $array)
{
//unique array
//$array3 = array_merge($Voltage,$Duration,$Number);
$fields = implode(',',array_keys($array));
//if you want append any new field append it
$fields .= ','.'timestamp,username';
$vals = "'".implode("','",array_values($array))."'";
//if you want append any new values append it
$vals .= ",'".time()."','".$login_session."'";
$q = "INSERT INTO ga (".$fields.") VALUES(".$vals.")";
$result = mysql_query($q);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
}
whenever user enter 3 then after computation result will store in array asma after store result will store in table ga that should be three rows but only one row insert in the table and display instead of three same in case the user enter any value in the text box.

I'm not sure what you mean, i think is an insert statement like this:
INSERT INTO `ga` (`field1`, `field2`, `field3`, `etc`)
VALUES (value11, value21, value31, more_values1),
(value12, value22, value32, more_values2),
(value13, value23, value33, more_values3)
So you should use your foreach cycle to create the values statement.
$sql = "INSERT INTO `ga` (`voltage`, `duration`, `number`, `timestamp`, `username`) VALUES ";
$values = "";
foreach ($asma as $row) {
$values .= ($values != "" ? "," : "") . "(" .
"'" . $row['voltage'] . "', " .
"'" . $row['voltage'] . "', " .
"'" . $row['number'] . "', " .
"'" . time() . "', " .
"'" . $login_session . "'" .
"),";
}
$sql .= substr($values, 0, -1) . ";";

Related

Inserting data into a database with an array

I don't know why the query is not working, might be a slight error that I have missed. I'm try to insert data into a table column depending if it is a match or not. I know data is in my array but I suspect it the query I'm writing out that is giving me an error.
Here is my code:
$querytwo = 'INSERT INTO `' . $tablename . '` ' . ' (`' . $match_player_in_game . '`) ' . 'VALUES' . '(' . 'yes' . ')';
foreach ($player_fromsite as $match_player_in_game) {
for ($a = 0; $a < 11; $a++) {
if ($match_player_in_game == $home_players[$a]) {
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
} else {
}
}
}
The message is returning 'Undefined variable: match_player_in_game'.
you need to put your $querytwo inside the for() loop, then it will work for you
It should be
foreach ($player_fromsite as $match_player_in_game) {
$querytwo = 'INSERT INTO `' . $tablename . '` ' . ' (`' . $match_player_in_game . '`) ' . 'VALUES' . '(' . 'yes' . ')';
for ($a = 0; $a < 11; $a++) {
if ($match_player_in_game == $home_players[$a]) {
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
} else {
}
}
}

How to write query for a php array?

I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
if (isset($this->request->post[$index])) {
$this->data[$index] = $this->request->post[$index];
} else {
$this->data[$index] = NULL;
}
}
Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
//this is the one I am trying to write, and this one works,
//but I'd have to add every single checkbox/radio name to the
//query, and I have 30!
$this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
(isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
"', store_sft = '" .
(isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
"'");
//Ends Here
$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
(int)$this->config->get('config_store_id') . "', firstname = '" .
$this->db->escape($data['firstname']) . "', lastname = '" .
$this->db->escape($data['lastname']) . "', email = '" .
$this->db->escape($data['email']) . "', telephone = '" .
$this->db->escape($data['telephone']) . "', fax = '" .
$this->db->escape($data['fax']) . "', password = '" .
$this->db->escape(md5($data['password'])) . "', newsletter = '" .
(isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
"', customer_group_id = '" .
(int)$this->config->get('config_customer_group_id') .
"', status = '1', date_added = NOW()");
Thanks a lot for any insight you can provide.
the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
$keys =""; $values = "";
foreach($table as $k=>$v)
{
$keys.=($keys != "" ? ",":"").$k:
$values .=($values != "" ? "," :"")."'".$v."'";
}
$this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}
The array has to be structured like this:
array("db_attribute1"=>"value1","db_attribute2"=>"value2");
Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
if (isset($this->request->post[$index]))
{
$this->data[$index] = $this->request->post[$index];
$values[] = $this->db->escape($this->request->post[$index]);
}
else
{
$this->data[$index] = NULL;
$values[] = "''";
}
}
$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");

trouble trying to save in multiple rows in the table in php + mysql

hi am having this trouble trying to save in multiple rows in the table "notification" with a for of customers table ids but it only save me one row this is my code:
$customers = tep_get_customers();
$count = 0;
for ($i=0, $n=sizeof($customers); $i<$n; $i++) {
$count ++;
$insert_str_cony .= $customers[$i]['id'];
$split_customers_id = explode("||", $insert_str_cony.'||', -1);
$values .= "('','" . tep_db_input('1') . "', now(), '" . tep_db_input($products_id) . "', '" . tep_db_input($split_customers_id[$count]) . "'),";
$db_values = substr_replace($values, '', -1, 1);
}
if ($action == 'insert_product') {
tep_db_query("insert into notifications (notify_id, prod_notify, notify_added, prod_id, customers_id) values ". $db_values);
} elseif ($action == 'update_product') {
tep_db_query("update notifications set prod_notify = '" . tep_db_input('1mod') . "', notify_last_mod = now(), prod_id = '" . $HTTP_GET_VARS['pID'] . "', customers_id = '" . tep_db_input($customers['customers_id']) . "'");
}
and this is the function tep_get_customers();
function tep_get_customers() {
$customers_query = tep_db_query("select distinct customers_id from " . TABLE_CUSTOMERS . "");
while ($customers = tep_db_fetch_array($customers_query)) {
$customers_array[] = array('id' => '||'.$customers['customers_id']);
}
return $customers_array;
}
plase need help!!! thanks!
That is because Insert + values insert one row in the database . (You can use Insert with a SELECT query to insert multiple rows using Insert command but that's not your case as I can see ).
Therefore you should provide a script containing multiple insert commands (an insert command for each customer) in order to insert multiple rows into the database.

Is there more elegant way to implode data to query?

I am going to ask because of this answer.
My code looks like
<?php
$lines = file('file.txt');
$count = count($lines);
$i = 0;
$query = "INSERT INTO table VALUES ";
foreach($lines as $line){
$i++;
if ($count == $i) {
$query .= "('".$line."')";
}
else{
$query .= "('".$line."'),";
}
}
echo $query;
is there more elegant way to do this/function in php?
foreach ( $lines AS $line )
{
$query[] = "($line)";
}
echo "INSERT INTO table VALUES " . implode(",",$query);
is how to do it with implode but i think AlienWebguy's is better
foreach(file('file.txt') as $line){
$query .= "('".$line."'),";
}
echo "INSERT INTO table VALUES " . rtrim($query,',');
$query = 'INSERT INTO table VALUES ';
$query .= "('" . implode("'), ('", $lines) . "')";
UPD:
For 2 fields it could look like (I suppose you use php5+):
$query = 'INSERT INTO table VALUES ';
$lines = array(array(1,2), array(3,4));
$query .= "('" . implode("'), ('", array_map(function($i) { return "'" . implode("', '", $i) . "'"; }, $lines)) . "')";
var_dump($query);
LOAD DATA INFILE is better suited for this specific task: http://dev.mysql.com/doc/refman/5.1/en/load-data.html

how to assign and concat using multiple delimiters in an array?

i apologize if the question is wrong. i am a still a newbie and a learner however i would appreciate if someone correct me if i am somewhere wrong.
here in the Class method i am using for Inserting the data into the database
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES(" . implode(",",$value) . ")";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES(". $value . ")";
}
}
now here i am determining if the $col and $value is an array if yes then process it.
however i have a problem here since the VALUES in the Insert statement needs to be represnted in the single or double quote format it will not process the query and hence print the error
for example the below code would print the error
$query = "INSERT INTO users(username,email) VALUES(test,test#test.com)";
and the correct format will be
$query = "INSERT INTO users(username,email) VALUES('test','test#test.com')";
now in the col value i would like to add the single quotes to every value in the array for example the $value array which is like this.
$value = array('test','test#test.com');
should give back the value
'test','test#test.com'
instead of
test,test#test.com
how do i achieve it?
$query = "INSERT INTO $table ('" . implode("','",$col) . "')
VALUES ('" . implode("','",$value) . "')";
Make sure that neither $col nor $value is empty.
Right code:
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES('" . implode("','",$value) . "')";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES('". $value . "')";
}
}
CHANGE:
VALUES(" . implode(",",$value) . ")
TO
VALUES('" . implode("','",$value) . "')
(Your output:)
VALUES(demo,demo2)
(New Output:)
VALUES('demo','demo2')
you could do this?
$value = array("'test'","'test#test.com'");
You can use array_map() method:
function addQuotes($str)
{
return "'".$str."'";
}
$value = array_map("addQuotes", $value);
or follow a Oswald's answer recommendations.

Categories