Easier way to do multiple loop styled actions? - php

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

Related

updating many rows using ajax .serializeArray()

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.

Optimize SQL queries in php file

I wrote PHP script to auto-update offers from provider API in my database. Unfortunately, by performing the following queries in the foreach loop (following the API records), the load is at 99% of the CPU. The script must be activated in cron every 10-15 minutes, but with this load the server is weak. How could I optimize it for more efficient work?
<?php
include "config.php";
function checkDevice($device) {
if($device == "Android" || $device == "iOS" || $device == "iPhone" || $device == "iPad") {
return true;
} else {
return false;
}
}
function countUserPayout($providerPayout) {
$summary = ($providerPayout * 100) / 2;
return ceil($summary);
}
function getOgAds() {
$response = file_get_contents("link");
$result = json_decode($response, true);
return $result["offers"];
}
function getAdGate() {
$response = file_get_contents("link");
$result = json_decode($response, true);
return $result["data"];
}
function checkOgAdsDevice($devices) {
$devicesArray = explode(",", $devices);
foreach($devicesArray as $device) {
if($device == "iPhone" || $device == "iPad" || $device == "Android") {
return true;
} else {
return false;
}
}
}
function detectDesktop($category) {
$categories = explode(",", $category);
$exists = array_search("Desktop", $categories);
if($exists) {
return true;
} else {
return false;
}
}
function createCountries($object) {
foreach($object as $country) {
$countries[] = $country;
}
if(isset($countries)) {
return $countries;
}
}
function createOfferWall() {
$offerWall = [];
foreach(getOgAds() as $offer) {
if(checkOgAdsDevice($offer["device"]) && detectDesktop($offer["device"]) == false) {
$offerWall[] = array(
"offer_id" => $offer["offerid"],
"name" => $offer["name_short"],
"requirements" => $offer["adcopy"],
"category" => $offer["device"],
"provider_payout" => $offer["payout"],
"payout" => countUserPayout($offer["payout"]),
"epc" => $offer["epc"],
"icon" => $offer["picture"],
"anchor" => $offer["link"],
"countries" => (array)$offer["country"],
"provider" => "ogads"
);
} else {
continue;
}
}
foreach(getAdGate() as $offer) {
if(checkDevice($offer["categories"][0])) {
$offerWall[] = array(
"offer_id" => $offer["id"],
"name" => $offer["adgate_rewards"]["anchor"],
"requirements" => $offer["requirements"],
"category" => $offer["categories"][0],
"provider_payout" => $offer["payout"],
"payout" => countUserPayout($offer["payout"]),
"epc" => $offer["epc"],
"icon" => $offer["creatives"]["icon"],
"anchor" => $offer["click_url"],
"countries" => createCountries($offer["countries"]),
"provider" => "adgate"
);
} else {
continue;
}
}
return $offerWall;
}
function createIdWall($dbh) {
$offerWall = createOfferWall();
foreach($offerWall as $offer) {
$idWall[$offer["offer_id"]] = $offer["offer_id"];
}
return $idWall;
}
function setCountries($dbh, $countries, $offer) {
if(isset($countries)) {
foreach($countries as $country) {
$stmt = $dbh->prepare("INSERT INTO `table`(`aaa`,`xxx`,`yyy`) VALUES(NULL, :country, :oid)");
$stmt->bindParam(":country", $country, PDO::PARAM_STR);
$stmt->bindParam(":oid", $offer, PDO::PARAM_INT);
$stmt->execute();
}
}
}
function checkOfferExists($dbh, $providerId) {
$stmt = $dbh->prepare("SELECT count(`id`) as `exists` FROM `table` WHERE `provider_id` = :providerId");
$stmt->bindParam(":providerId", $providerId, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result["exists"] == 1) {
return true;
} else {
return false;
}
}
function getOfferInfo($dbh, $providerId) {
$stmt = $dbh->prepare("SELECT * FROM `table` WHERE `provider_id` = :providerId");
$stmt->bindParam(":providerId", $providerId, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
function compareOffers($dbh, $providerId, $offer) {
$dbOffer = getOfferInfo($dbh, $providerId);
if($dbOffer["provider_payout"] != $offer["provider_payout"] || $dbOffer["anchor"] != $offer["anchor"] || $dbOffer["offer_name"] != $offer["name"] || $dbOffer["category"] != $offer["category"] || $dbOffer["icon"] != $offer["icon"] || $dbOffer["requirements"] != $offer["requirements"]) {
return true;
} else {
return false;
}
}
function getDbOffers($dbh) {
$stmt = $dbh->prepare("SELECT `provider_id` FROM `table`");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
function activateOffer($dbh, $providerId) {
$stmt = $dbh->prepare("UPDATE `table` SET `active` = 1 WHERE `provider_id` = :providerId");
$stmt->bindParam(":providerId", $providerId, PDO::PARAM_INT);
$stmt->execute();
}
function disableOffer($dbh, $providerId) {
$stmt = $dbh->prepare("UPDATE `table` SET `active` = 0 WHERE `provider_id` = :providerId");
$stmt->bindParam(":providerId", $providerId, PDO::PARAM_INT);
$stmt->execute();
}
function updateOffer($dbh, $providerId, $offer) {
$stmt = $dbh->prepare("UPDATE `table` SET
`aaa` = :payout,
`bbb = :points,
`ccc` = :anchor,
`ddd` = :name,
`eee` = :category,
`fff` = :icon,
`ggg` = :requirements
WHERE `provider_id` = :providerId");
$stmt->bindParam(":providerId", $providerId, PDO::PARAM_STR);
$stmt->bindParam(":payout", $offer["provider_payout"], PDO::PARAM_INT);
$stmt->bindParam(":points", $offer["payout"], PDO::PARAM_INT);
$stmt->bindParam(":anchor", $offer["anchor"], PDO::PARAM_STR);
$stmt->bindParam(":name", $offer["name"], PDO::PARAM_STR);
$stmt->bindParam(":category", $offer["category"], PDO::PARAM_STR);
$stmt->bindParam(":icon", $offer["icon"], PDO::PARAM_STR);
$stmt->bindParam(":requirements", $offer["requirements"], PDO::PARAM_STR);
$stmt->execute();
}
function addOffer($dbh, $offer) {
$stmt = $dbh->prepare("INSERT INTO `table` (`aaa`, `bbb`, `ccc, `ddd`, `eee`, `fff`, `ggg`, `hhh`, `jjj`, `kkk`, `lll`, `zzz`, `xxx`) VALUES (NULL, :requirements, :points, :providerId, :icon, :epc, :ownPayout, :anchor, :category, :name, 1, 0, :provider);");
$stmt->bindParam(":requirements", $offer["requirements"], PDO::PARAM_STR);
$stmt->bindParam(":points", $offer["payout"], PDO::PARAM_INT);
$stmt->bindParam(":providerId", $offer["offer_id"], PDO::PARAM_INT);
$stmt->bindParam(":icon", $offer["icon"], PDO::PARAM_STR);
$stmt->bindParam(":epc", $offer["epc"], PDO::PARAM_STR);
$stmt->bindParam(":ownPayout", $offer["provider_payout"], PDO::PARAM_STR);
$stmt->bindParam(":anchor", $offer["anchor"], PDO::PARAM_STR);
$stmt->bindParam(":category", $offer["category"], PDO::PARAM_STR);
$stmt->bindParam(":name", $offer["name"], PDO::PARAM_STR);
$stmt->bindParam(":provider", $offer["provider"], PDO::PARAM_STR);
$stmt->execute();
setCountries($dbh, $offer["countries"], $offer["offer_id"]);
}
function checkStatus($dbh, $providerId) {
$stmt = $dbh->prepare("SELECT `active` FROM `table` WHERE `provider_id` = :providerId");
$stmt->bindParam(":providerId", $providerId, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result["active"] == 0) {
return false;
} else {
return true;
}
}
function followOffers($dbh) {
foreach(createOfferWall() as $offer) {
if(checkOfferExists($dbh, $offer["offer_id"])) {
if(compareOffers($dbh, $offer["offer_id"], $offer)) {
updateOffer($dbh, $offer["offer_id"], $offer);
} else {
continue;
}
} else {
addOffer($dbh, $offer);
}
}
}
function findRevokeOffers($dbh) {
$idWall = array_flip(createIdWall($dbh));
foreach(getDbOffers($dbh) as $dbOffer) {
$providerId = $dbOffer["provider_id"];
if(isset($idWall[$providerId])) {
continue;
} else {
if(checkStatus($dbh, $providerId)) {
disableOffer($dbh, $providerId);
} else {
continue;
}
}
}
}
function getCurrentTime() {
$currentTime = date('Y-m-d H:i:s');
return $currentTime;
}
echo "// START [".getCurrentTime()."]" .PHP_EOL;
followOffers($dbh);
findRevokeOffers($dbh);
echo "// END" .PHP_EOL;
?>

PHP No such file or directory error

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.

returning data from function in another file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to make a function that just checks to see if the user has the correct rank and if they don't have a serial in the database.
I'm having trouble returning the values to use in the file though.
index.php
$xf_user = $_SESSION['user']['username'];
check_user_serial($xf_user);
check_user_rank($xf_user);
if($has_serial == 0) {
if($user_rank == 4) {
generate_serial($xf_user);
} else {
header('Location: ../index.php?d=n');
die();
}
} else {
header('Location: ../index.php?d=s');
die();
}
functions.php
function check_user_serial($username) {
global $dbConnect;
$query = "SELECT * FROM xf_users WHERE username = '".$username."'";
try {
$stmt = $dbConnect->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
$has_serial = $row['has_serial'];
}
}
catch(PDOException $ex) {
die($ex->getMessage());
}
return $has_serial;
}
function check_user_rank($username) {
global $dbConnect;
$query = "SELECT * FROM xf_users WHERE username = '".$username."'";
try {
$stmt = $dbConnect->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
$user_rank = $row['user_rank'];
}
}
catch(PDOException $ex) {
die($ex->getMessage());
}
return $user_rank;
}
function generate_serial($username) {
global $dbConnect;
$serial1 = substr(md5(uniqid(rand(), true)), -5, 5);
$serial2 = substr(md5(uniqid(rand(), true)), -5, 5);
$serial3 = substr(md5(uniqid(rand(), true)), -5, 5);
$serial4 = substr(md5(uniqid(rand(), true)), -5, 5);
$serial = sprintf('%s-%s-%s-%s', $serial1, $serial2, $serial3, $serial4);
$query = "SELECT * FROM xf_users WHERE serial = '".$serial."'";
try {
$stmt = $dbConnect->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
if($result == NULL) {
$query = "INSERT INTO xf_users (serial, has_serial) VALUES (:serial, :has_serial) WHERE username = '".$username."'";
$query_params = array(':serial' => $serial, ':has_serial' => '1');
try {
$stmt = $dbConnect->prepare($query);
$stmt->execute($query_params);
}
catch(PDOException $ex) {
die();
}
} else {
die('serial generation has failed. please notify an administrator.');
}
}
catch(PDOException $ex) {
die($ex->getMessage());
}
return $serial;
}
$xf_user = $_SESSION['user']['username'];
$has_serial = check_user_serial($xf_user);
$user_rank = check_user_rank($xf_user);
if($has_serial == 0) {
if($user_rank == 4) {
generate_serial($xf_user);
} else {
header('Location: ../index.php?d=n');
die();
}
} else {
header('Location: ../index.php?d=s');
die();
}
Try this, you weren't assigning $has_serial and $user_rank to anything.
Debug version:
$xf_user = $_SESSION['user']['username'];
$has_serial = check_user_serial($xf_user);
$user_rank = check_user_rank($xf_user);
if($has_serial == 0) {
if($user_rank == 4) {
echo "generated serial";
generate_serial($xf_user);
} else {
echo "user rank not 4";
//header('Location: ../index.php?d=n');
die();
}
} else {
echo "has serial";
//header('Location: ../index.php?d=s');
die();
}
there where you call the function you have to add a variable that gets the data what the function will return:
$serial = check_user_serial($xf_user);
$rank = check_user_rank($xf_user);
Another problem that is see in the function check_user_serial is that there is no initialization for the $has_serial variable. It is now possible that the function will return a variable that does not exist. It will happen if there are zero rows retrieved from the database.
For example you could add a rule in top of your function to initialize the variable and assign a default value to it:
$has_serial = FALSE;
I ll try to explain it with a little example:
// wrong
function getNumber($assign)
{
if($assign)
$number = 5;
return $number; // will not exist if $assign == FALSE
}
echo getNumber(FALSE); // will throw an error
// right
function getNumber($assign)
{
//initialization
$number = 0;
if($assign)
$number = 5;
return $number; // returns 0 or 5 but will never cause an error
}
echo getNumber(FALSE); // no problem :-)

Sql injection without overwrite

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

Categories