I am trying to build a class that insert array of values into oracle database, I am also trying to make the class scalable (works with all forms of the application).
the reason am doing this is to reduce code repeating for the application am working on, because it has a lot of forms, and some of them has a lot of variables (50+).. therefore I need to make a class capable of inserting values into table, where the number of values is dynamic (depending on the form).
so far what I did is:
class ArrayQuery {
public $conn;
public $table;
public function __construct($conn){
$this->conn = $conn;
}
public function setTableName($table)
{
$this->table = $table;
}
public function InsertArray(array $args){
$keys = array_keys($args);
$values = array_values($args);
// need help here //
}
}
The construct function will get database connection, by calling the $conn object from the db_connection class (e.g $conn = new db_connection(); $query = new ArrayQuery($conn);)
setTableName is obviously for defining the desired table.
now the ArrayQuery, what I did in my form page, I named the keys of the array the same as the name of columns in table, for example array args['id']= $_post['id']. so basically array_key = column name. I did that in order to get columns name without manually setting them.
now I have 2 arrays: $keys (holds the name of columns), and $values (holds the data to be insert).
I cant figure out how to bind variables into keys? knowing that the number of variables is dynamic ?
any help will be much appreciated
UPDATE:
Here is how the $args array are set
$args = array(
'id' => $_POST['id'],
'firstname' => $_POST['firstname'],
'lastname' => $_POST['lastname'],
'email' => $_POsT['email'],
)
answer:
thanks to #calculon for putting me on the right track, with little modifications to work in my scenario, for future reference the answer to my case is:
$i=0; $col=''; $val='';
foreach ($args as $key => $value) {
if($i==0){
$col .= $key;
$val .= ':'.$key;
}
else{
$col .= ', '.$key;
$val .= ', :'.$key;
}
$i++;
}
$sql = 'INSERT INTO '.$table.' ('.$col.') VALUES ('.$val.') ';
$stmt = oci_parse($this->conn, $sql);
foreach ($args as $key => $value) {
oci_bind_by_name($stmt, $key, $args[$key]) ;
}
oci_execute($stmt);
hope it will be helpful, thanks again calculon.
Approximately such algorithm for inserting one row with an unknown number of columns I used in my project, for multiple rows should be added one more cycle
$i=0; $keys=''; $vals='';
foreach ($args as $key => $value) {
if($i==0){
$keys .= ''.$key;
$vals .= ':'.$key;
}
$keys .= ', '.$key;
$vals .= ', :'.$key;
$i++;
}
$sql = 'INSERT INTO '.$table.' ('.$keys.') VALUES ('.$vals.') ';
$stmt = oci_parse($conn, $sql);
foreach ($args as $key => $value) {
oci_bind_by_name($stmt, $key, $args[$key]) ;
}
oci_execute($stmt);
Related
public function add_employee($input)
{
$key_array = null;
$value_array = null;
$bind_array = null;
foreach ($input as $column => $value) {
if ($value) {
#$bind_array => ?, ?, ?;
#$value_array => [$value1, $value2, $value3];
#$key_array => column1, column2, column3;
}
}
$sql = "INSERT INTO ol_employee ($key_array) VALUES ($bind_array)";
$this->db->query($sql, $value_array);
}
Refer to comment in the function, how to achieve that output?
the idea is, from the input POST i get which over 27 fields, i just want to fill in into the $sql query i prepared as you can see. I don't think writing each table column manually is a good way.
im using Codeigniter 4 php framework + postgresql.
According to CodeIgniter 4 documentation, you can do this inside your loop for each employee:
$data = [
'title' => $title,
'name' => $name,
'date' => $date
];
$db->table('mytable')->insert($data);
You can use array and implode function first make array of key_array, value_array and bind_array then use implode() and use in sql like following
public function add_employee($input)
{
$key_array = array();
$value_array = array();
$bind_array = array();
foreach ($input as $column => $value) {
if ($value) {
$bind_array[] = '?';
$value_array[] = $value;
$key_array[] = $column;
}
}
$binds = implode(",",$bind_array);
$keys = implode(",",$key_array);
$values = implode(",",$value_array);
$sql = "INSERT INTO ol_employee ($keys) VALUES ($binds)";
$this->db->query($sql,$values);
}
by the insight of Alex Granados, this is the query i use:
public function add_employee($input)
{
foreach ($input as $column => $value) {
if ($value) {
$data[$column] = $value;
}
}
$this->db->table('ol_employee')->insert($data);
}
this will eliminate null field and regardless how many field, still working good.
as long the input name field from form is same as db column. Else, need to do some changes on that.
Thanks guys.
I'm preparing my own function due to hurry the updates automatically.
I have that code:
$allowededitablefields = array('mail');
$userid = $_GET['uid'];
$query = 'UPDATE users SET ';
foreach ($_POST as $key => $value) {
if(!in_array($key,$allowededitablefields)) {
unset($_POST[$key]);
}
else {
$query .= $key.' = :'.$key.',';
}
}
$query = substr($query, 0, -1);
$query .= ' WHERE id='.$userid;
$statement = $this->_db->prepare($query);
foreach ($_POST as $key => $value) {
$statement->bindParam(':'.$key,$value);
}
$statement->execute();
If in $allowededitablefields array, I have only a value, it works properly, but if I push some values to the array, for example $allowededitablefields = array('mail','country',...); the fields in the table take the same values.
$value holds the value of the last iteration when the foreach loop ends.
change the bindParam to this.
$statement->bindParam(':'.$key,$_POST[$key]);
This should work, but your approach is fundamentally flawed. It undermines the whole purpose of prepared statements.
I am using an API that returns search results as json. Then, I need to write this to a MYSQL table. I've done this successfully before, but this time the situation is different, and I think that's because of the structure of the resulting array: the key names are dynamic in that, if no data exists for a particular key, the key is not listed in the array. Here is an example vardump of the array:
array
0 =>
array
'title' => string 'Funny but not funny' (length=19)
'body' => string 'by Daniel Doi-yesterday while eating at Curry House...
'url' => string 'http://danieldoi.com/2012/11/20/funny-but-not-funny/'
'source_site_name' => string 'WordPress.com' (length=13)
'source_site_url' => string 'http://www.wordpress.com' (length=24)
'query_topic' => string 'thanksgiving' (length=12)
'query_string' => string 'blogs=on&topic=thanksgiving&output=json' (length=39)
1 =>
array
'title' => string 'Travel Easy this Holiday Season...' (length=34)
'body' => string 'Give yourself a few gifts and get this holiday season off...
'url' => string 'http://facadebeauty.wordpress.com/2012/11/20
'date_published' => string 'Tue, 20 Nov 2012 18:22:35 +0000' (length=31)
'date_published_stamp' => string '1353435755' (length=10)
Notice how the order/inclusion of the keys is subject to change.
My proposed solution was to use the array keys as column names, turning them into a variable to use in a query statement, but this isn't working for me. Here's my attempt:
$jsonString = file_get_contents("http://search-query-URL&output=json");
$array = json_decode($jsonString, true);
// database connection code snipped out here
$table = "results";
foreach($array as $arr_value) {
foreach ($arr_value as $value) {
$colName = key($arr_value);
$colValue = ($value);
$insert="INSERT INTO $table ($colName) VALUES ('$colValue')";
mysql_query($insert) OR die(mysql_error());
next($arr_value);
}
}
Any suggestions on where to look next? Thank you!
UPDATE 11/27:
Here I am trying to adapt David's suggestion. I'm receiving the following error: "Database Connection Error (1110) Column 'title' specified twice on query."
Here's my code as it stands now:
$mysqli = mysqli_connect("localhost");
mysqli_select_db($mysqli, "mydatabase");
foreach ($array as $column) {
foreach ($column as $key => $value) {
$cols[] = $key;
$vals[] = mysqli_real_escape_string($mysqli, $value);
}
}
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";
$mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;
Final Upate - WORKING!
It's working. Here's what we've got:
$mysqli = mysqli_connect("localhost");
mysqli_select_db($mysqli, "mydatabase");
foreach ($array as $column) {
foreach ($column as $key => $value) {
$cols[] = $key;
$vals[] = mysqli_real_escape_string($mysqli, $value);
}
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";
$mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
unset($cols, $vals);
}
mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;
I actually have just this function sitting around because I use it all the time. What this does: pool all the associative pairs in your array for insertion into the table, and puts them in as a single insert. To be clear: this isn't what you're doing above, as it looks like you're trying to insert each value in its own insert, which would probably give you way more rows than you want.
function mysqli_insert($table, $assoc) {
$mysqli = mysqli_connect(PUT YOUR DB CREDENTIALS HERE);
mysqli_select_db($mysqli, DATABASE NAME HERE);
foreach ($assoc as $column => $value) {
$cols[] = $column;
$vals[] = mysqli_real_escape_string($mysqli, $value);
}
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";
$mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;
}
As MarcB says above, there is a risk that your target table won't have a column that your results show. But we are sanitizing the insertion (with mysqli_real_escape_string) so we shouldn't have issues with injections vulnerabilities.
Here's one-liner:
$query = 'INSERT INTO '.$table.'(`'.implode('`, `', array_keys($array)).'`) VALUES("'.implode('", "', $array).'")';
I noticed an answer being posted above, but since I already wrote this, thought I'd post it. Note: I hope you trust where you get your data from, otherwise this opens up all sorts of problems. I've also added comments throughout the code, hopefully helps to understand how it's being done.
$jsonString = file_get_contents("http://search-query-URL&output=json");
$array = json_decode($jsonString, true);
// database connection code snipped out here
$table = "results";
foreach($array as $sub_array) {
// First, grab all keys and values in separate arrays
$array_keys = array_keys($sub_array);
$array_values = array_values($sub_array);
// Build a list of keys which we'll insert as string in the sql query
$sql_key_list = array();
foreach ($array_keys as $key){
$sql_key_list[] = "`$key`";
}
$sql_key_list = implode(',', $sql_key_list);
// Build a list of values which we'll insert as string in the sql query
$sql_value_list = array();
foreach ($array_values as $value){
$value = mysql_real_escape_string($value);
$sql_value_list[] = "'$value'";
}
$sql_value_list = implode(',', $sql_value_list);
// Build the query
$insert = "INSERT INTO $table ($sql_key_list) VALUES ($sql_value_list)";
mysql_query($insert) or die(mysql_error());
}
In my database I've fields like "status", which are reserved keywords. This code works fine for me (status is escaped by ``):
$sql = "UPDATE $table SET `status`='$status' WHERE `id`='123'";
But now I want to use prepared statements only! My Database.class:
class Database extends \PDO {
private $_sth; // statement
private $_sql;
public function update($tbl, $data, $where, $where_params = array()) {
// prepare update string and query
$update_str = $this->_prepare_update_string($data);
$this->_sql = "UPDATE $tbl SET $update_str WHERE $where";
$this->_sth = $this->prepare($this->_sql);
// bind values to update
foreach ($data as $k => $v) {
$this->_sth->bindValue(":{$k}", $v);
}
// bind values for the where-clause
foreach ($where_params as $k => $v) {
$this->_sth->bindValue(":{$k}", $v);
}
return $this->_sth->execute();
}
private function _prepare_update_string($data) {
$fields = "";
foreach ($data as $k => $v) {
$fields .= "`$k`=:{$k}, ";
}
return rtrim($fields, ", ");
}
}
Update example that won't work:
$DB = new Database();
$DB->update("tablename",
array("status" => "active"),
"`username`=:username AND `status`=:status",
array("username" => "foofoo", "status" => "waiting"));
I think, its because of the reserverd keyword "status". But I don't know how to escape it. I tried to escape the placeholder in _prepare_update_string($data) to:
bindValue("`:{$k}`", $v)
but no result.
I hope the solution is very simple and it's just a stuck overflow in my brain. ;-) Thanks in advance people!
When you construct the SQL string (prepare_update_string i think), as well as in both the foreach loops where you bind data, run an incrementing count and append it to the bind value. So ":status" become ":status1".
Something like:
$i = 1;
foreach ($data as $k => $v) {
$this->_sth->bindValue(":{$k.$i}", $v);
$i++;
}
This will solve the problem of any reserved keywords.
It also solves the problem (which I'm sure you'll encounter in the future) where you need to bind to the same placeholder more than once.
e.g. instead of the following, which throws an error due to two binds on the :status placeholder
SELECT * from table WHERE `status` = :status AND `otherfield` = :status
With an incrementing count, this becomes:
SELECT * from table WHERE `status` = :status1 AND `otherfield` = :status2
Enjoy.
I had a similar problem and solved by passing the parameter by reference
I have a varchar(3) field and a pointer was been passed instead of 'aaa' value
This works ($val by reference):
<?php
foreach ($params as $key => &$val) {
$sth->bindParam($key, $val);
}
?>
This will fail ($val by value, because bindParam needs &$variable):
<?php
foreach ($params as $key => $val) {
$sth->bindParam($key, $val);
}
?>
reference: Vili's comment at
https://www.php.net/manual/pt_BR/pdostatement.bindparam.php
In trying to create a simple PHP PDO update function that if the field is not found would insert it, I created this little snippet.
function updateorcreate($table,$name,$value){
global $sodb;
$pro = $sodb->prepare("UPDATE `$table` SET value = :value WHERE field = :name");
if(!$pro){
$pro = $sodb->prepare("INSERT INTO `$table` (field,value) VALUES (:name,:value)");
}
$pro->execute(array(':name'=>$name,':value'=>$value));
}
It does not detect though if the update function is going to work with if(!$pro); How would we make this one work.
You are assigning $pro to the prepare, not the execute statement.
Having said that, if you are using mysql you can use the insert... on duplicate key update syntax.
insert into $table (field, value) values (:name, :value) on duplicate key update value=:value2
You can't use the same bound param twice, but you can set two bound params to the same value.
Edit: This mysql syntax will only work where a key (primary or another unique) is present and would cause an insert to fail.
If it's mysql-only you could try INSERT INTO ... ON DUPLICATE KEY UPDATE
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You will first need to execute it.
Apart from that, this is a dodgy way of doing this. It would be better to start a transaction, do a SELECT and then determine what to do (INSERT or UPDATE). Just checking whether the UPDATE query succeeded doesn't suffice, it succeeds when no row is found too.
try,
PDO::exec()
returns 1 if inserted.
2 if the row has been updated.
for prepared statements,
PDOStatement::execute()
You can try,
PDOStement::rowCount()
The following are PHP PDO helper functions for INSERT and UPDATE
INSERT function:
function basicInsertQuery($tableName,$values = array()){
/*
//
USAGE INSERT FUNCTÄ°ON
$values = [
"column" => $value,
];
$result = basicInsertQuery("bulk_operations",$values);
*/
try {
global $pdo;
foreach ($values as $field => $v)
$vals[] = ':' . $field;
$ins = implode(',', $vals);
$fields = implode(',', array_keys($values));
$sql = "INSERT INTO $tableName ($fields) VALUES ($vals)";
$rows = $pdo->prepare($sql);
foreach ($values as $k => $vl)
{
$rows->bindValue(':' . $k, $l);
}
$result = $rows->execute();
return $result;
} catch (\Throwable $th) {
return $th;
}
}
UPDATE function:
function basicUpdateQuery($tableName, $values = array(), $where = array()) {
/*
*USAGE UPDATE FUNCTÄ°ON
$valueArr = [ column => "value", ];
$whereArr = [ column => "value", ];
$result = basicUpdateQuery("bulk_operations",$valueArr, $whereArr);
*/
try {
global $pdo;
//set value
foreach ($values as $field => $v)
$ins[] = $field. '= :' . $field;
$ins = implode(',', $ins);
//where value
foreach ($where as $fieldw => $vw)
$inswhere[] = $fieldw. '= :' . $fieldw;
$inswhere = implode(' && ', $inswhere);
$sql = "UPDATE $tableName SET $ins WHERE $inswhere";
$rows = $pdo->prepare($sql);
foreach ($values as $f => $v){
$rows->bindValue(':' . $f, $v);
}
foreach ($where as $k => $l){
$rows->bindValue(':' . $k, $l);
}
$result = $rows->execute();
return $result;
} catch (\Throwable $th) {
return $th;
}
}