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();
}
?>
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.
Having trouble with the following code. It's not giving an error nor does it output anything. The problem is with the multipleReg part. If I remove bindValue multiplereg and replace :multiplereg in the select statement with $multipleReg it works. I have a feeling it's cause it's not an array but I've tried executing it as an array which has not worked. Any help would be much appreciated.
<?php
header('Content-Type: application/json; Charset=UTF-8');
require "includes/config.php";
$offset = $_GET["offset"];
$region = trim($_GET["region"]);
$regionExp = explode(",", $region);
$tag = $_GET["tag"];
$data = array();
foreach ($regionExp as $singleReg)
$queryKeyword[] = "'%$singleReg%'";
$multipleReg = implode(' OR region LIKE ', $queryKeyword);
try {
$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag) AND
(region LIKE :multipleReg) ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";
$stmt = $db->prepare($sql);
$stmt->bindValue(':tag', $tag);
$stmt->bindValue(':multipleReg', $multipleReg);
$stmt->bindValue(':offsetNr', (int) $offset, PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
$stmt->closeCursor();
exit();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
You could create an array to prepare your SQL string and another to store placeholders :
$qstr = [];
foreach ($regionExp as $k => $singleReg) {
$queryKeyword[':lk'.$k] = "%$singleReg%";
$qstr[] = 'region LIKE :lk'.$k ;
}
Then your SQL query (don't forget to check if $qstr is not empty) :
$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
AND (".implode(' OR ', $qstr).")
ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";
And to bind :
// Instead of : $stmt->bindValue(':multipleReg', $multipleReg);
foreach ($queryKeyword as $k => $v) $stmt->bindValue($k, $v);
EDIT The full code :
$offset = $_GET["offset"];
$region = trim($_GET["region"]);
$regionExp = explode(",", $region);
$tag = $_GET["tag"];
// This part has changed :
$qstr = [];
foreach ($regionExp as $k => $singleReg) {
$queryKeyword[':lk'.$k] = "%$singleReg%";
$qstr[] = 'region LIKE :lk'.$k ;
}
try {
// The SQL string changed
$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
AND (".implode(' OR ', $qstr).")
ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";
// Debug (see below)
// echo $sql."\n" ;
// print_r($queryKeyword);
$stmt = $db->prepare($sql);
$stmt->bindValue(':tag', $tag);
// The line below replaced
foreach ($queryKeyword as $k => $v) $stmt->bindValue($k, $v);
$stmt->bindValue(':offsetNr', (int) $offset, PDO::PARAM_INT);
$stmt->execute();
$data = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
$stmt->closeCursor();
exit();
} catch(PDOException $e) {
echo $e->getMessage();
}
The SQL and dump will look like this :
SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
AND (region LIKE :lk0 OR region LIKE :lk1)
ORDER BY id DESC LIMIT 10 OFFSET :offsetNr
Array
(
[:lk0] => %test%
[:lk1] => %test2%
)
If I use the following statement, my code is working well:
$statement = $this->pdo->prepare($sql)->execute();
But if I use the following statements, my code doesn't work:
$statement = $this->pdo->prepare($sql);
$statement->execute();
Does anyone have an idea, what I'm doing wrong or why this is so?
Here my complete code:
public function deleteUser($pid_user){
/* DESCRIPTION
* delete an user an all his data
*
* PARAMETERS
*
* EXAMPLE
* deleteUser();
*/
try {
//begin transaction
$this->pdo->beginTransaction();
//define all tables to delete all entries from the overgiven user id
//name = name of the table
//column = column to identify the users entries
$tables = array();
$tables[0]["name"] = "snsho_bittrex_apikey";
$tables[0]["column"] = "fk_user";
$tables[1]["name"] = "snsho_bittrex_balances";
$tables[1]["column"] = "fk_user";
$tables[2]["name"] = "snsho_bittrex_deposit_history";
$tables[2]["column"] = "fk_user";
$tables[3]["name"] = "snsho_bittrex_order_history";
$tables[3]["column"] = "fk_user";
$tables[4]["name"] = "snsho_bittrex_withdrawal_history";
$tables[4]["column"] = "fk_user";
$tables[5]["name"] = "snsho_user_settings";
$tables[5]["column"] = "fk_user";
$tables[6]["name"] = "snsho_user";
$tables[6]["column"] = "pid_user";
//do the queries
$sql = '';
foreach($tables as $key => $table){
$sql .= 'DELETE FROM ' . $table["name"] . ' WHERE ' . $table["column"] . ' = ' . $pid_user . ';';
}
//$statement = $this->pdo->prepare($sql)->execute();
$statement = $this->pdo->prepare($sql);
$statement->execute();
if($this->pdo->commit()){
echo "commited";
}else{
echo "commit failed";
}
return TRUE;
} catch (Exception $e) {
$this->adminMessages->setSingleError("Failed: " . $e->getMessage());
$this->pdo->rollBack();
return FALSE;
}
}
Try the execute without the assignment.
$this->pdo->prepare($sql)->execute();
This only returns a true or false.
Iam bringing my old code (vunerable in so many ways) to new standards with PDO.
The problem is, i'm getting no return, no error message, no nothing.
What my code do is the following: Makes a query to the DB and if there is any result ($resultado) it creates an order of the data in arrays.
Can please someone give me a help?
I tried the Array approach and the Object approach, no donuts :/
Old Code:
$sql_code =
"SELECT news_id, news_title, news_date, news_resume
FROM news
WHERE news_show = 'S'
ORDER BY news_date DESC
";
$result = mysql_query($sql_code);
if ($result) {
$rows = mysql_num_rows($result);
for ($i=0; $i<$rows; $i++) {
$aID[] = mysql_result($result, $i, "news_id");
$aTitle[] = mysql_result($result, $i, "news_title");
$aDate[] = mysql_result($result, $i, "news_date");
$aResume[] = mysql_result($result, $i, "news_resume");
}
}
?>
New Code that doesnt work:
try
{
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpasswd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT news_id, news_title, news_date, news_resume
FROM news
WHERE news_show = :newsS
ORDER BY news_date DESC");
$stmt->execute(array('newsS' => 'S'));
while ($sql_code = $stmt->fetchall(PDO::FETCH_ASSOC))
{
$result = mysql_query($sql_code);
}
}
catch(PDOException $e)
{
echo "Error:". $e->getMessage();
}
$result = mysql_query($sql_code);
if ($result)
{
$rows = mysql_num_rows($result);
for ($i=0; $i<$rows; $i++)
{
$aID[] = mysql_result($result, $i, "news_id");
$aTitle[] = mysql_result($result, $i, "news_title");
$aDate[] = mysql_result($result, $i, "news_date");
$aResume[] = mysql_result($result, $i, "news_resume");
}
}
?>
If you're using PDO, you don't call any mysql_XXX functions, you have to use PDO methods for everything.
$stmt->fetchAll() returns all the rows of the results. To process it, just use a foreach loop.
try
{
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpasswd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT news_id, news_title, news_date, news_resume
FROM news
WHERE news_show = :newsS
ORDER BY news_date DESC");
$stmt->execute(array('newsS' => 'S'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$aId[] = $row['news_id'];
$aTitle[] = $row['news_title'];
$aDate[] = $row['news_date'];
$aResume[] = $row['news_resume'];
}
}
catch(PDOException $e)
{
echo "Error:". $e->getMessage();
}
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.