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))
Related
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
I know that this theme is very common, but i'm stuck and can't find an error.
I created an array in PHP:
$dataarray=array("FECHAS" => date("Y-m-d"),"HORAS" => date("H:i:s"),
"RGD" => 0,"RGA" => 0,"FLU" => 0,"DD2" => 0,
"H2O" => 0,"PRES:U" => 0,"U" => 0,"V" => 0,"TS" => 0,
"T1" => 0,"T2" => 0,"H1" => 0,"H2" => 0, "HS" => 0,
"VV1" => 0,"VV2" => 0);
and i've got a table in MYSQL with the same names, but when i try to put data into it, it does nothing.
for($j=0;$j<$variable_para_base;$j++)
{
$keys;
$vars;
foreach($dataarray[$j] as $k=>$v)
{
$keys.= $k.',';
$vars.= $v.",";
}
echo $keys."<br>";
echo $vars."<br>";
mysqli_query($mysqli,'INSERT INTO ff ( .$keys.) VALUES ( .vars. ) ') or die(mysql_error());
unset($keys);
unset($vars);
}
if i do it with die option it does for only once another way my key starts to have strange values in the end of it.
Any ideas, and again sorry for maybe a repeted question. I get access to DB because it doesn't give me any error, though noow i'm doubting :(.
You have syntax promlems in your query.
INSERT INTO ff ( .$keys.) VALUES ( .vars. ) '
change it to
INSERT INTO ff ( '.$keys.') VALUES ( '.$vars.') '
Also you need to add ' to the varialbles inserted as VALUES.
like that:
$vars.= "'".$v."',";
In addition your last variable is also ending with , and it shouldn't be.
So your end result might look something like this:
<?
for($j=0;$j<$variable_para_base;$j++)
{
$keys = array();
$vars = array();
foreach($dataarray[$j] as $k=>$v)
{
$keys[] = $k;
$vars[] = $v;
}
$placeholders = array_fill(0, count($keys), '?'); //used to fill a number of '?' needed to fill later
//here we use the '?' array to be placeholders for the values
$query = "INSERT INTO ff (".implode(', ', $keys).") VALUES (".implode(', ', $placeholders).")"; //implode the arrays and separate by comma
$statement = $mysqli->prepare($query);
$types = array(str_repeat('s', count($vars))); //get the number of parameters and put the 's' to it (used for string values)
$values = array_merge($types, $vars); //merge the arrays (gets you {'s', $value})
call_user_func_array(array($statement, 'bind_param'), $values); //bind the values to the statement
$result = $statement->execute(); //execute.
if($result) {
print "Array inserted, worked like a charm.";
}
else {
print "I failed, sorry...". $mysqli->error();
}
unset($keys);
unset($vars);
}
$statement->close();
?>
This is however untested so test it good.
References you can use:
Stackoverflow question: PHP - MySQL prepared statement to INSERT an array
Stackoverflow question: Best way to INSERT many values in mysqli
Stackoverflow question: Mysqli insert command
You can not insert a array directly to mysql as mysql doesn't understand php data types. Mysql only understands SQL. So to insert this array into a mysql database you have to convert it to an sql statement. This can be done manually or by a library. The output should be an INSERT statement.
Here is a standard mysql insert statement.
INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)
If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.
$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";
you have error in query try this,
mysqli_query($mysqli,'INSERT INTO ff (' .$keys. ') VALUES (' .$vars. ') ') or die(mysql_error());
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 an array like this
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
When I do a var-dump I get this ->
{ ["phone"]=> int(111111111) ["image"]=> string(19) "sadasdasd43eadasdad" }
Now I am trying to add this to the DB using the IN statement -
$q = $DBH->prepare("INSERT INTO user :column_string VALUES :value_string");
$q->bindParam(':column_string',implode(',',array_keys($a)));
$q->bindParam(':value_string',implode(',',array_values($a)));
$q->execute();
The problem I am having is that implode return a string. But the 'phone' column is an integer in the database and also the array is storing it as an integer. Hence I am getting the SQL error as my final query look like this --
INSERT INTO user 'phone,image' values '111111111,sadasdasd43eadasdad';
Which is a wrong query. Is there any way around it.
My column names are dynamic based what the user wants to insert. So I cannot use the placeholders like :phone and :image as I may not always get a values for those two columns. Please let me know if there is a way around this. otherwise I will have to define multiple functions each type of update.
Thanks.
Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)
What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.
To insert user defined fields, I think you have to do something like this (at least that how I do it);
$fields=array_keys($a); // here you have to trust your field names!
$values=array_values($a);
$fieldlist=implode(',',$fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="insert into user($fieldlist) values(${qs}?)";
$q=$DBH->prepare($sql);
$q->execute($values);
If you cannot trust the field names in $a, you have to do something like
foreach($a as $f=>$v){
if(validfield($f)){
$fields[]=$f;
$values[]=$v;
}
}
Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)
SQL query parameters can be used only where you would otherwise put a literal value.
So if you could see yourself putting a quoted string literal, date literal, or numeric literal in that position in the query, you can use a parameter.
You can't use a parameter for a column name, a table name, a lists of values, an SQL keyword, or any other expressions or syntax.
For those cases, you still have to interpolate content into the SQL string, so you have some risk of SQL injection. The way to protect against that is with whitelisting the column names, and rejecting any input that doesn't match the whitelist.
Because all other answers allow SQL injection. For user input you need to filter for allowed field names:
// change this
$fields = array('email', 'name', 'whatever');
$fieldlist = implode(',', $fields);
$values = array_values(array_intersect_key($_POST, array_flip($fields)));
$qs = str_repeat("?,",count($fields)-1) . '?';
$q = $db->prepare("INSERT INTO events ($fieldlist) values($qs)");
$q->execute($values);
I appreciated MortenSickel's answer, but I wanted to use named parameters to be on the safe side:
$keys = array_keys($a);
$sql = "INSERT INTO user (".implode(", ",$keys).") \n";
$sql .= "VALUES ( :".implode(", :",$keys).")";
$q = $this->dbConnection->prepare($sql);
return $q->execute($a);
You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.
But the answer to your question might look like this:
$keys = ':' . implode(', :', array_keys($array));
$values = str_repeat('?, ', count($array)-1) . '?';
$i = 1;
$q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
foreach($array as $value)
$q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
I know this question has be answered a long time ago, but I found it today and have a little contribution in addition to the answer of #MortenSickel.
The class below will allow you to insert or update an associative array to your database table. For more information about MySQL PDO please visit: http://php.net/manual/en/book.pdo.php
<?php
class dbConnection
{
protected $dbConnection;
function __construct($dbSettings) {
$this->openDatabase($dbSettings);
}
function openDatabase($dbSettings) {
$dsn = 'mysql:host='.$dbSettings['host'].';dbname='.$dbSettings['name'];
$this->dbConnection = new PDO($dsn, $dbSettings['username'], $dbSettings['password']);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function insertArray($table, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="INSERT INTO `".$table."` (".$fieldlist.") VALUES (${qs}?)";
$q = $this->dbConnection->prepare($sql);
return $q->execute($values);
}
function updateArray($table, $id, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$firstfield = true;
$sql = "UPDATE `".$table."` SET";
for ($i = 0; $i < count($fields); $i++) {
if(!$firstfield) {
$sql .= ", ";
}
$sql .= " ".$fields[$i]."=?";
$firstfield = false;
}
$sql .= " WHERE `id` =?";
$sth = $this->dbConnection->prepare($sql);
$values[] = $id;
return $sth->execute($values);
}
}
?>
dbConnection class usage:
<?php
$dbSettings['host'] = 'localhost';
$dbSettings['name'] = 'databasename';
$dbSettings['username'] = 'username';
$dbSettings['password'] = 'password';
$dbh = new dbConnection( $dbSettings );
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
$dbh->insertArray('user', $a);
// This will asume your table has a 'id' column, id: 1 will be updated in the example below:
$dbh->updateArray('user', 1, $a);
?>
public function insert($data = [] , $table = ''){
$keys = array_keys($data);
$fields = implode(',',$keys);
$pre_fields = ':'.implode(', :',$keys);
$query = parent::prepare("INSERT INTO $table($fields) VALUES($pre_fields) ");
return $query->execute($data);
}