When i insert this type of array values directly into Mysql database, I got error like this
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':23:09Z, 36840bd430637, Success, 85.0, 11457922, 10.02, USD, X, M, 59106737WV831' at line 1
and myquery is
INSERT INTO `transaction`(TIMESTAMP, CORRELATIONID, ACK, VERSION, BUILD, AMT, CURRENCYCODE, AVSCODE, CVV2MATCH, TRANSACTIONID) VALUES (2014-06-26T02:23:09Z, 36840bd430637, Success, 85.0, 11457922, 10.02, USD, X, M, 59106737WV831451U)
Mycode is
$columns = implode(", ",array_keys($result_array));
$escaped_values = array_map('mysql_real_escape_string', array_values($result_array));
$values = implode(", ", $escaped_values);
echo $sql = "INSERT INTO `transaction`($columns) VALUES ($values)";
$res =mysql_query($sql);
what are the changes can i do?
First of all, you should escape column names (not always required):
$cols = join(',', array_map(function($name) {
return '`' . str_replace('`', '``', $name) . '`';
}, array_keys($result_array));
Then, keeping in mind that mysql_real_escape_string() doesn't add quoted enclosures:
$vals = join(',', array_map(function($value) {
return "'" . mysql_real_escape_string($value) . "'";
}, $result_array);
$sql = "INSERT INTO `transaction` ($cols) VALUES ($vals)";
Lastly, using mysql_ functions is deprecated and you should move onto using either PDO or mysqli.
What is meaning of echo $sql here? try this way & you can also escape your string firstly.
foreach($singleRow as $key=>$data) //for multiple rows
{
if(isset($data)){
$dataArray[$key] = is_string($data) ? mysql_real_escape_string($data) : $data;
}
}
$tableName='transaction';
$keys = implode(',',array_keys($dataArray));
$data_values = ("'".implode("','",array_values($dataArray))."'");
$insertSql = "INSERT INTO ".$tableName." ($keys) VALUES ($data_values)";
$res =mysql_query($insertSql );
use mysqli_* and PDO anyway
Related
Hi i been trying to inserting array's into MySql database
The problem i am having is that i have different datatypes and sometime data can be a 0 value, having () curly brackets, percentage value with % sign. I would like to know a way use some already built php function that can deal with this issues.
So here is what i have done so far:
$t = array('country_code' => $data->country_code,
'Name' => $data->Name,
'money' => $data->money,
'chanceToDie' => $data->death,
'age' => $cb->age)
/* FORMAT EXAMPLE
country_code = Africa (AF)
name = jack
chanceToDie = 5.5
age = 62
*/
$columns = implode(", ",array_keys($t));
//Tried
$values = implode(", ",array_values($t)); //Dont work
$values = "'".implode("', '",array_values($t))."'"; //Dont work
$sql = "INSERT INTO table ($columns) VALUES ($values)";
You need to quote each individual value and use array_values() instead of array_keys():
$values = '"' . implode('", "', array_values($t)) . '"';
However, this leaves you with an sql injection problem so you should really use a prepared statement.
In PDO you could use something like (assuming you control the keys and they are safe to use):
$values = ':' . implode(', :', array_keys($t));
// generates: ... VALUES(:country_code, :Name, :money, // etc
Now you can prepare and execute your query using the array to bind the values to the placeholders. See for example http://php.net/manual/en/pdo.prepared-statements.php (the 6th example).
Try to use the advantage of PDO prepared queries - it is more safe and convinient.
Your code may look like this:
$col_names = array_keys($t);
// filter column names before inserting to sql to prevent sql injection
array_filter($col_names, function($v){return preg_relace("#\W#", "_", $v);});
// generate placeholders list: ?,?,?,?
$placeholders = implode(',', array_fill(0, count(t), "?"));
$values = array_values($t);
$q = $pdo->prepare('insert into (' . implode(",", $col_names) . ') values (' . $placeholders . ')');
$q->execute($values);
PDO will deal with data types and correctly replace every placeholder with the corresponding value.
I am trying to create a custom MVC framework in that I have a function which takes in array and triggers insert queries.
function insertFromArray($array, $table) {
foreach ($array as $key => $value) {
$fields[] = "`" . $key . "`";
$values[] = "'" . $value . "'";
}
$sql = "INSERT INTO `$table` (" . implode(",", $fields) . ") VALUES (" . implode(",", $values) . ")";
mysql_query($sql);
return (mysql_error()) ? mysql_error() : mysql_insert_id();
}
But when I get some mysql function instead of a string or integer my function does not work say for a filed name 'dateTime' I get value = NOW() in that case my query would be
INSERT INTO `$table` (`field1`, `field2`, `dateTime`) VALUES ('value1','value2','NOW()')
And this would throw error I want some generic solution so that my queries would run in either case if it is a string, number or if it is any mysql function.
I tried creating an array of all the functions and started with comparisons like if the starting of the $value matches any function from the array of mysql functions but I do not think that is a good way to do it, is there any better way to do that
$values[] = "'" . $value . "'";
The above line treats all values as strings and this causes the issue. Do not treat all values as strings and enclose them by single quotes.
You could even make the value part an array itself with 2 elements: one for the value and one for the type of the value (string, numeric, function, etc.) and would treat ech of them differently while creating the insert statement.
And pls use mysql or PDO instead of php's old mysql extension.
You could use an array to store your SQL keywords/function names. Then in your query string, you test to see if the current value is an SQL word or not. If it is, don't quote it, otherwise, you quote it.
Here is an example:
function is_sql_term($term)
{
$sql_terms = array('NOW()', 'DATE()', ...);
return in_array($term, $sql_terms) || preg_match("/\(.*\)/", $term);
}
Then you test as follows:
$values[] = is_sql_term($value) ? $value : "'" . $value . "'";
I have tried to create a function for an SQL/PDO Insert query:
function InsertQuery ($table,$cols,$values) {
global $pdo_conn;
foreach($values as $values2) {
$values2 = $values2;
}
$stmt='INSERT into $table (';
foreach($cols as $cols2) {
$stmt.=" ".$cols2.", ";
}
$stmt.=" ) VALUES ( ";
foreach($cols as $cols2) {
$stmt.=" :".$cols2." ";
}
$stmt.=" ) ";
$stmt2 = $pdo_conn->prepare($stmt);
foreach($cols as $cols2) {
$stmt2->bindParam(':$cols2', $cols2);
}
}
but i am getting the error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in /home/integra/public_html/admin/includes/functions.php on line 30
please be patient with me as i am new to PDO and just used to using MySQL
have i put the prepared statement wrong or my foreach loops?
I believe the statement should look like:
$stmt2 = $pdo_conn->prepare('INSERT into $table (col1) values (:val1)');
$stmt2->bindParam(':$val1', $val);
here is how i called my function:
$col=array('col1');
$val=array('val1');
InsertQuery ("table1",$col,$val);
UPDATE:
Ok here is my new code:
global $pdo_conn;
foreach($values as $values2) {
$values2 = $values2;
}
$stmt='INSERT into '.$table.' (';
foreach($cols as $cols2) {
$stmt.=" ".implode(",", $cols2)." ";
}
$stmt.=" ) VALUES ( ";
foreach($cols as $cols2) {
$stmt.=" :".implode(",", $cols2)." ";
}
$stmt.=" ) ";
$stmt2 = $pdo_conn->prepare($stmt);
foreach($cols as $cols2) {
$stmt2->bindParam(':$cols2', $cols2);
}
but i now get the error about the implode:
Warning: implode() [function.implode]: Invalid arguments passed in /home/integra/public_html/admin/includes/functions.php on line 18
Warning: implode() [function.implode]: Invalid arguments passed in /home/integra/public_html/admin/includes/functions.php on line 22
which i think is because there is nothing to implode as there is only one column and one value
Use type hints to ensure the function arguments are arrays:
function InsertQuery ($table, array $cols, array $values) {
Make sure your PDO connection is accessible. If it's global, you have to declare it (credit to #u_mulder):
global $pdo_conn;
The following does nothing, get rid of it:
foreach($values as $values2) {
$values2 = $values2;
}
Use builtin array functions instead of foreach'ing everything:
$col_list = implode(",", $cols);
$param_list = implode(",", array_fill(1,count($cols), "?"));
Variables don't expand inside single-quotes. You need to use double-quotes (credit to #MichaelBerkowski).
Also, use $stmt for a PDOStatement object, and not for the SQL string. That's confusing.
$sql="INSERT into $table ($col_list) VALUES ($param_list)";
$stmt = $pdo_conn->prepare($sql);
You don't need to write a foreach loop to bindParam() in PDO. You can just pass an array of values to execute(). And you already have the values in an array, so it's really easy:
$stmt->execute($values);
}
For extra safety, make sure to delimit the columns, in case someone uses special characters or a SQL keyword in a column name:
$col_list = implode(",", array_map(function ($c) { return "`$c`" }, $cols));
And make sure the values is in a simple array, not an associative array:
$stmt->execute(array_values($values));
Re your comment:
would you be able to show me how to do the same with select, I'm not sure how it would work as if i have a where clause what would i do with it in the function?
One could for example design a function with an argument $where that is an associative array, whose keys are column names, and whose values are the values you're searching for.
Assume the resulting WHERE clause includes these column/value pairs as AND terms, and all the comparisons are equality.
function SelectQuery($table, array $where) {
global $pdo_conn;
$sql = "SELECT * FROM `$table` ";
$values = null;
if ($where) {
$sql .= "WHERE " . implode(" AND ",
array_map(function ($c) { return "`$c` = ?"; } array_keys($where)));
$values = array_values($where);
}
$stmt = $pdo_con->prepare($sql);
$stmt->execute($values);
}
Of course this supports only a small subset of the possible expressions you can have in a SELECT, but I'm just demonstrating a technique here.
If you want a more fully-feature query builder for PHP, take a look at Zend_Db_Sql or Doctrine QueryBuilder or Laravel query builder.
if anything changes on my server and the PDO stops working i can revert back to MySQL while i fix it.
PDO has been stable since 2005 and it will not stop working, unless you change your PHP environment and disable the extension or the mysql driver or something.
Whereas the ext/mysql extension will stop working. It is currently deprecated and PHP has announced they will remove it in a future version of PHP.
There are a few things going on:
First, $cols and $vals should be arrays, but they are strings.
Quick fix is to make them arrays:
$col = array('col1');
$val = array('val1');
InsertQuery("table1", $col, $val);
Second, $pdo_conn is unknown in the function scope. Make it a parameter or a global.
you can also use this for create query from array:
$myArray = array(
'col1' => 'val1',
'col2' => 'val2'
);
$query = "INSERT INTO table (" . implode(", ", array_keys($myArray)) . ") VALUES (" . implode(", ", $myArray) . ")";
maybe usefull for you
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Let's read the image file into varialble picture:
$picture = addslashes(fread(fopen($image, "r"), filesize($image)));
This $picture you can easy insert into database table with no trouble.
*for example*: INSERT INTO $banners(banner) VALUES( $picture );
For some reason lets create an associative array $final:
$final["banner"] = $picture;
$final["place"] = something...
Later lets decompose $final and insert the obtained values into database:
$fields = ""; $values = "";
while (list($name, $value) = each( $final ))
{
$fields .= "$name, ";
$values .= "'$value', ";
}
// Cut trailing commas
$values_fields = ereg_replace(", $", "", $values_fields);
$values = ereg_replace(", $", "", $values);
// Execute query
$query = "INSERT INTO banners($values_fields) VALUES($values)";
$res = mysql_db_query($database, $query) or mysql_die();
Now MySQL warns "Something wrong" when comes to insert consecutive $value with $picture into database. Why?
First, don't destroy your data. Read it directly and keep the variable clean:
$picture = file_get_contents($image);
Next, prepare the data for insertion:
$final["banner"] = mysqli_real_escape_string($picture);
$final["place"] = $something;
Last, there is no need to loop through your array, since it only contains one record. You don't quote the values, causing an error.
$fields = "`" . implode("`, `", array_keys($final)) . "`";
$values = "'" . implode("', '", array_values($final)) . "'";
$query = "INSERT INTO banners ({$fields}) VALUES ({$values})";
$result = mysqli_query($database, $query) or die(mysqli_error($database));
I'm using MySQLi here, since the mysql_* functions are deprecated (as well as ereg_* functions).
If the code you posted here is exactly the one you are trying to run then please note that you are accumulating field names in $fields variable but "cut trailing commas" from $values_fields which is at this point empty. Putting empty $values_fields into your query might be the cause of mysql error.
Why are you doing addslashes()? Try to use mysql_real_escape_string() instead.
Also make sure that the type of the database column where you are trying to put your image into is BLOB or LONGBLOB.
You may find answer to this question Binary Data in MySQL relevant.
i have this function
protected function insert($data){
$data['datecreated'] = date('Y-m-d h:i:s');
echo "array_keys(data) = ".$data['datecreated'];
var_dump($data);
echo array_keys($data);
$sql = "INSERT INTO {$this->table_name} (". array_keys($data).")";
$sql.= " VALUES ('";
$sql.=implode("','", $data);
$sql.=")";
$this->execute($sql);
$this->last_id = mysql_insert_id();
}
when i read the array_keys($data) it returns 'Array' not the key
i call it like this $this->insert(array()); why is that ?
EDIT :
this is the output
array_keys(data) = 2012-05-18 04:44:46array(2) { [0]=> array(0) { } ["datecreated"]=> string(19) "2012-05-18 04:44:46" } Array
Notice: Array to string conversion in /Applications/MAMP/htdocs/Tamara/model/dbTable.php on line 105
INSERT INTO account (Array) VALUES ('Array','2012-05-18 04:44:46)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2012-05-18 04:44:46)' at line 1
array_keys returns an array with all the keys.
You need to implode that aswell
implode(',', array_keys($data));
Edit:
And you might want to take a look at this part
$sql.=implode("','", $data);
$sql.=")";
You need need a starting and trailing '.
What you want is implode(',', array_keys($data)) since array_keys() returns an array containing all the keys - but you want a comma-separated string:
$sql = "INSERT INTO {$this->table_name} (".implode(',', array_keys($data)).")";
By the way, I hope that the values in $data are already escaped. If not, replace implode("','", $data) with implode("','", array_map('mysql_real_escape_string', $data))