Insert MySql data from array [duplicate] - php

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;
}
}

Related

Binding Parameters Issues

I have looked at all of the other questions asked on SO and had no luck finding the problem in my code. I am trying to update a Database with an Update() method. My Insert() method is up and running, but I receive the above error when I run the code. It seems to be an error when binding my values. Would someone please give me some advice? Thank you.
<?php
class DB{
private static $_instance = null;
private $_pdo,$_query,$_error = false, $_result, $_count = 0, $_lastInsertID = null;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.DB_HOST.';port=3307;dbname='.DB_NAME , DB_USER, DB_PASSWORD);
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = []){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
//binds paramaters
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()){
$this->_result = $this->_query->fetchALL(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastInsertID = $this->_pdo->lastInsertId();
} else{
$this->error = true;
}
}
return $this;
}
public function insert($table,$fields=[]){
$fieldString = '';
$valueString = '';
$values = [];
foreach( $fields as $field => $value){
$fieldString .= '`'. $field . '`,';
$valueString .= '?,';
$values[] = $value;
}
$fieldString = rtrim($fieldString, ',');
$valueString = rtrim($valueString, ',');
$sql = "INSERT INTO {$table} ({$fieldString}) VALUES ({$valueString})";
if(!$this->query($sql, $values)->error()){
return true;
}else{
return false;
}
}
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
public function error(){
return $this->_error;
}
}
?>
<?php
class Home extends Controller{
public function __construct($controller,$action){
parent::__construct($controller, $action);
}
public function indexAction(){
//die('welcome to the home controller this is the index action.');
$db = DB::getInstance();
$fields = [
'fname'=> 'Jared',
'email'=>'JBowser#123.com'];
//$contacts = $db->insert('contacts',$fields); This is how we insert to our DB.
$contacts = $db->update('contacts',3, $fields); // This is how we update our DB.
$this->view->render('home/index'); ///path from views directory **
}
}
You dont load the values array in the Update method
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
$values[] = $value; // <<-- Added this line
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}

when i run my program it keeps throwing these errors

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);
}

insert form data with more columns into mysql database from php page using PDO

I have a HTML form which has more than 25 entries.
I know how to insert normal form data into MySQL database using PHP PDO. But I just want to know if there is any alternative way in which I can store the form entries to an array and insert the data into database using the array.
Because writing an insert statement for more than 25 columns is cumbersome.
You could always use a PDO wrapper class, I use the class below to handle most of my PDO queries:
class DB {
protected
// Return from mysql statement
$data = array(),
// Used for checking whether something was added to the JSON object and remove it if the table column doens't exist
$table_cols = array(),
// Storing the table name we are working with
$table = '';
protected static
// PDO connection to the DB
$_conn = null,
// The DB credentials retrieved from the ini file
$_credentials = array ();
private
$_id = -1,
$_keys = array(),
$_values = array(),
$_last_insert_id = -1,
$_results = array();
//
// PUBLIC FUNCTIONS
//
public function __construct () {
if (self::$_conn === null) {
self::setCredentials();
try {
self::$_conn = new \PDO("mysql:host=" . self::$_credentials['host'] . ";dbname=" . self::$_credentials['dbname'] , self::$_credentials['username'], self::$_credentials['password']);
} catch (\PDOException $e) {
DebugLog::instance('DB')->error($e, 'db_connection');
}
}
}
public function insert ($data) {
$data = $this->checkCols($data);
// Allows us to quickly clone data by removing the id and inserting as a new record
if (isset($data['id'])) {
unset($data['id']);
}
$this->data = $data;
$this->setDataBinding();
$sql = "INSERT INTO `" . self::$_credentials['dbname'] . "`.`{$this->table}` (`" . implode('`, `', $this->_keys) . "`) VALUES (:" . implode(', :', $this->_keys) . ");";
return $this->prepareAndExecute($sql);
}
public function update ($data) {
$data = $this->checkCols($data);
if (!isset($data['id'])) {
// Houston we have a problem, there needs to be an id to update a record
DebugLog::instance('DB')->error("No ID set for Update: " . implode(', ', array_keys($data)), 'db_id_' . $this->table);
} else {
// We need to unset the id because it shouldn't be in the data binding
// But we still hold onto it for the where clause
$id = $data['id'];
unset($data['id']);
$this->data = $data;
$this->setDataBinding();
$sql = "UPDATE `" . self::$_credentials['dbname'] . "`.`{$this->table}` SET ";
$query_string = "";
foreach ($this->_keys as $i => $key) {
$query_string .= "`{$key}` = :{$key}, ";
}
$query_string = trim($query_string);
if (substr($query_string, -1) === ',') {
$query_string = substr($query_string, 0, -1);
}
$sql .= $query_string . " WHERE `id` = '{$id}'";
return $this->prepareAndExecute($sql);
}
return false;
}
public function remove ($id) {
$this->rawQuery("DELETE FROM `{$this->table}` WHERE `id` = '{$id}';");
}
public function rawQuery ($sql) {
try {
$pdo = self::$_conn->query($sql);
$pdo->setFetchMode(\PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
DebugLog::instance('DB')->error($e, 'db_query_' . $this->table);
return array();
}
return $pdo->fetchAll();
}
//
// GETTERS
//
public function getColumns () {
return $this->table_cols;
}
public function getLastInsertID () {
return $this->_last_insert_id;
}
public function getRecord ($id) {
$this->_id = $id;
$response = $this->rawQuery("SELECT * FROM `{$this->table}` WHERE `id` = '{$id}'");
$this->_results = $response[0];
}
public function getResults () {
return $this->_results;
}
public function close () {
$this->setDefaults();
}
//
// PROTECTED FUNCTIONS
//
protected function initColumns () {
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . self::$_credentials['dbname'] . "' AND TABLE_NAME = '{$this->table}';";
$response = $this->rawQuery($sql);
if (!empty($response)) {
return $this->parseColumns($response);
}
return array();
}
//
// PRIVATE FUNCTIONS
//
private function setDataBinding () {
$this->_keys = array_keys($this->data);
foreach ($this->data as $k => $v) {
$this->_values[':' . $k] = $v;
}
}
private function prepareAndExecute ($sql) {
try {
$q = self::$_conn->prepare($sql);
$q->setFetchMode(\PDO::FETCH_ASSOC);
if ($q->execute($this->_values)) {
while ($r = $q->fetch()) {
$this->_results[] = $r;
}
$this->_last_insert_id = self::$_conn->lastInsertId();
return true;
} else {
DebugLog::instance('DB')->error('Failed to execute', 'db_' . $this->table);
}
} catch (\PDOException $e) {
DebugLog::instance('DB')->error($e, 'db_' . $this->table);
}
return false;
}
private function checkCols ($array) {
foreach ($array as $col => $val) {
if (!in_array($col, $this->table_cols)) {
unset($array[$col]);
}
}
return $array;
}
private static function setCredentials () {
// I actually use a config file here, instead of hard coding
self::$_credentials = array(
'host' => '',
'dbname' => '',
'username' => '',
'password' => ''
);
}
private function parseColumns ($cols) {
$array = array();
foreach ($cols as $index => $col_array) {
$array[] = $col_array['COLUMN_NAME'];
}
return $array;
}
private function setDefaults () {
$this->data = array();
$this->table_cols = array();
$this->table = '';
self::$_conn = null;
$this->_keys = array();
$this->_values = array();
$this->_last_insert_id = -1;
$this->_results = array();
}
}
Then for each table, create a class that extends the class above. For example, lets say we have a users table:
class UsersTable extends DB {
public function __construct () {
// Parent constructor creates the DB connection
parent::__construct();
// Now let's set the desired table based on this class
$this->table = "users";
// Set the table columns, for mysql column validation
$this->table_cols = $this->initColumns();
}
}
Usage is than as simple as:
$table = new UsersTable();
$table->insert($record);
As long as your array has the 25 values in the same order as the table you can use unnamed parameters and lazy binding See PDO info
$sql ="INSERT INTO table_name VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)";
$stmt = $dbh->prepare($sql);
$stmt->execute($array);

Is this mysqli wrapper secure against SQL injection?

Here is how a wrapper looks like:
<?php
Class mysqliwrapper{
protected $_mysqli;
protected $_debug;
public function __construct($host, $username, $password, $database, $debug) {
$this->_mysqli = new mysqli($host, $username, $password, $database);
$this->_debug = (bool) $debug;
if (mysqli_connect_errno()) {
if ($this->_debug) {
echo mysqli_connect_error();
debug_print_backtrace();
}
return false;
}
return true;
}
public function q($query) {
if ($query = $this->_mysqli->prepare($query)) {
if (func_num_args() > 1) {
$x = func_get_args();
$args = array_merge(array(func_get_arg(1)),
array_slice($x, 2));
$args_ref = array();
foreach($args as $k => &$arg) {
$args_ref[$k] = &$arg;
}
call_user_func_array(array($query, 'bind_param'), $args_ref);
}
$query->execute();
if ($query->errno) {
if ($this->_debug) {
echo mysqli_error($this->_mysqli);
debug_print_backtrace();
}
return false;
}
if ($query->affected_rows > -1) {
return $query->affected_rows;
}
$params = array();
$meta = $query->result_metadata();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($query, 'bind_result'), $params);
$result = array();
while ($query->fetch()) {
$r = array();
foreach ($row as $key => $val) {
$r[$key] = $val;
}
$result[] = $r;
}
$query->close();
return $result;
} else {
if ($this->_debug) {
echo $this->_mysqli->error;
debug_print_backtrace();
}
return false;
}
}
public function handle() {
return $this->_mysqli;
}
}
?>
This works fine:
$w = new mysqliwrapper("localhost","root","","testdb",1);
$r = $w->q("SELECT * FROM `testdb_news` WHERE `id`=? AND `lang`=?","is",16,'en');
However, this does not:
$r = $w->q("INSERT INTO `testdb_news` ('lang','title','content','date') VALUES (?,?,?,?)","ssss","en","NewTitle","NewContent",mktime());
Why? Should I be using ?-s only for SELECT statements? And go for insert like this?
$r = $w->q("INSERT INTO `testdb_news` (lang,title,content,date) VALUES ('en','newTitle','newContent','".mktime()."')");
Is this secure? Is this class actually secure? Thanks!
safe against injections. see this question which has similar questions Parameterized Query

MySQL last entry PHP sorted by date

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.

Categories