so I have this function below. At the very bottom I am returning $this->conn->lastInsertId(). If i'm not mistaken this should be correct.
FILE #1
public function insertData($table, $qty, $data){
$errors = "";
$columns = $this->fetchColumnNames($table);
$column_list = implode(', ', $columns);
$values = array_fill(0, $qty, '?');
$value_list = implode(', ', $values);
$q = "INSERT INTO $table ($column_list) VALUES ($value_list)";
$stmt = $this->conn->prepare($q);
for($i = 1; $i < $qty + 1; $i++){
foreach($data as $key => $val){
if($key == $columns[$i-1]){
try{
if(is_numeric($val)){
$stmt->bindValue($i, $val, PDO::PARAM_INT);
}else{
$stmt->bindValue($i, $val, PDO::PARAM_STR);
}
}catch(PDOException $e){
print $e->getMessage();
}
}
}
}
try{
$stmt->execute();
}catch(PDOException $e){
$errors .= $e->getMessage();
print $errors;
}
return $this->conn->lastInsertId();
}
So moving on to my main file, I have the following line of code
FILE #2
error_reporting(E_ALL);
ini_set('display_errors', 1);
include '../../inc/config.php';
include 'ProcessApplication/ProcessApplication.php';
include 'ProcessApplication/ProcessApplicationQuery.php';
$processor = new ProcessApplicationQuery($CONN);
$processor->insertData("full_application", 17, $general);
if($processor->getConn()){
list($general, $phones) = $processor->processGeneralInfo($_REQUEST['general_information']);
print $processor->insertData("full_application", 17, $general);
}
If I remove the return line from File #1 and just print in File #2 nothing happens, and the program inserts into the database like so. For some reason this return line is causing the entire program to fail and 404. It's very odd I have never had this occur, so why would this return line cause this error?
===UPDATE===
So even weirder I have added the follow items to my files
FILE #1
public function insertData($table, $qty, $data){
$errors = "";
$columns = $this->fetchColumnNames($table);
$column_list = implode(', ', $columns);
$values = array_fill(0, $qty, '?');
$value_list = implode(', ', $values);
$q = "INSERT INTO $table ($column_list) VALUES ($value_list)";
$stmt = $this->conn->prepare($q);
for($i = 1; $i < $qty + 1; $i++){
foreach($data as $key => $val){
if($key == $columns[$i-1]){
try{
if(is_numeric($val)){
$stmt->bindValue($i, $val, PDO::PARAM_INT);
}else{
$stmt->bindValue($i, $val, PDO::PARAM_STR);
}
}catch(PDOException $e){
print $e->getMessage();
}
}
}
}
try{
$stmt->execute();
}catch(PDOException $e){
$errors .= $e->getMessage();
print $errors;
}
}
public function getApplicationid(){
$query = "SELECT id FROM eagle.full_application ORDER BY create_date DESC LIMIT 1";
$id = null;
foreach($this->conn->query($query) as $row){
$id = $row['id'];
}
return $id;
}
FILE #2
error_reporting(E_ALL);
ini_set('display_errors', 1);
include '../../inc/config.php';
include 'ProcessApplication/ProcessApplication.php';
include 'ProcessApplication/ProcessApplicationQuery.php';
$processor = new ProcessApplicationQuery($CONN);
$processor->insertData("full_application", 17, $general);
if($processor->getConn()){
list($general, $phones) = $processor->processGeneralInfo($_REQUEST['general_information']);
$processor->insertData("full_application", 17, $general);
echo $processor->getApplicationId();
}
I added a new method, and attempted to print it. I still get the error in which the files 404. It is really odd. I hope this helps out on the solution, because I am stumped.
Related
Warning: move_uploaded_file(C:\mpp\htdocs\ch09\data2018_03_22_11_38_23_0.gif): failed to open stream: No such file or directory in C:\xampp\htdocs\ch09\concert\insert.php on line 101
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpE1D0.tmp' to 'C:\mpp\htdocs\ch09\data2018_03_22_11_38_23_0.gif' in C:\xampp\htdocs\ch09\concert\insert.php on line 101
$upload_dir = "C:\xampp\htdocs\ch09\data";
I think file_name is set correctly, but uploaded_dir isn't.
\xa is missed, despite being typed correctly. Why?
<?php session_start(); ?>
<meta charset="utf-8">
<?php
$userid = $_SESSION["userid"];
if(isset($_REQUEST["page"]))
{
$page = $_REQUEST["page"];
}else{
$page = 1;
}
if(!$userid) {
echo("
<script>
window.alert('로그인 후 이용해 주세요.')
history.go(-1)
</script>
");
exit;
}
if(isset($_REQUEST["mode"])){
$mode = $_REQUEST["mode"];
}else{
$mode ="";
}
if(isset($_REQUEST["num"])){
$num = $_REQUEST["num"];
}else{
$num = "";
}
if(isset($_REQUEST["html_ok"])) //checkbox는 체크해야 변수명 전달됨
$html_ok = $_REQUEST["html_ok"];
else
$html_ok = "";
$subject = $_REQUEST["subject"];
$content = $_REQUEST["content"];
// 다중 파일 업로드
$files = $_FILES["upfile"];
$count = count($files["name"]);
$upload_dir = "C:\xampp\htdocs\ch09\data\\";
$regist_day = date("Y-m-d (H:i)"); // 현재의 '년-월-일-시-분'을 저장
/* 단일 파일 업로드
$upfile_name = $_FILES["upfile"]["name"];
$upfile_tmp_name = $_FILES["upfile"]["tmp_name"];
$upfile_type = $_FILES["upfile"]["type"];
$upfile_size = $_FILES["upfile"]["size"];
$upfile_error = $_FILES["upfile"]["error"];
*/
for ($i=0; $i<$count; $i++)
{
$upfile_name[$i] = $files["name"][$i];
$upfile_tmp_name[$i] = $files["tmp_name"][$i];
$upfile_type[$i] = $files["type"][$i];
$upfile_size[$i] = $files["size"][$i];
$upfile_error[$i] = $files["error"][$i];
$file = explode(".", $upfile_name[$i]);
$file_name = $file[0];
$file_ext = $file[1];
if (!$upfile_error[$i])
{
$new_file_name = date("Y_m_d_H_i_s");
$new_file_name = $new_file_name."_".$i;
$copied_file_name[$i] = $new_file_name.".".$file_ext;
$uploaded_file[$i] = $upload_dir.$copied_file_name[$i];
if( $upfile_size[$i] > 500000 ) {
echo("
<script>
alert('업로드 파일 크기가 지정된 용량(500KB)을 초과합니다!<br>파일 크기를 체크해주세요! ');
history.go(-1)
</script>
");
exit;
}
if ( ($upfile_type[$i] != "image/gif") &&
($upfile_type[$i] != "image/jpeg")
)
{
echo("
<script>
alert('JPG와 GIF 이미지 파일만 업로드 가능합니다!');
history.go(-1)
</script>
");
exit;
}
if (!move_uploaded_file($upfile_tmp_name[$i], $uploaded_file[$i]))
{
print $upfile_tmp_name[$i];
print $uploaded_file[$i];
echo("
<script>
alert('파일을 지정한 디렉토리에 복사하는데 실패했습니다.$upfile_tmp_name[$i] AANNDD $uploaded_file[$i]');
history.go(-1)
</script>
");
exit;
}
}
}
include_once ''; "../lib/dbconn.php"; // dconn.php 파일을 불러옴
$pdo = db_connect();
if ($mode=="modify")
{
$num_checked = count($_POST['del_file']);
$position = $_POST['del_file'];
for($i=0; $i<$num_checked; $i++) // delete checked item
{
$index = $position[$i];
$del_ok[$index] = "y";
}
try{
$sql = "select * from phptest.concert where num=?"; // get target record
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $num, PDO::PARAM_STR);
$stmh->execute();
$row = $stmh->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $ex) {
print "오류: ".$ex->getMessage();
}
for ($i=0; $i<$count; $i++) // update DB with the value of file input box
{
$field_org_name = "file_name_".$i;
$field_real_name = "file_copied_".$i;
$org_name_value = $upfile_name[$i];
$org_real_value = $copied_file_name[$i];
if ($del_ok[$i] == "y")
{
$delete_field = "file_copied_".$i;
$delete_name = $row[$delete_field];
$delete_path = "./data/".$delete_name;
unlink($delete_path);
try{
$sql = "update phptest.concert set $field_org_name = ?, $field_real_name = ? where num=?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $org_name_value, PDO::PARAM_STR);
$stmh->bindValue(2, $org_real_value, PDO::PARAM_STR);
$stmh->bindValue(3, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
print "오류: ".$ex->getMessage();
}
}
else
{
if (!$upfile_error[$i])
{
try{
$pdo->beginTransaction();
$sql = "update phptest.concert set $field_org_name = ?, $field_real_name = ?, where num = ?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $org_name_value, PDO::PARAM_STR);
$stmh->bindValue(2, $org_real_value, PDO::PARAM_STR);
$stmh->bindValue(3, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
print "오류: ".$ex->getMessage();
}
}
}
}
try{
$pdo->beginTransaction();
$sql = "update phptest.concert set subject=?, content=?, is_html=? where num=?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $subject, PDO::PARAM_STR);
$stmh->bindValue(2, $content, PDO::PARAM_STR);
$stmh->bindValue(3, $html_ok, PDO::PARAM_STR);
$stmh->bindValue(4, $num, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
print "오류: ".$ex->getMessage();
}
} //기존내용을 수정하는 경우..
else //신규 추가하는 경우.
{
if ($html_ok=="y")
{
$is_html = "y";
}
else
{
$is_html = "";
$content = htmlspecialchars($content);
}
try{
$pdo->beginTransaction();
$sql = "insert into phptest.concert(id, name, nick, subject, content, regist_day, hit, is_html, ";
$sql .= " file_name_0, file_name_1, file_name_2, file_copied_0, file_copied_1, file_copied_2) ";
$sql .= "values(?,?,?,?,?,now(),0,?,?,?,?,?,?,?)";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $_SESSION["userid"],PDO::PARAM_STR);
$stmh->bindValue(2, $_SESSION["name"],PDO::PARAM_STR);
$stmh->bindValue(3, $_SESSION["nick"],PDO::PARAM_STR);
$stmh->bindValue(4, $subject, PDO::PARAM_STR);
$stmh->bindValue(5, $content,PDO::PARAM_STR);
$stmh->bindValue(6, $is_html,PDO::PARAM_STR);
$stmh->bindValue(7, $upfile_name[0],PDO::PARAM_STR);
$stmh->bindValue(8, $upfile_name[1],PDO::PARAM_STR);
$stmh->bindValue(9, $upfile_name[2],PDO::PARAM_STR);
$stmh->bindValue(10, $copied_file_name[0],PDO::PARAM_STR);
$stmh->bindValue(11, $copied_file_name[1],PDO::PARAM_STR);
$stmh->bindValue(12, $copied_file_name[2],PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
print "오류: ".$ex->getMessage();
}
}
echo "
<script>
location.href = 'list.php?page=$page';
</script>
";
?>
$upload_dir = "C:\xampp\htdocs\ch09\data\";
you missed a backslash.
hi guys here is my update function it takes some parameters and eveluates them if they are integer or string after that process the values and throws for query sentence...
public function update ($table, $cols, $values, $addition) {
$db = $this->connect();
$i = 0;
$update = '';
if ((is_array($cols)) && (is_array($values))) {
foreach ($cols as $a) {
if (!is_int($values[$i])) {
$update = $a.'="'.$values[$i].'",';
} else {
$update = $a.'='.$values[$i].',';
}
$i++;
}
$update = substr($update, 0, -1);
} else {
if (!is_int($values)) {
$update = $cols.'="'.$values.'",';
} else {
$update = $cols.'='.$values.',';
}
}
echo "update ".$table." set ".$update." ".$addition."<br>";
try {
$sql = $db->prepare("update ".$table." set ".$update." ".$addition);
$sql->execute();
} catch (PDOException $e) {
print $e->getMessage();
}
$db = null;
}
and here are the parameters and the sql query
$this->db->update("brands", "car_count", $brandCarCount[0]+1, "where brand = '".$brand."'");
update brands set car_count=2, where brand = 'alfa_romeo'
i really do not understand what happens, i can not find the problem. it works for other inserting selecting or deleting functions.
i need help!
That is the relevant line which removes the trailing comma:
$update = rtrim($update,',');
and this is the full code:
public function update ($table, $cols, $values, $addition) {
$db = $this->connect();
$i = 0;
$update = '';
if ((is_array($cols)) && (is_array($values))) {
foreach ($cols as $a) {
if (!is_int($values[$i])) {
$update = $a.'="'.$values[$i].'",';
} else {
$update = $a.'='.$values[$i].',';
}
$i++;
}
} else {
if (!is_int($values)) {
$update = $cols.'="'.$values.'",';
} else {
$update = $cols.'='.$values.',';
}
}
$update = rtrim($update,',');
echo "update ".$table." set ".$update." ".$addition."<br>";
try {
$sql = $db->prepare("update ".$table." set ".$update." ".$addition);
$sql->execute();
} catch (PDOException $e) {
print $e->getMessage();
}
$db = null;
}
I have a php script which fill tables in my sql database. The problem is that it overwrites the tables each time I run it and I just want to add the datas at the end. I took inspiration from an existing script that I modify and I don't understand all it contains.
Here is my code :
<?php
try {
session_start();
require_once('./lib/demo/php/functions.php');
$db = getConnection();
$colMap = array(
0 => "LIBELLE",
1 => "DESCRIPTION",
2 => "CODE"
);
if (isset($_GET['data']) && $_GET['data']) {
$select = $db -> prepare('DELETE FROM COMPETENCES');
$select2 = $db -> prepare('DELETE FROM DESCRIPTION');
$select -> execute();
$select2 -> execute();
for ($r = 0, $rlen = count($_GET['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_GET['data'][$r]); $c < $clen; $c++) {
if (!isset($colMap[$c]) && !isset($colMap[$c])) {
continue;
}
$newVal = $_GET['data'][$r][$c];
$select = $db -> prepare('SELECT ID FROM COMPETENCES WHERE ID=? LIMIT 1');
$select2 = $db -> prepare('SELECT ID FROM DESCRIPTION WHERE ID=? LIMIT 1');
$select -> execute(array($rowId));
$select2 -> execute(array($rowId));
if ($row = $select->fetch() && $row = $select2->fetch()) {
$query = $db->prepare('UPDATE COMPETENCES SET `' . $colMap[$c] . '` = :newVal WHERE ID = :id');
$query2 = $db->prepare('UPDATE DESCRIPTION SET `' . $colMap[$c] . '` = :newVal2 WHERE ID = :id2');
} else {
$query = $db->prepare('INSERT INTO COMPETENCES (ID, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
$query2 = $db->prepare('INSERT INTO DESCRIPTION (ID, `' . $colMap[$c] . '`) VALUES(:id2, :newVal2)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query2->bindValue(':id2', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query2->bindValue(':newVal2', $newVal, PDO::PARAM_STR);
$query->execute();
$query2->execute();
}
}
}
$out = array(
'result' => 'ok'
);
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
}
I thought that remove the DELETE queries will fix the problem but the script doesn't work at all. I think the issue comes from the ids but I don't find where.
The datas are taken from a grid created with the javascript plugin Handsontable.
Can you help me please? I really need this script.
My script still doesn't work but I removed all what I found useless. Now, nothing happens at all in the database even if the new code seems to be more appropriate.
Here is the new :
<?php
try {
session_start();
require_once('./lib/demo/php/functions.php');
$db = getConnection();
mysql_set_charset('utf8', $db);
$colMap = array(
0 => 'LIBELLE',
1 => 'DESCRIPTION',
2 => 'CODE'
);
if (isset($_GET['data']) && $_GET['data']) {
for ($r = 0, $rlen = count($_GET['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_GET['data'][$r]); $c < $clen; $c++){
if (!isset($colMap[$c])) {
continue;
}
$newVal = $_GET['data'][$r][$c];
$query = $db->prepare('INSERT INTO COMPETENCES ("'.$colMap[$c].'") VALUES(:newVal)');
$query2 = $db->prepare('INSERT INTO DESCRIPTION ("'.$colMap[$c].'") VALUES(:newVal2)');
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query2->bindValue(':newVal2', $newVal, PDO::PARAM_STR);
$query->execute();
$query2->execute();
}
}
}
$out = array('result' => 'ok');
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
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 found this http://net.tutsplus.com/tutorials/php/the-problem-with-phps-prepared-statements/
and it works really good to have it in a seperate php file which my other files calls to with a query as argument.
Is it possible to make something similar with other queries like insert and update?
This is the updated example:
$params is an array.
function insertToDB($params, $db) { //Pass array and db
$fields = array();
$conn = new mysqli('localhost', 'root', 'root', 'db') or die('XXX');
$stmt = $conn->stmt_init();
$stmt->prepare("SELECT * FROM ".$db);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$fields[] = $field->name;
}
$fields = implode(", ", $fields);
$placeholders = implode(',', array_fill(0, count($params), '?'));
$types = '';
foreach($params as $value) {
$types.= substr(strtolower(gettype($value)), 0, 1);
}
$ins = "INSERT INTO MYDB (".$fields.") VALUES (".$placeholders.")";
$bind_names[] = $types;
for ($i = 0; $i < count($params); $i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
if ($stmt->prepare($ins)) {
call_user_func_array(array($stmt,'bind_param'),$bind_names);
$insresult = $stmt->execute();
}
return $insresult;
$stmt->close();
}