Warning: Missing argument 1 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 2 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 3 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 4 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Notice: Undefined variable: host in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: username in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: password in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: db in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
This is my MysqlDB.php code
<?php
class MysqlDB {
protected $_mysql;
protected $_where = array();
protected $_query;
protected $_paramTypeList;
public function __construct ($host, $username, $password, $db) {
$this->_mysql = new mysqli($host, $username, $password, $db)
or die('There was a problem connecting to the database');
}
public function query($query)
{
$this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery();
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
* A convenient SELECT * function.
*
* #param string $tableName The name of the database table to work with.
* #param int $numRows The number of rows total to return.
* #return array Contains the returned rows from the select query.
*/
public function get($tableName, $numRows = NULL)
{
$this->_query = "SELECT * FROM $tableName";
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
*
* #param <string $tableName The name of the table.
* #param array $insertData Data containing information for inserting into the DB.
* #return boolean Boolean indicating whether the insert query was completed succesfully.
*/
public function insert($tableName, $insertData)
{
$this->_query = "INSERT into $tableName";
$stmt = $this->_buildQuery(NULL, $insertData);
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function update($tableName, $tableData)
{
$this->_query = "UPDATE $tableName SET ";
$stmt = $this->_buildQuery(NULL, $tableData);
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function delete($tableName) {
$this->_query = "DELETE FROM $tableName";
$stmt = $this->_buildQuery();
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function where($whereProp, $whereValue)
{
$this->_where[$whereProp] = $whereValue;
}
protected function _determineType($item)
{
switch (gettype($item)) {
case 'string':
return 's';
break;
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
}
protected function _buildQuery($numRows = NULL, $tableData = false)
{
$hasTableData = null;
if (gettype($tableData) === 'array') {
$hasTableData = true;
}
// Did the user call the "where" method?
if (!empty($this->_where)) {
$keys = array_keys($this->_where);
$where_prop = $keys[0];
$where_value = $this->_where[$where_prop];
// if update data was passed, filter through
// and create the SQL query, accordingly.
if ($hasTableData) {
$i = 1;
$pos = strpos($this->_query, 'UPDATE');
if ( $pos !== false) {
foreach ($tableData as $prop => $value) {
// determines what data type the item is, for binding purposes.
$this->_paramTypeList .= $this->_determineType($value);
// prepares the reset of the SQL query.
if ($i === count($tableData)) {
$this->_query .= $prop . " = ? WHERE " . $where_prop . "= " . $where_value;
} else {
$this->_query .= $prop . ' = ?, ';
}
$i++;
}
}
} else {
$this->_paramTypeList = $this->_determineType($where_value);
$this->_query .= " WHERE " . $where_prop . "= ?";
}
}
if ($hasTableData) {
$pos = strpos($this->_query, 'INSERT');
if ($pos !== false) {
$keys = array_keys($tableData);
$values = array_values($tableData);
$num = count($keys);
foreach ($values as $key => $val) {
$values[$key] = "'{$val}'";
$this->_paramTypeList .= $this->_determineType($val);
}
$this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES(';
while ($num !== 0) {
($num !== 1) ? $this->_query .= '?, ' : $this->_query .= '?)';
$num--;
}
}
}
if (isset($numRows)) {
$this->_query .= " LIMIT " . (int) $numRows;
}
$stmt = $this->_prepareQuery();
if ($hasTableData) {
$args = array();
$args[] = $this->_paramTypeList;
foreach ($tableData as $prop => $val) {
$args[] = &$tableData[$prop];
}
call_user_func_array(array($stmt, 'bind_param'), $args);
} else {
if ($this->_where)
$stmt->bind_param($this->_paramTypeList, $where_value);
}
return $stmt;
}
protected function _dynamicBindResults($stmt)
{
$parameters = array();
$results = array();
$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;
}
return $results;
}
protected function _prepareQuery()
{
if (!$stmt = $this->_mysql->prepare($this->_query)) {
trigger_error("Problem preparing query", E_USER_ERROR);
}
return $stmt;
}
public function __destruct()
{
$this->_mysql->close();
}
}
?>
and i'm calling a function insert() through index.php
<?php
ob_start();
session_start();
require_once("phpinclude/include/membersite_config.php");
require_once("phpinclude/include/MySqlDB.php");
$DB = new MysqlDB('172.90.13.97','king','mi*****hhh','kxxxx_database');
if (isset($_GET['action'])){$action = htmlentities($_GET['action']);}
else{$action = NULL;}
$mysqldb = new MysqlDB();
?>
<?php if($action=='add_cart'){?>
<?php $data=array($arrival, $departure, $result, $roomID, $category_price); $table='tb_cart';?>
<?php $this->mysqldb->insert($table, $data); ?>
<?php }?>
Problem is in this line
$mysqldb = new MysqlDB();
The constructor requries arguments which are not passed. You need to pass $host, $username, $password, $db to constructor.
Your code acutally makes no sense. You could use $DB instead of creating new object. You also use $this->mysqldb in no object context. There are plenty of errors in your code.
To fix:
Remove this line $mysqldb = new MysqlDB();
Change <?php $this->mysqldb->insert($table, $data); ?> to $DB->insert($table, $data);
Script should +- look like:
<?php
ob_start();
session_start();
require_once("phpinclude/include/membersite_config.php");
require_once("phpinclude/include/MySqlDB.php");
$DB = new MysqlDB('172.90.13.97','king','mi*****hhh','kxxxx_database');
$action = !empty($_GET['action']) ? htmlentities($_GET['action']) : null;
if ($action == 'add_cart') {
$data = array(
'arrival' => $arrival,
'departure' => $departure,
'result' => $result,
'roomID' => $roomID,
'category_price' => $category_price
);
$DB->insert('tb_cart', $data);
}
Related
I want to run a PHP website on localhost. I set up the server and imported the database but getting the following error...I Downloaded the website from the client c_panel public HTML folder and exported the database. I have to do changes in front-end and I have no idea of PHP(I am a Node.js developer, so if you can reference it with that to help me.). I just want to start the website locally, so that I can do the front-end changes. I'm getting the following error in my app/Models.php
Fatal error: Uncaught Error: Non-static method SB\Response::redirect() cannot be called statically in /Applications/MAMP/htdocs/app/src/sb/Model.php:475 Stack trace: #0 /Applications/MAMP/htdocs/app/src/sb/Model.php(12): SB\Model->db_error(Object(PDOException)) #1 /Applications/MAMP/htdocs/app/src/sb/DB.php(21): SB\Model->__construct() #2 /Applications/MAMP/htdocs/app/src/sb/DB.php(28): SB\DB->__construct() #3 /Applications/MAMP/htdocs/route/web.php(20): SB\DB::table('blogs') #4 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(66): require('/Applications/M...') #5 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(56): composerRequire6b60b5a5888bbd230d022934044bba82('8dab41e234cc925...', '/Applications/M...') #6 /Applications/MAMP/htdocs/vendor/autoload.php(7): ComposerAutoloaderInit6b60b5a5888bbd230d022934044bba82::getLoader() #7 /Applications/MAMP/htdocs/index.php(10): require_once('/Applications/M...') #8 {main} thrown in /Applications/MAMP/htdocs/app/src/sb/Model.php on line 475
Modal.php file:
<?php
namespace SB;
use PDO;
use PDOException;
class Model {
private $pdo = null;
public function __construct() {
try {
$this->pdo = new PDO(DSN, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
} catch (PDOException $e) {
$this->db_error($e);
}
}
/**
* Create table
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
function create_table($table, $data) {
$sql = "CREATE TABLE IF NOT EXISTS $table (";
$num = count($data);
$sql .= "`_id` bigint(20) PRIMARY KEY NOT NULL AUTO_INCREMENT, ";
for ($i = 0; $i < $num; $i++):
$sql .= $data[$i] . ", ";
endfor;
$sql .= "`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
$sql .="`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);";
$this->pdo->exec($sql);
return '<big>This code was executed. Please check manually if no table is created for the database<big> <br> '.$sql ;
}
/**
* insert
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function add($table, $data) {
ksort($data);
$this->pdo->beginTransaction();
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$s = $sth->execute();
$this->pdo->commit();
return $s;
}
/**
* insert with get auto increment _id
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function addGetId($table, $data) {
ksort($data);
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$res = $sth->execute();
if($res) {
return $this->pdo->lastInsertId();
} else {
return $res;
}
}
/**
* update
* #param string $table A name of table to insert into
* #param string $data An associative array
* #param string $where the WHERE query part
*/
public function modify($table, $data,$where,$where_data = []) {
ksort($data);
$fieldDetails = NULL;
foreach ($data as $key => $value) {
$fieldDetails .= "`$key`=:$key,";
}
$fieldDetails = rtrim($fieldDetails, ',');
$sth = $this->pdo->prepare("UPDATE `$table` SET $fieldDetails $where");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$val = rtrim($val," ");
$sth->bindValue(":$key", $val);
}
foreach ($where_data as $key => $value) {
$sth->bindValue(":".$key, $value);
}
return $sth->execute();
}
/**
* Fetch all
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_all($table,$cols = '*',$where = false, $type = null,$where_data = []) {
$statement = '';
if(!$where) {
$statement = "SELECT $cols FROM $table";
} else {
$statement = "SELECT $cols FROM $table $where";
}
$pre = $this->pdo->prepare($statement);
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM') {
return $pre->fetchAll(PDO::FETCH_NUM);
}
else if($type == 1 || $type == 'ASSOC') {
return $pre->fetchAll(PDO::FETCH_ASSOC);
} else {
return $pre->fetchAll(PDO::FETCH_OBJ);
}
}
/**
* Fetch one
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_one($table,$cols = '*',$where = false, $type = null,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM')
return $pre->fetch(PDO::FETCH_NUM);
else if($type == 1 || $type == 'ASSOC' )
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_some($table, $cols, $where, $operator) {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' :'. $key.', ' ;
}else{
$fields .= $key.' '.$operator.' :'. $key;
} $i++;
endforeach;
$pre = $this->pdo->prepare("SELECT $cols FROM $table WHERE $fields");
foreach ($where as $key => $value):
$pre->bindValue(":$key", $value);
endforeach;
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
/**
* Fetch row
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_row($table, $cols = '*', $where = false, $operator = '=') {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}else{
if(!is_array($where)){
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
} else {
return $this->pdo->fetch_some($table, $cols, $where, $operator);
}
}
}
/**
* Fetch rows
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_rows($table, $cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
public function fetch_one_assoc($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
public function fetch_one_object($table,$cols = '*',$where = false,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
if(!empty($where_data))
$pre->execute($where_data);
else
$pre->execute();
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_all_assoc($table,$cols = '*',$where = false) {
if(!$where) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch_all_object($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
e = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
/**
* Fetch type
* #param string $table A name of table to get all data
* #param string $where the WHERE query part
*/
public function fetch_type($table, $type = PDO::FETCH_OBJ, $limit = false,$cols = '*',$where = 1) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
if(!$limit){
return $pre->fetchAll($type);
}else{
return $pre->fetch($type);
}
}
public function fetch_sql($sql,$type = PDO::FETCH_OBJ) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
return $pre->fetchAll($type);
}
public function delete_row($table,$where,$operator = '=') {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' ? AND ' ;
} else {
$fields .= $key.' '.$operator.' ?';
} $i++;
endforeach;
$pre = $this->pdo->prepare("DELETE FROM $table WHERE $fields");
foreach ($where as $key => $value):
$a[] = $value;
endforeach;
return $pre->execute($a);
}
protected function deleteData($table,$where,$where_data=[]) {
$pre = $this->pdo->prepare("DELETE FROM $table $where");
foreach ($where_data as $key => $value) {
$pre->bindValue(":".$key, $value);
}
return $pre->execute();
}
public function customeDate($date=false) {
$date=date_create("$date");
return date_format($date,"dS-M-Y");
}
public function get_json($table) {
$rows = $this->pdo->fetch_all_assoc($table);
$out = "";
foreach($rows as $row) {
$cols = array_keys($row);
if ($out != "") {
$out .= ",";
}
foreach($cols as $i=>$col){
if($i==0){
$out .= '{"'.$col.'":"' . $row[$col] . '",';
} else {
$out .= '"'.$col.'":"' . $row[$col] . '",';
}
if($i==count($cols)-1) {
$out .= '"'.$col.'":"'. $row[$col] . '"}';
}
}
}
$out ='{"records":['.$out.']}';
return $out;
}
protected function connection_close() {
$this->pdo = null;
}
private function db_error($e) {
if(IS_DEBUGG):
die('
<br><h2><br>
<center>!Config Error.<br>
<small style="color:gray">Setup your .env file. Read Following Error</small>
</center></h2>
<h3>.env file variables</h3>
<ul>
<li>DB_HOST="Enter database host name"</li>
<li>DB_USER="Enter here database user name"</li>
<li>DB_PASS="enter Database Password"</li>
<li>DB_NAME="enter Database Name"</li>
<li>DB_DRIVER="DB DIRVER like `mysql`"</li>
</ul>
<br><div style="padding:50px;"><small style="color:lightgray"><pre>' . $e . '</pre></small></div>'
);
else:
return Response::redirect('404');
endif;
}
public function fetch_qry($sql,$one=0) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
if($one)
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
}
Update this line of code
public static function redirect($endpoint){
#header('Location:'.URL.$endpoint);
}
Or, you can create an instance of this class.
$response = new Response();
Then call this method.
$response->redirect('404');
I'm passing an array of values through a bind_param function, the way I do this is like this:
<?php
class Query{
private $_mysqli;
/*
* #param object $mysqli
*/
public function __construct($mysqli)
{
$this->_mysqli = $mysqli;
}
/*
* #param string query
* #param string $types
* #param array $values
*/
public function read($query = "", $type = "", $params = array())
{
$query = ($query === "") ? die("Read error: Query") : $query;
$type = ($type === "") ? die("Read error: Type") : array($type);
$params = (count($params) == 0) ? die("Read error: Params") : $params;
$values = array();
foreach($params as $key => $value) {
$values[$key] = &$params[$key];
}
if ($stmt = $this->_mysqli->prepare($query))
{
call_user_func_array(array($stmt, "bind_param"), array_merge($type, $values));
$stmt->execute();
$fields = array();
for($i=0; $i<count($params); $i++){
$fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);
$array = array();
while($data = $stmt->fetch())
{
$array[] = $data;
}
return $array;
}
}
}
This is the way I use my function
<?php
//$mysqli is the mysqli connection
$query = new Query($mysqli);
$query_str = "SELECT * FROM users WHERE voornaam = ? AND achternaam = ?";
$types = "ss";
$params = array("Firstname", "Lastname");
var_dump($query->read($query_str, $types, $params));
?>
The part where I get stucked is:
<?php
$fields = array();
for($i=0; $i<count($params); $i++){
$fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);
$array = array();
while($data = $stmt->fetch())
{
$array[] = $data;
}
?>
Im not sure where it goes wrong, I have a feeling at the while loop.
hope you guys can help me making this function working :)
you are binding results , so you don't need to assign your fetched data to new variable,
mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables
to a prepared statement for result storage
while you are using call_user_func_array , and according to this comment, your loop :
while($data = $stmt->fetch())
{
$array[] = $data;
}
may be as follows:
while($stmt->fetch())
{
// params which you had bind it into bindParams
$array[] = $params;
}
I have the following query.
$mysqldb = mysqlidb_class();
$query = "select * from post where idx < ?"
Then I bind the parameter and execute.
$bindvariable = array();
array_push($bindvariable, $post_photoidx);
array_push($bindvariable, $post_idx);
$res = $mysqldb->rawQuery($query, $bindvariable);
Then I get the following error.
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement
But when I change the query like below, the error disappears.
$query = "select * from post where idx = ?"
What am I doing wrong here?
Here is the class I use for the mysql query
<?php
class MysqliDb
{
......
public function rawQuery ($query, $bindParams = null, $sanitize = true)
{
$this->_query = $query;
if ($sanitize)
$this->_query = filter_var ($query, FILTER_SANITIZE_STRING,
FILTER_FLAG_NO_ENCODE_QUOTES);
$stmt = $this->_prepareQuery();
if (is_array($bindParams) === true) {
$params = array(''); // Create the empty 0 index
foreach ($bindParams as $prop => $val) {
$params[0] .= $this->_determineType($val);
array_push($params, $bindParams[$prop]);
}
call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));
}
$stmt->execute();
$this->_stmtError = $stmt->error;
$this->reset();
return $this->_dynamicBindResults($stmt);
}
......
protected function _buildQuery($numRows = null, $tableData = null)
{
$this->_buildJoin();
$this->_buildTableData ($tableData);
$this->_buildWhere();
$this->_buildGroupBy();
$this->_buildOrderBy();
$this->_buildLimit ($numRows);
$this->_lastQuery = $this->replacePlaceHolders ($this->_query, $this->_bindParams);
if ($this->isSubQuery)
return;
// Prepare query
$stmt = $this->_prepareQuery();
// Bind parameters to statement if any
if (count ($this->_bindParams) > 1)
call_user_func_array(array($stmt, 'bind_param'), $this->refValues($this->_bindParams));
return $stmt;
}
protected function _prepareQuery()
{
if (!$stmt = $this->_mysqli->prepare($this->_query)) {
trigger_error("Problem preparing query ($this->_query) " . $this->_mysqli->error, E_USER_ERROR);
}
return $stmt;
}
protected function refValues($arr)
{
//Reference is required for PHP 5.3+
if (strnatcmp(phpversion(), '5.3') >= 0) {
$refs = array();
foreach ($arr as $key => $value) {
$refs[$key] = & $arr[$key];
}
return $refs;
}
return $arr;
}
......
} // END class
You mightn't use array(2).
Instead, use
$sql = "select * from post where idx < :i";
$stmt->bindparam("i", 2);
$stmt->execute();
or use
$array = array($something,$else,$whatever);
$sql = "select * from post where idx < ?";
$stmt->bindparam("i", $array[2]);
$stmt->execute();
It looks like you are not preparing your query before biding parameters to it.
$sql = "SELECT * FROM post WHERE idx < ?";
if($stmt = $stmt->prepare($sql)) {
$stmt->bind_param('i', 2);
$stmt->execute();
}
Santize filters ruined my SQL query.
I have changed the source to the following to resolve the problem.
$mysqldb->rawQuery($query, $bindvariable, false);
This question already has an answer here:
Mysqli prepared statements build INSERT query dynamically from array
(1 answer)
Closed 6 months ago.
<?php
$files=array(name1,name2,name3,);
$conn = new mysqli($host, $user, $pass, $name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO parmi_files (name)
VALUES ('$files')"; ///// -problem is here
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I want to insert each value from array to MySql row, please solve it out.
Iterate through the items in the array and add them individually:
foreach ($arrayWithValues as $key=>$value) {
$sql = "INSERT INTO parmi_files (name) VALUES ('$value')";
mysqli_query($conn, $sql);
}
Something like this to insert multiple records at once:
$files = array('name1', 'name2', 'name3');
// ...
$filesMap = implode(',', array_map(function($value) {
return "('" . $conn->real_escape_string($value) . "')";
}, $files));
$sql = "INSERT INTO parmi_files (name) VALUES $filesMap";
You could use a PDO abstraction layer for this
I have made a class for this in the past
It uses: PDO, bound parameters, prepared statements
and it inserts everything in one sql query and the insert looks like this:
$db->insertRows('test_table', $default_row, $rows);
The full code
(which might seem a bit long, but makes sense if you read it) including the code for the connection would look like:
<?php
// Establish connection (on demand)
$db = new PdoHelper(function(){
$db_server = 'localhost';
$db_port= '3306';
$db_name = 'your_database';
$db_user = 'your_username';
$db_pass = 'your_password';
$dsn = 'mysql:host='.$db_server.';dbname='.$db_name.';port='.$db_port;
$driver_options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
$dbh = new PDO( $dsn, $db_user, $db_pass, $driver_options );
return $dbh;
});
// Make a blank sample to have default values for row keys
$default_row = array(
'a'=>null,
'b'=>null,
'c'=>null,
);
// The rows that we want to insert, with columns in the wrong order and nonsense
$rows = array(
array(
'b'=>'a2',
'c'=>'a3',
),
array(
'c'=>'b3',
'b'=>'b2',
),
array(
'b'=>'c2',
'c'=>'c3',
'nonsense'=>'boo',
),
);
// The actual insert query
// INSERT INTO `test_table` (`a`,`b`,`c`) VALUES (null,'a2','a3'), (null,'b2','b3'), (null,'c2','c3')
$db->insertRows('test_table', $default_row, $rows);
// The class that does it all
class PdoHelper {
private $db, $factory;
public function __construct($factory)
{
$this->factory = $factory;
}
public function connect()
{
$cb = $this->factory;
$this->db = $cb();
}
public function release()
{
$this->db = null;
}
public function implyConnect()
{
if(!$this->db){
$this->connect();
}
}
public function begin()
{
$this->implyConnect();
if($this->db instanceof PDO){
$this->db->beginTransaction();
}
}
public function commit()
{
$this->implyConnect();
if($this->db instanceof PDO){
$this->db->commit();
}
}
public function prepare($sql, $data=null, $callback=null)
{
$err = null;
$flat_data = array();
if($data){
$flat_data = self::flatten($data);
$sql = preg_replace_callback('/\?/isu', function($v) use (&$data) {
$val = array_shift($data);
if(is_array($val)){
return self::arrayToPlaceholder($val);
}
return '?';
}, $sql);
}
$this->implyConnect();
if($this->db instanceof PDO){
$stmt = $this->db->prepare($sql);
if($stmt instanceof PDOStatement){
$i = 1;
foreach($flat_data as $v) {
if(is_int($v)){
// workaround for a PDO bug with LIMIT ?,?
$stmt->bindValue($i++, $v, PDO::PARAM_INT);
}else{
$stmt->bindValue($i++, $v, PDO::PARAM_STR);
}
}
}
}
if($callback){
return call_user_func_array($callback, array($stmt));
}
return $stmt;
}
public function query($sql)
{
$res = false;
$args = func_get_args();
$data = array();
$callback = null;
if(isset($args[2])){
$data = $args[1];
$callback = $args[2];
}else
if(isset($args[1])){
if(is_callable($args[1])){
$callback = $args[1];
}else{
$data = $args[1];
}
}
$this->implyConnect();
$stmt = $this->prepare($sql, $data);
$res = $stmt->execute();
if($res && $callback && is_callable($callback)){
return call_user_func_array($callback, array($stmt, $this->db));
}
return $stmt;
}
// Helper functions
public function insertRows($table, $default, $rows=array(), $flag=null, $chunk_size=500)
{
if(empty($rows)){
return null;
}
$chunks = array_chunk($rows, $chunk_size);
foreach($chunks as $rows){
$data = array();
$data[] = $this->extend($default, $rows);
// http://stackoverflow.com/questions/1542627/escaping-column-names-in-pdo-statements
$flag = strtolower($flag);
$flags = array(
'ignore'=>'INSERT IGNORE INTO ',
'replace'=>'REPLACE INTO ',
);
$cols = array();
foreach($default as $k=>$v){
$k = str_replace('`', '``', $k);
$cols[] = '`'.$k.'`';
}
$sql = (isset($flags[$flag])?$flags[$flag]:'INSERT INTO ').$table.' ('.implode(',', $cols).') VALUES ?';
if($flag==='update'){
$cols = array();
foreach($default as $k=>$v){
$k = str_replace('`', '``', $k);
$cols[] = '`'.$k.'`=VALUE('.$k.')';
}
$sql .= ' ON DUPLICATE KEY UPDATE '.implode(', ', $cols);
}
$res = $this->query($sql, $data);
if(!$res){
return $res;
}
}
return $res;
}
public function insertRow($table, $default, $row, $flag=null)
{
$rows = array($row);
return $this->insertRows($table, $default, $rows, $flag);
}
// Helper functions
public static function extend($set, $rows)
{
foreach($rows as $k=>$v){
$v = array_intersect_key($v, $set);
$rows[$k] = array_replace($set, $v);
}
return $rows;
}
public static function flatten($x)
{
$d = array();
if(is_array($x)){
foreach($x as $k=>$v){
$d = array_merge($d, self::flatten($v));
}
}else{
$d[] = $x;
}
return $d;
}
public static function arrayToPlaceholder($array, $timeZone=null) {
return implode(',', array_map(function($v) use($timeZone){
if(is_array($v)){
return '('.self::arrayToPlaceholder($v, $timeZone).')';
}
return '?';
}, $array));
}
public function arrayToList($array, $timeZone=null) {
return implode(',',array_map(function($v) use($timeZone){
if(is_array($v)){
return '('.self::arrayToList($v, $timeZone).')';
}
$this->implyConnect();
return $this->escape($v);
},$array));
}
public function escape($val, $stringifyObjects=false, $timeZone=false) {
if(is_null($val)) return 'NULL';
if(is_bool($val)) return ($val) ? 'true' : 'false';
if(is_int($val)) return (string)$val;
if(is_float($val)) return (string)$val;
if (is_array($val)) {
return $this->arrayToList($val, $timeZone);
}
if(is_callable($val)){ return null; } // TODO
$val = preg_replace_callback('/[\0\n\r\b\t\\\'\"\x1a]/um', function($s) {
switch($s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\".$s;
}
}, $val);
return $this->db->Quote($val);
}
// Debug functions
public function getSQL($sql, $data){
foreach($data as $k=>$v){
if(is_array($v)){
$data[$k] = self::arrayToList($v);
}else{
$this->implyConnect();
$data[$k] = $this->escape($v);
}
}
$sql = preg_replace_callback('/\?/', function($match) use(&$data)
{
return array_shift($data);
}, $sql);
return $sql;
}
}
I want to display the latest entry from a MySQL database with PHP.
The table (bird_playlog) looks like that:
interpret: Tiny Dancers
title: Bonfire Of The Night
date: 2012-06-11 14:30:58
Screenshot:
The MySQL Connect script:
<?php
class mw_sql{
private $host;
private $user;
private $pass;
private $db;
private $connection = null;
public $connected = false;
public function __construct($data){
$this->host = $data['host'];
$this->user = $data['user'];
$this->pass = $data['pass'];
$this->db = $data['db'];
}
public function __destruct(){
if($this->connected) mysql_close($this->connection);
}
public function connect(){
$this->connection = mysql_connect($this->host, $this->user, $this->pass, true);
if(!$this->connection){
echo '<pre>MySQL connect failed</pre>';
$this->connected = false;
}else{
if(#mysql_select_db($this->db, $this->connection)){
$this->connected = true;
}else{
echo '<pre>MySQL select db failed</pre>';
echo '<pre>'.mysql_error($this->connection).'</pre>';
$this->connected = false;
}
}
return $this->connected;
}
public function select($table, $fields=null, $key=null, $where=null, $sort=null, $sort_dir='ASC', $limit=null){
$cols = (is_array($fields) && $fields != null) ? mysql_real_escape_string(implode(', ', $fields), $this->connection) : '*';
$where_clause = ($where != null) ? ' WHERE '.$where : '';
$sort_clause = ($sort != null) ? ' ORDER BY '.$sort.' '.$sort_dir : '';
$limit_clause = ($limit != null) ? ' LIMIT '.$limit : '';
$query = "SELECT ".$cols." FROM ".$table.$where_clause.$sort_clause.$limit_clause;
$res = #mysql_query($query, $this->connection);
if(!$res){
return false;
}else{
$data = array();
if(mysql_num_rows($res) > 0){
while($dat = mysql_fetch_assoc($res)){
if($key == null) array_push($data, $dat);
else $data[$dat[$key]] = $dat;
}
}
return $data;
}
}
public function query($query){
$res = #mysql_query($query, $this->connection);
if(!$res){
echo mysql_error();
return false;
}else{
return $res;
}
}
public function insert($table, $fields, $values){
$vals = array();
foreach($values as $value){
array_push($vals, mysql_real_escape_string($value, $this->connection));
}
$query = "INSERT INTO ".$table." (".mysql_real_escape_string(implode(', ', $fields), $this->connection).") VALUES ('".implode("', '", $vals)."')";
$res = #mysql_query($query, $this->connection);
if(!$res){
pre(mysql_error($this->connection));
return false;
}
return true;
}
public function update($table, $fields, $values, $where, $error_no_rows=true){
$update = array();
foreach($fields as $key => $value){
if($values[$key] == 'increment'){
array_push($update, $value."=".$value.'+1');
}else{
array_push($update, mysql_real_escape_string($value, $this->connection)."='".mysql_real_escape_string($values[$key], $this->connection)."'");
}
}
$query = "UPDATE ".$table." SET ".implode(', ', $update)." WHERE ".$where;
$res = #mysql_query($query, $this->connection);
if(!$res){
pre(mysql_error($this->connection));
return false;
}
if(mysql_affected_rows($this->connection) == 0 && $error_no_rows){
return false;
}
return true;
}
public function delete($table, $where){
$query = "DELETE FROM ".$table." WHERE ".$where;
echo '<pre>'.$query.'</pre>';
$res = #mysql_query($query, $this->connection);
if(!$res) return false;
return true;
}
} ?>
And the script which shows the latest entry looks like this:
<?php
require_once('mw_sql.class.php');
$cuelist_db_conf = array(
'host' => 'w00b2ffc.kasserver.com',
'user' => 'd0144421',
'pass' => '****',
'db' => 'd0144421',
'table' => 'bird_playlog'
);
$cuelist_db = new mw_sql($cuelist_db_conf);
$cuelist_db->connect();
$last_track = $cuelist_db->select('bird_playlog', array('interpret', 'title'), 'date', 'DESC', 1);
echo $last_track[0]['interpret']; ?>
But the script doesn't show $last_track[0]['interpret'];, so what is wrong? I have no error message...
Thanks for your help! David
UPDATE:
This works:
$con = mysql_connect("w00b2ffc.kasserver.com","d0144421","****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("d0144421", $con);
$last_track = mysql_query("SELECT * FROM bird_playlog ORDER BY date DESC LIMIT 1");
while($row = mysql_fetch_assoc($last_track)) {
extract($row);
}
I think you should pass null if you don't want.
Because the function originally have 7 parameters to accept and you are passing only 5 so it will not take as you want. It seems that $key you dont want than at for $key you should pass null.
Because if you pass 5 parameter than function will take it as the first 5 parameters and the last two will be taken as default even if you don't want.
I hope this will solve your problem.