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
Related
I have a mySQL table with the fields:
preview_url
large_url
And I have an object that I submit with the following structure:
var $urls = {largeImg:[],preview:[]}
$urls.largeImg values have to be inserted into 'large_url' and
$urls.preview_url values have to be inserted into 'preview_url'
$urls.largeImg[0] has to go in the same mysql table row as $urls.preview[0],
$urls.largeImg[1] into the same row as $urls.preview[1] and so on.
my php:
$urls = $_POST['urls'];
function cache_urls($urls){
global $db;
foreach($urls as $url){
$sql = "INSERT INTO cache ";
$sql .= "(preview_url, large_url) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $url['preview']) . "', ";
$sql .= "'" . db_escape($db, $url['largeImg']) . "'";
$sql .= ");";
$result = mysqli_query($db, $sql);
}
And then I also tried this:
foreach($urls as $url){
foreach($url as $key => $value){
$sql = "INSERT INTO cache ";
$sql .= "(preview_url, large_url) ";
$sql .= "VALUES (";
if($key==="preview"){
$sql .= "'" . db_escape($db, $value) . "', ";
}
if($key==="largeImg"){
$sql .= "'" . db_escape($db, $value) . "'";
}
$sql .= ");";
$result = mysqli_query($db, $sql);
}
}
So I assume the SQL bit must be wrong but I'm really at the end of my knowledge! Any help much appreciated.
You should do it like this way,
$sql = "INSERT INTO cache (preview_url, large_url) values";
foreach($urls["largeImg"] as $index => $large_url){
$preview_url = $urls["preview"][$index];
$sql .= "('" . db_escape($db,$preview_url) . "','" . db_escape($db,$large_url) . "'),";
}
$sql = rtrim($sql,",");
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) . ";";
I am going through an article in nettuts.com and it is about building a twitter clone and there is a function in the code that does standard inserts into the database.Here is the code
private function insert($table, $arr){
$query = "INSERT INTO" . $table . " (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref . $key;
$pref = ", ";
}
$query .= ") VALUES (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref. "'" . $value . "'";
$pref = ", ";
}
$query = .= ");";
return $this->db->query($query);
}
what I am having trouble understanding is the $pref variable.Can someone explain its purpose to me?
It's a way of having commas only in between the values in VALUES('like','this','and','this')
because $pref is still set to "" the first time it's value and the key is appended to $query they will always have a comma before the value except the first one:
$query .= $pref . $key;
$pref = ", ";
you could also use the implode() function http://php.net/manual/en/function.implode.php to create a string from the $arr array!
implode(", ", array_keys($arr));
Silly mistake in your code
$query = "INSERT INTO" . $table . " (";
Need to space after INTO
$query = "INSERT INTO " . $table . " (";
$query .= ") VALUES (";
$query .= ");";
I want to bulk insert all POST data without having to individually type each name/field. Is the last line that has the mysql INSERT correct? Also I don't have to reprocess mysql_real_escape_string() again for the INSERT correct?
if (is_array($_POST['add']))
foreach ($_POST['add'] as $key => $value)
$_POST['add'][$key] = mysql_real_escape_string(stripslashes($value));
mysql_query("UPDATE mem SET m_".$key."='".$value."' WHERE m_id=$id");
.... more code
mysql_query("INSERT INTO meminfo m_".$key." VALUES '".$value."'");
This code is injection-prone.
You have to whitelist your keys for protection.
Here is a function to produce SET statement for the mysql queries.
function dbSet($fields, $source = array()) {
$set='';
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`$field`='".mysql_real_escape_string($source[$field])."', ";
}
}
return substr($set, 0, -2);
}
used like this
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "INSERT INTO $table SET ".dbSet($fields,$_POST['add']);
$fields = array("foo","bar");
$query = "UPDATE $table SET ".dbSet($fields,$_POST['add'])." where id=".intval($id);
You can do something like this:
$fields = $values = $set = '';
foreach ($_POST as $key=>$value) {
$fields .= '`fld_' . $key . '`,';
$values .= '"' . mysql_real_escape_string($value) . '",';
$set .= '`fld_' . $key . '` = "' . $mysql_real_escape_string($value) . '",';
}
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
$set = substr($set, 0, -1);
$sql_insert = 'INSERT INTO `table` (' . $fields . ') VALUES (' . $values . ');';
$sql_update = 'UPDATE `table` SET ' . $set . ' WHERE `fld_id`=' . $id . ';';
This code isn't tested, I just wrote it from the top of my head, there could be some errors.
I have the following function to create the SQL for an insert query:
function insertQuery($data, $table) {
$key = array_keys($data);
$sql = "INSERT INTO " . $table . " (" . implode(', ', $key) . ") VALUES " ;
$val = array_values($data);
$sql .= "('" . implode("', '", $val) . "');";
return $sql;
}
Normally, this works fine. However I would like to return a query containing the SQL command LAST_INSERT_ID().
When run through the function, quotes are added so it returns as 'LAST_INSERT_ID()'
Is there a simple way to remove the quotes, without removing the quotes from other items?
Any advice appreciated.
Thanks.
$sql = str_replace("'LAST_INSERT_ID()'", 'LAST_INSERT_ID()', $sql);
The problem is that your input parameters don't make a difference between values and functions. You need to find a way to make that difference obvious to your function.
I expect you use your function like this:
insertQuery(array('name'=>'John', 'age' => 43), 'person');
How about something like this:
insertQuery(
array(
'name' => 'John',
'age' => 43,
'prevId' => array('LAST_INSERT_ID()')
), 'person');
function insertQuery($data, $table) {
$keys = array_keys($data);
$sql = "INSERT INTO `" . $table . "` (`" . implode('`, `', $keys) . "`) VALUES ";
$values = array_values($data);
$sqlparams = array();
foreach ($values as $val) {
if (is_array($val)) {
$val = $val[0];
}
else {
# Escape and quote
$val = '"' . mysql_real_escape_string($val) . '"';
}
$sqlparams[] = $val;
}
$sql .= "(" . implode(", ", $sqlparams) . ");";
return $sql;
}
I also included two bugfixes:
Without mysql_real_escape_string quoting is always wrong. A quote in your parameter will mess up your whole SQL query.
Added quotes around the table and the keys. This way you won't get errors for table and field names that are also keywords in SQL.