PHP - Remove part of string from another string - php

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.

Related

Escape String in SQL Server using PHP

Whenever I implement this code, I no longer get an error while using a single quote, but the hexstring get's written to the database instead of being converted back to the original characters.
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
This is what I'm trying to do. $suggestTest is the variable I'm using the escape function on.
$nomDept = $_POST['nomDept'];
$subSupervisor = $_POST['subSupervisor'];
$suggestion = $_POST['suggestion'];
$suggestTest = mssql_escape($suggestion);
if ($subSupervisor == "Yes") {
$query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
$query .= "'" . $nomDept . "', ";
$query .= "'" . $suggestTest . "', ";
$query .= "'" . $subSupervisor . "');";
$res = mssql_query($query);
}
I've also tried omitting the single quotes around the variable like so
if ($subSupervisor == "Yes") {
$query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
$query .= "'" . $nomDept . "', ";
$query .= $suggestTest ", ";
$query .= "'" . $subSupervisor . "');";
$res = mssql_query($query);
}
If you use prepare to build your SQL statement, you do not need to escape the variables.

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.

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