converting an insert function using query method into a prepared statement - php

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

Related

Submit Multi-Dimensional Array to mySQL

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,",");

Call to a member function getTimestamp() on boolean

I got this error whatever format i changed, i have no idea what else causes of this. Can someone help me on this? My csv excel dateTime format is yyyy/mm/dd H:mm
$i = 0;
$len = count($map_column);
$insData = array();
foreach ($map_column as $key => $value) {
$i++;
if ($key == 'dateTime') {
$date = date_create_from_format('Y/m/d H:i:s', $row[$value]);
$timestamp = $date->getTimestamp();
$sql .= 'UNIX_TIMESTAMP('.$key . ') = "' . $timestamp . '"';
} else {
$sql .= $key . ' = "' . $row[$value] . '"';
}
$insData[$key] = $row[$value];
if ($i < $len) {
$sql .= ' AND ';
}
}
$result = mysqli_query($cons, $sql);
$r = mysqli_fetch_array($result);
$count = (int)$r['count'];
if ($count) {
return;
}
// pr($insData);
$columns = implode(", ",array_keys($insData));
$escaped_values = array_values($insData);
$values = implode("', '", $escaped_values);
$sql = "INSERT INTO hrar($columns) VALUES ('$values')";
if ($cons->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

php database insert function

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 .= ");";

Bulk INSERT foreach statement

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.

Creating a flexible update query

I'm trying to create an flexible update query. I have now something like this:
$lsQuery = "UPDATE `";
$lsQuery .= $psTableName;
$lsQuery .= " SET ";
foreach($psValues as $lsKey => $lsValue)
{
$lsQuery .= $lsKey;
$lsQuery .= " = '";
$lsQuery .= $lsValue;
$lsQuery .= "' AND ";
}
$lsQuery .= "` ";
$lsQuery .= "WHERE ";
if(isset($psWhere)){
foreach($psWhere as $lsKey => $lsValue)
{
$lsQuery .= $lsKey;
$lsQuery .= " = '";
$lsQuery .= $lsValue;
$lsQuery .= "' AND ";
}
}
$lsQuery = substr($lsQuery,0,(strlen($lsQuery)-5));
But when I print my query on the screen I get something like:
UPDATE persons SET per_password = '2a6445462a09d0743d945ef270b9485b' AND WHERE per_email = 'bla#gmail.com'
How can I get rid of this extra 'AND'?
I'd probably start with:
function update($table, $set, $where) {
$change = array();
foreach ($set as $k => $v) {
$change[] = $k . ' = ' . escape($v);
}
$conditions = array();
foreach ($where as $k => $v) {
$conditions[] = $k . ' = ' . escape($v);
}
$query = 'UPDATE ' . $table . ' SET ' .
implode(', ', $change) . ' WHERE ' .
implode(' AND ', $conditions);
mysql_query($query);
if (mysql_error()) {
// deal with it how you wish
}
}
function escape($v) {
if (is_int($v)) {
$v = intval($v);
} else if (is_numeric($v)) {
$v = floatval($v);
} else if (is_null($v) || strtolower($v) == 'null') {
$v = 'null';
} else {
$v = "'" . mysql_real_escape_string($v) . "'";
}
return $v;
}
If you want to keep your existing code.
$lsWhere = array();
foreach($psWhere as $lsKey => $lsValue)
{
$lsWhere[] = $lsKey." = '".mysql_real_escape_string($lsValue)."'";
}
$lsQuery .= join(" AND ", $lsWhere);
It's not a solution I'm particularly proud of, but you can always add $lsQuery .= 'someField=someField'.

Categories