I'm coding my web app in PHP and when I run my script, I've got this error :
array to string conversion
Here is the script where the error fires.
public function insert($table, array $columns, array $values) {
$sql = "INSERT INTO " . $table .
" (" . implode(',' , $columns) . " )
VALUES (" . implode(',',
$values) . ")";
$this->request($sql);
}
Here is the request function :
public function request($sql, $param = null) {
if ($param == null) {
$query = Database::getInstance()->getDb()->query($sql);
}
else {
$query = Database::getInstance()->getDb()->prepare($sql);
$query->execute(array($param));
}
return $query;
}
N.B : I'm using my own MVC framework.
So, any advise or help would be apreciated ?
Regards
YT
I advice to modify your class methods for using parameterized queries:
class Test {
public function insert($table, array $columns, array $values) {
$sql = "INSERT INTO " . $table . " (" . implode(',' , $columns) . ")
VALUES (?" . str_repeat(",?", count($columns) - 1) . ");";
echo $sql;
$this->request($sql, $values);
}
public function request($sql, $param = null) {
if ($param == null) {
$query = Database::getInstance()->getDb()->query($sql);
}
else {
$query = Database::getInstance()->getDb()->prepare($sql);
$query->execute($param);
}
return $query;
}
};
$test = new Test();
$test->insert('tbl', ['id', 'name'], [1, 'first row']);
Online PHP test
Related
i have below query and it work fine.
but if the $where were array it will be fail,what's the solution?
public function update($tbl_name, $data = NULL, $where = NULL)
{
if ($data) {
$data_key = array_keys($data);
$where_key = array_keys($where);
$query = "UPDATE " . $data['db_table'] . " SET ";
foreach ($data_key as $key) {
$query .= "`" . $key . "` = '" . $data[$key] . "' ";
}
//todo fix that for multi where
$query.=" WHERE `".$where."`=".$where[''];
return $this->query($query);
}
return false;
}
You do realize that this is a rather dangerous thing that you are doing? Chances of your database getting nuked by someone entering something unexpected is way too high. As for the where clause, you can get help from is_array
if(is_array($criteria)) {
$query.=" WHERE `".$where." IN (" . join(",", $criteria) . ")";
}
else {
$query.=" WHERE `".$where." = '{$criteria}'";
}
The other issue here is that never ending string concatenation of this nature leads to very hard to trace bugs.
I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
As the title says, I'm having problems trying to use a pre-made wrapper class for PDO prepared statements. I'm not able to insert more than 5 values at a time in one row, this is the first time I have ever encountered this error in my programing days. Here is the class source code, and first attempt at implementation;
class db extends PDO {
private $error;
private $sql;
private $bind;
private $errorCallbackFunction;
private $errorMsgFormat;
public function __construct($dsn, $user="", $passwd="") {
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
parent::__construct($dsn, $user, $passwd, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
private function debug() {
if(!empty($this->errorCallbackFunction)) {
$error = array("Error" => $this->error);
if(!empty($this->sql))
$error["SQL Statement"] = $this->sql;
if(!empty($this->bind))
$error["Bind Parameters"] = trim(print_r($this->bind, true));
$backtrace = debug_backtrace();
if(!empty($backtrace)) {
foreach($backtrace as $info) {
if($info["file"] != __FILE__)
$error["Backtrace"] = $info["file"] . " at line " . $info["line"];
}
}
$msg = "";
if($this->errorMsgFormat == "html") {
if(!empty($error["Bind Parameters"]))
$error["Bind Parameters"] = "<pre>" . $error["Bind Parameters"] . "</pre>";
$css = trim(file_get_contents(dirname(__FILE__) . "/error.css"));
$msg .= '<style type="text/css">' . "\n" . $css . "\n</style>";
$msg .= "\n" . '<div class="db-error">' . "\n\t<h3>SQL Error</h3>";
foreach($error as $key => $val)
$msg .= "\n\t<label>" . $key . ":</label>" . $val;
$msg .= "\n\t</div>\n</div>";
}
elseif($this->errorMsgFormat == "text") {
$msg .= "SQL Error\n" . str_repeat("-", 50);
foreach($error as $key => $val)
$msg .= "\n\n$key:\n$val";
}
$func = $this->errorCallbackFunction;
$func($msg);
}
}
public function delete($table, $where, $bind="") {
$sql = "DELETE FROM " . $table . " WHERE " . $where . ";";
$this->run($sql, $bind);
}
private function filter($table, $info) {
$driver = $this->getAttribute(PDO::ATTR_DRIVER_NAME);
if($driver == 'sqlite') {
$sql = "PRAGMA table_info('" . $table . "');";
$key = "name";
}
elseif($driver == 'mysql') {
$sql = "DESCRIBE " . $table . ";";
$key = "Field";
}
else {
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';";
$key = "column_name";
}
if(false !== ($list = $this->run($sql))) {
$fields = array();
foreach($list as $record)
$fields[] = $record[$key];
return array_values(array_intersect($fields, array_keys($info)));
}
return array();
}
private function cleanup($bind) {
if(!is_array($bind)) {
if(!empty($bind))
$bind = array($bind);
else
$bind = array();
}
return $bind;
}
public function insert($table, $info) {
$fields = $this->filter($table, $info);
$sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ");";
$bind = array();
foreach($fields as $field)
$bind[":$field"] = $info[$field];
return $this->run($sql, $bind);
}
public function run($sql, $bind="") {
$this->sql = trim($sql);
$this->bind = $this->cleanup($bind);
$this->error = "";
try {
$pdostmt = $this->prepare($this->sql);
if($pdostmt->execute($this->bind) !== false) {
if(preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
elseif(preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql))
return $pdostmt->rowCount();
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
$this->debug();
return false;
}
}
public function select($table, $where="", $bind="", $fields="*") {
$sql = "SELECT " . $fields . " FROM " . $table;
if(!empty($where))
$sql .= " WHERE " . $where;
$sql .= ";";
return $this->run($sql, $bind);
}
public function setErrorCallbackFunction($errorCallbackFunction, $errorMsgFormat="html") {
//Variable functions for won't work with language constructs such as echo and print, so these are replaced with print_r.
if(in_array(strtolower($errorCallbackFunction), array("echo", "print")))
$errorCallbackFunction = "print_r";
if(function_exists($errorCallbackFunction)) {
$this->errorCallbackFunction = $errorCallbackFunction;
if(!in_array(strtolower($errorMsgFormat), array("html", "text")))
$errorMsgFormat = "html";
$this->errorMsgFormat = $errorMsgFormat;
}
}
public function update($table, $info, $where, $bind="") {
$fields = $this->filter($table, $info);
$fieldSize = sizeof($fields);
$sql = "UPDATE " . $table . " SET ";
for($f = 0; $f < $fieldSize; ++$f) {
if($f > 0)
$sql .= ", ";
$sql .= $fields[$f] . " = :update_" . $fields[$f];
}
$sql .= " WHERE " . $where . ";";
$bind = $this->cleanup($bind);
foreach($fields as $field)
$bind[":update_$field"] = $info[$field];
return $this->run($sql, $bind);
}
}
$db = new db("mysql:host=xxxx;dbname=xxxx", 'xxxxx', "xxxxx");
$insert = array(
"network" => "High",
"to" => "High",
"from" => "High",
"headerType" => "High",
"date" => "High",
"priority" => "High",
"content" => "High"
);
$db->insert("email_queue", $insert);
Any help would be appropriated!
I've tested this wrapper and it works with 6-fields inserts. Proof:
<?php
ini_set('display_errors', true);
require_once __DIR__.'/class.db.php';
$db = new db('mysql:host=127.0.0.1;dbname=test', 'root', '');
$db->setErrorCallbackFunction('echo', 'text');
$createTableQuery = <<<SQL
CREATE TABLE IF NOT EXISTS `q17224744` (
`name` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL DEFAULT '',
`gender` char(1) NOT NULL DEFAULT '',
`birthday` date NOT NULL,
`city` varchar(100) NOT NULL DEFAULT '',
`country` char(2) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL;
$db->run($createTableQuery);
$db->insert('q17224744', array(
'name' => 'John',
'lastname' => 'Doe',
'gender' => 'm',
'birthday' => '1971-12-03',
'city' => 'London',
'country' => 'GB',
));
I assume your problem is about incorrect values in your insert. Wrapper lib wont say you about errors if you not set error callback function. Try to enable debug output with setErrorCallbackFunction function as in example above.
P.S. This wrapper has counterintuitive behavior - by default it says nothing when exception coming. It would be much better by default throw exception and silent only when programmer set exception handler.
I am currently going through a nettuts.com tutorial on building a twitter clone and there they have a function for deleting rows from a database and they are using the query method but i tried converting the function to a prepared statement.However I get the Invalid parameter number: parameter was not defined error.Here is the code for the function
public function delete($table, $arr){
$query = "DELETE FROM " . $table;
$pref = "WHERE ";
foreach ($arr as $key => $value) {
$query .= $pref. $key . " = " . ":" . $key;
$pref = "AND ";
}
$query .= ";";
$result = $this->db->prepare($query);
$result->execute($arr);
}
$connect = new Model();
$connect->delete("ribbits", array("user_id" => 2,
"ribbit" => "trial ribbit"
));
can someone please tell me what I am doing wrong?Thank you!
When you pass your array to ->execute(), the keys need to have the : character before them (just like they appear in the SQL query).
So, in your delete function, build the SQL query like this:
public function delete($table, $arr){
$keys = array();
$values = array();
foreach($arr as $key => $value){
$keys[] = $key . " = :" . $key;
$values[":".$key] = $value;
}
$query = "DELETE FROM " . $table . " WHERE " . implode(" AND ", $keys);
$result = $this->db->prepare($query);
$result->execute($values);
}
Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch())
{
$x = array();
foreach($row as $key => $val)
{
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }