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.
Related
I have one problem it's kinda strange, I have one sale receipt which contains 66 rows of data, now I want to update a receipt when I fetch data from the table is shows all record perfectly. but when I try to update rows in table it works fine till record number 58, but after that it gives me "undefined offset 58" error, it will bet update rows after index 58. Please can anyone help me it's been two days I am working on it but have not got a solution.
this is my code for sending the data to Ajax page using .serializeArray()
$('#submit').on('click',function(){
if($('#partnumber_1').val()=='' ||
($('.quantitytak').val()==0&& $('.quantity').val()==0)){
swal("هەموو خانەکان داخل بکە","هەلە","warning");
}else{
$.ajax({
url: "edit_sale_ajax.php?request=2",
type: 'post',
data: $('#form1').serializeArray(),
success: function (data) {
swal(data);
$( "#invoice" ).prop( "disabled", false );
window.reload();
}
});
}
return false;
});
and this is my code for updating record in the table
if($_GET['request']==2){
$date = $_POST['order_date'];
$cus_name = $_POST['cus_name'];
$recipt_no = $_POST['recipt_no'];
$total_all = $_POST['total_all'];
$total_loan=$_POST['total_load'];
$discount=$_POST['discount'];
$totalafterdis=$_POST['totalafterdis'];
$paid_money = $_POST['money_paid'];
$loan_now=$_POST['loan_now'];
$partnumber = $_POST['partnumber'];
$pricekarton = $_POST['pricekarton'];
$pricetdana= $_POST['pricedana'];
$product_id = $_POST['product_id'];
$number_inkarton = $_POST['danaynawkarton'];
$total_dana = $_POST['totaldana'];
$kartonbefor=$_POST['kartonbefore'];
$danabefor = $_POST['danabefore'];
$hamwbefore = $_POST['hamwbefore'];
$sale_de_id = $_POST['detail_id'];
$prev_id = $_POST['pro_id'];
$quantity = $_POST['quantity'];
$quantitytak = $_POST['quantitytak'];
$sub_total = $_POST['total'];
$remain_purchase = $_POST['remain_purchase'];
$sale_id=$_POST['sale_id'];
$today=date('Y-m-d h:i:sa');
$loan_id=$_POST['loan_id'];
$user_id=$_SESSION['userid'];
$row=$_POST['row'];
try {
$flag = true;
$message = "";
$dbh->beginTransaction();
$sql_update_sale = "update sale_tbl set
sale_reciept_no=?,sale_date=?,total_befordis=?,
discoun =?, total_afterdic=?, sale_paid_money=?,
customer_id=?,user_id=? where sale_id=$sale_id";
$query = $dbh->prepare($sql_update_sale);
$query->bindParam(1, $recipt_no, PDO::PARAM_STR);
$query->bindParam(2, $date, PDO::PARAM_STR);
$query->bindParam(3, $total_all, PDO::PARAM_STR);
$query->bindParam(4, $discount, PDO::PARAM_STR);
$query->bindParam(5, $totalafterdis,PDO::PARAM_STR
);
$query->bindParam(6, $paid_money, PDO::PARAM_STR);
$query->bindParam(7, $cus_name, PDO::PARAM_STR);
$query->bindParam(8, $user_id, PDO::PARAM_STR);
if (!$query->execute()) {
$flag = false;
print_r($dbh->errorInfo());
$message .= "error la update sale" .
}
for ($i = 1; $i <= $row; $i++) {
var_dump($partnumber[$i]);
$sql_update_sale_detail = "update sale_detail_tbl set
product_id='$product_id[$i]',pricekarton='$pricekarton[$i]'
, pricedana= '$pricetdana[$i]', sale_kartonquantity=
'$quantity[$i]', sale_danaquantity='$quantitytak[$i]',
sub_total='$sub_total[$i]' where
sale_id='$sale_id' and sale_de_id='$sale_de_id[$i]' ";
$statement = $dbh->prepare($sql_update_sale_detail);
if (!$statement->execute()) {
$flag = false;
$m = print_r($dbh->errorInfo());
$message .= "error la update sale detail<br>" .
}
//checking if product exist in stock table
$check_product = "SELECT product_id FROM stock_tbl
where product_id='$product_id[$i]'";
$pro_check_ex = $dbh->prepare($check_product);
$pro_check_ex->execute();
if ($pro_check_ex->rowCount() >= 1) {
$hamwfater[$i] = intval($quantity[$i]) *
intval($number_inkarton[$i]) +
intval($quantitytak[$i]);
//if product still same product
if ($prev_id[$i] == $product_id[$i]) {
$kartontaza[$i] = $quantity[$i] -
$kartonbefor[$i];
$danataza[$i] = $quantitytak[$i] -
$danabefor[$i];
$hamwtaza[$i] = $hamwfater[$i] -
$hamwbefore[$i];
$update_stock2 = "UPDATE stock_tbl SET
quantitystock_karton=(quantitystock_karton-
$kartontaza[$i]), quantitystock_tak=
(quantitystock_tak-$danataza[$i]),
total_quantity=(total_quantity-
$hamwtaza[$i]),last_update='$date',
pricekarton_instock= $pricekarton[$i],
pricetak_instock=$pricetdana[$i] where
product_id=$product_id[$i]";
$exe_update2= $dbh->prepare($update_stock2);
if (!$exe_update2->execute()) {
$flag = false;
$message .= "error la update stock yaksanan";
}
} else {
//if product changes in the list
$kartontaza[$i] = $quantity[$i];
$danataza [$i]= $quantitytak[$i];
$hamwtaza [$i]= $hamwfater[$i];
$update_stock1 = "UPDATE stock_tbl SET
quantitystock_karton=quantitystock_karton+
$kartonbefor[$i],quantitystock_tak=quantitystock_tak
+$danabefor[$i],total_quantity=
total_quantity+$hamwbefore[$i],last_update=$date
where product_id=$prev_id[$i]";
$exe_update1 = $dbh->prepare($update_stock1);
if (!$exe_update1->execute()) {
$flag = false;
$message .= "error la update stocki producti
peshtr" . print_r($exe_update1->errorInfo());
}
$update_stock = "UPDATE stock_tbl SET
quantitystock_karton=quantitystock_karton-
$kartontaza[$i], quantitystock_tak=quantitystock_tak-
$danataza[$i], total_quantity=
total_quantity-$hamwtaza[$i],last_update=$date,
pricekarton_instock=$pricekarton[$i], pricetak_instock=
$pricetdana[$i] where product_id=$product_id[$i]";
$exe_update = $dbh->prepare($update_stock);
if (!$exe_update->execute()) {
$flag = false;
$message .= "error la update stock";
}
}
}
}
$sql_update_company_loan = "update customer_load_tbl
set customer_id=?,sale_id=?,total_money=?,paid_money=?
,remain_money=?,total_remain=?,cus_pay_date=? where
cus_loan_id=?";
$query_update_com = $dbh-
>prepare($sql_update_company_loan);
$query_update_com->bindParam(1, $cus_name,
PDO::PARAM_STR);
$query_update_com->bindParam(2, $sale_id,
PDO::PARAM_STR);
query_update_com->bindParam(3, $total_all,
PDO::PARAM_STR);
$query_update_com->bindParam(4,
$paid_money, PDO::PARAM_STR);
$query_update_com->bindParam(5,$remain_purchase,
PDO::PARAM_STR);
$query_update_com->bindParam(6, $loan_now,
PDO::PARAM_STR);
$query_update_com->bindParam(7, $today,
PDO::PARAM_STR);
$query_update_com->bindParam(8, $loan_id,
PDO::PARAM_STR);
if (!$query_update_com->execute()) {
$flag = false;
$message .= "error la update customer loan" .
print_r($query_update_com->errorInfo());
}
//end of all statements
if ($flag) {
$dbh->commit();
$message.="گۆرانکاری بەسەرکەوتووی ";
} else {
echo $message;
echo "\nPDO::errorInfo():\n";
//print_r($dbh->errorInfo());
//echo '<div class="alert alert-danger">Ops..,
Something wrong</div>';
}
} catch (PDOException $e) {
// Failed to insert the order into the database so
we rollback any changes
throw $e;
}
echo $message;
}
Please can anyone help I really appreciated it.
The below PHP code gets all data from a MySQL DB and sends it to an android app. I want the data to be paginated.
ALL DATA PHP CODE
<?php
include 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$HostName;dbname=$DatabaseName", $HostUser, $HostPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `tiffa`");
$stmt->execute();
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($data);
} catch (PDOException $e) {
print "Connection failed! Please Try Again Or Contact Us: " . $e->getMessage() . "<br/>";
die();
$conn = null;
}
POJO/DATA MODEL CLASS
public class ImageList {
#SerializedName("image1name")
private String name;
#SerializedName("county")
private String county;
#SerializedName("image1URL")
private String imageurl;
#SerializedName("image2URL")
private String image2url;
public ImageList(String name,String county,String imageurl, String image2url) {
this.name = name;
this.county = county;
this.imageurl = imageurl;
this.image2url = image2url;
}
public String getName() {
return name;
}
String getCounty() {
return county;
}
String getImageurl() {
return imageurl;
}
String getImage2url() {
return image2url;
}
}
I have tried to pass the page_number and item_count (which come from the app) but I can't seem to get it. Here is my tried PHP Code. The POJO remains the same.
<?php
$page_number = $_GET['page_number'];
$item_count = $_GET['item_count'];
$from = $page_number * $item_count - ($item_count - 1);
$to = $page_number * $item_count;
$data = array();
include 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$HostName;dbname=$DatabaseName", $HostUser, $HostPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `tiffa`");
$stmt->execute();
if ($to > $stmt) {
array_push($response, array('status' => 'end'));
echo json_encode($response);
} else {
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($data);
}
array_push($response, array('images' => $images));
sleep(2);
echo json_encode($response);
catch (PDOException $e) {
print "Connection failed! Please Try Again Or Contact Us: " . $e->getMessage() . "<br/>";
die();
$conn = null;
}
Thanks for the leads #Nigel Ren. I resolved this by
<?php
$page_number = $_GET['page_no'];
$item_count = $_GET['item_cnt'];
$from = $page_number*$item_count - ($item_count-1);
$to = $page_number*$item_count;
$response=array();
$stats=array();
include 'dbconfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$total = mysqli_num_rows(mysqli_query($conn, "SELECT id from db1"));
if($to>$total)
{
array_push($response,array('status'=>'end'));
echo json_encode($response);
}
else
{
array_push($response,array('status'=>'ok'));
$count = $from;
$images = array();
$start = ($page - 1) * $limit;
//SQL query to fetch data of a range
$sql = "SELECT * from db1 limit $start, $item_count";
//Getting result
$result = mysqli_query($conn,$sql);
//Adding results to an array
$res = array();
while($row = mysqli_fetch_array($result))
{
$image122 = $row['image122'];
$image_path = $image122;
array_push($images,array('id'=>$count,'image_path'=>$image_path));
$count = $count+1;
}
array_push($response,array('images'=>$images));
sleep(2);
echo json_encode($response);
}
?>
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();
}
?>
I'm reasonably new with AJAX but have had some good help, both on reading up and asking specific questions on here. This one is for the php backend...
I have a load of code like this:
if(isset($_POST['shortTitle'])) {
$userInput = ucwords($_POST['shortTitle']);
if(trim($userInput) == "") { $userInput = NULL; }
try {
$stmt = $conn->prepare("UPDATE $database.app_$applicationKey SET `shortTitle` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
$stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
$stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
$stmt->execute();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
$report_shortTitle = array();
if($userInput == NULL) {
$report_shortTitle['errorText_shortTitle'] = "This field cannot be left blank";
$report_shortTitle['resultImg_shortTitle'] = "<img src=\"./gfx/form_boo.gif\" class=\"resultImg\" alt=\"✘\" title=\"✘\">";
} else {
$report_shortTitle['errorText_shortTitle'] = NULL;
$report_shortTitle['resultImg_shortTitle'] = "<img src=\"./gfx/form_yay.gif\" class=\"resultImg\" alt=\"✔\" title=\"✔\">";
}
echo json_encode($report_shortTitle);
}
// groupName
if(isset($_POST['groupName'])) {
$userInput = ucwords($_POST['groupName']);
if(trim($userInput) == "") { $userInput = NULL; }
try {
$stmt = $conn->prepare("UPDATE $database.app_$applicationKey SET `groupName` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
$stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
$stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
$stmt->execute();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
$report_groupName = array();
if($userInput == NULL) {
$report_groupName['errorText_groupName'] = "This field cannot be left blank";
$report_groupName['resultImg_groupName'] = "<img src=\"./gfx/form_boo.gif\" class=\"resultImg\" alt=\"✘\" title=\"✘\">";
} else {
$report_groupName['errorText_groupName'] = NULL;
$report_groupName['resultImg_groupName'] = "<img src=\"./gfx/form_yay.gif\" class=\"resultImg\" alt=\"✔\" title=\"✔\">";
}
echo json_encode($report_groupName);
}
Which all works, however it would be nice if I could simply use one blob of code for everything that is actioned in the same style - the data post from the input fields all the way through to the DB insertion are always consistent - is shortTitle, groupName etc. Obviously the
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
line will be different so I guess I'll need different pieces of code, for "PDO::PARAM_STR, 64", PDO::PARAM_INT, 11" etc but that is ok. How can I work it so that I only need one bit of code. I'm sure it must be possible, but I am unsure how to achieve this. Feedback appreciated!
You can use array for dependable parts and use a foreach.
$names = ['groupName', 'shortTitle'];
foreach($names as $name){
if(isset($_POST[$name])) {
$userInput = ucwords($_POST[$name]);
if(trim($userInput) == "") { $userInput = NULL; }
try {
$stmt = $conn->prepare("UPDATE $database.app_$applicationKey SET '$name' = :userinput, `lastModified` = :time WHERE `appID` = :appid");
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
$stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
$stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
$stmt->execute();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
$report_name = array();
if($userInput == NULL) {
$report_name['errorText_'.$name] = "This field cannot be left blank";
$report_name['resultImg_'.$name] = "<img src=\"./gfx/form_boo.gif\" class=\"resultImg\" alt=\"✘\" title=\"✘\">";
} else {
$report_name['errorText_'.$name] = NULL;
$report_name['resultImg_'.$name] = "<img src=\"./gfx/form_yay.gif\" class=\"resultImg\" alt=\"✔\" title=\"✔\">";
}
echo json_encode($report_name);
}
}
This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.