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 .= ");";
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 have the following code that does standard INSERTs.How can i rewrite this function to do the same but instead of using
$this->db->query($query)
i want it to be able to do the same by using a prepared statement because this code seems very vulnerable against SQL injection..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);
}
I am connected to mysql with PDO.
EDİT:I wrote the following code which works without a problem.
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. ":" . $key ;
$pref = ", ";
}
$query .= ");";
$result = $this->db->prepare($query);
$result->execute($arr);
}
From http://www.php.net/manual/en/pdo.prepare.php Example #1, try something like
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. ":" . $key;
$pref = ", ";
}
$query = .= ")";
$this->db->prepare($query);
$this->db->execute($arr);
}
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 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
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.