mysqli_query insert and update within array not working - php

Hey everyone I am trying to run two insert statements and than finally run an update statement within a php array but it seems not to be working correctly. I realize this code has some problems for instance escaping html data before inserting it into the database isn't ideal however i will fix that later the only thing I am concerned about is the insert and update statements. The following is the code I am using:
This is the job data array being built.
if(empty($_POST) === false && empty($errors) === true){
date_default_timezone_set('America/Denver');
$datetime =date("Y-m-d H:i:s");
$submissionId = rand(10000,99999);
$req_data = array(
'itemId' => $i_san,
'itemName' => $_POST['itemName'],
'submissionId' => $submissionId,
'username' => $_SESSION['username'],
'email' => $_SESSION['email'],
'subDate' => $datetime,
'wistiaId' => $_SESSION['wistiaId']
);
add_DCRequests($req_data);//INSERT INTO `DCrequests`
// === Sanatize inputs === //
$text_1_raw = $_POST['textOne'];
$text_1_noQuotes = str_replace('"',"'",$text_1_raw);
//$text_one = utf8_encode("Ñ");
$text_one = htmlentities(trim($text_1_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_2_raw = $_POST['textTwo'];
$text_2_noQuotes = str_replace('"',"'",$text_2_raw);
$text_two = htmlentities(trim($text_2_noQuotes) , ENT_QUOTES , 'UTF-8' );
$text_3_raw = $_POST['textThree'];
$text_3_noQuotes = str_replace('"',"'",$text_3_raw);
$text_three = htmlentities(trim($text_3_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_4_raw = $_POST['textFour'];
$text_4_noQuotes = str_replace('"',"'",$text_4_raw);
$text_four = htmlentities(trim($text_4_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_5_raw = $_POST['textFive'];
$text_5_noQuotes = str_replace('"',"'",$text_5_raw);
$text_five = htmlentities(trim($text_5_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_6_raw = $_POST['textSix'];
$text_6_noQuotes = str_replace('"',"'",$text_6_raw);
$text_six = htmlentities(trim($text_6_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_7_raw = $_POST['textSeven'];
$text_7_noQuotes = str_replace('"',"'",$text_7_raw);
$text_seven = htmlentities(trim($text_7_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_8_raw = $_POST['textEight'];
$text_8_noQuotes = str_replace('"',"'",$text_8_raw);
$text_eight = htmlentities(trim($text_8_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_9_raw = $_POST['textNine'];
$text_9_noQuotes = str_replace('"',"'",$text_9_raw);
$text_nine = htmlentities(trim($text_9_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_10_raw = $_POST['textTen'];
$text_10_noQuotes = str_replace('"',"'",$text_10_raw);
$text_ten = htmlentities(trim($text_10_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_11_raw = $_POST['textEleven'];
$text_11_noQuotes = str_replace('"',"'",$text_11_raw);
$text_eleven = htmlentities(trim($text_11_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_12_raw = $_POST['textTwelve'];
$text_12_noQuotes = str_replace('"',"'",$text_12_raw);
$text_twelve = htmlentities(trim($text_12_noQuotes) , ENT_QUOTES , 'UTF-8');
$aep = escape_data($_POST['aep']);
$output = escape_data($_POST['output']) . "_" . $_POST['subId'];
$output_scrub = preg_replace('/[^A-Za-z0-9\-_]/', "", $output);
$rendStatus = "ready";
//parse out 3 items from POST target (display shape matrix | disp w | disp h)
$item = escape_data($_POST['target']);
$get_target_w_h = explode('|', $item);
$targ = escape_data($get_target_w_h[0]);
$w = escape_data($get_target_w_h[1]);
$h = escape_data($get_target_w_h[2]);
$matrix = $w ."x". $h;
$BGColor = escape_data($_POST['hex']);
$bg_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $BGColor);
$c1 = escape_data($_POST['hex2']);
$c1_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c1);
$c2 = escape_data($_POST['hex3']);
$c2_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c2);
$c3 = escape_data($_POST['hex4']);
$c3_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c3);
// if user is banner attach value = 2
if($_SESSION['userLevel'] == 5){$attach = 2;}else{$attach = 0;}
$show = escape_data($_POST['hide']);
if($show === '1'){
$show_1_val = '{{on}}';
$show_2_val = '{{off}}';
$show_3_val = '{{off}}';
}elseif($show === '2'){
$show_1_val = '{{off}}';
$show_2_val = '{{on}}';
$show_3_val = '{{off}}';
}elseif($show === '3'){
$show_1_val = '{{off}}';
$show_2_val = '{{off}}';
$show_3_val = '{{on}}';
}
$show1_scrub = preg_replace('/[^a-z\{}]/', "", $show1);
$show2 = escape_data($_POST['HideShowLayer2']);
$show2_scrub = preg_replace('/[^a-z\{}]/', "", $show2);
$show3 = escape_data($_POST['HideShowLayer3']);
$show3_scrub = preg_replace('/[^a-z\{}]/', "", $show3);
$still = escape_data($_POST['HideShowLayer1']);
$stillFrame = preg_replace('/[^0-9\.{}]/', "", $custStillFrame);
if($target_file1 != ""){
$image1 = "https://www.test.com/ce/". escape_data($target_file1);}
else{
$image1 = "";
}
if($target_file2 != ""){
$image2 = "https://www.test.com/ce/". escape_data($target_file2);}
else{
$image2 = "";
}
if($target_file3 != ""){
$image3 = "https://www.test.com/ce/". escape_data($target_file3);}
else{
$image3 = "";
}
$completion_date="";
$DCjobsFileId="";
$itemName = escape_data($_POST['itemName']);
$estimatedTime = $currentRendTotal + $custEstRenderTime;
$mydate = date('m/d/Y');
// === Data to insert into the table === //
$job_data = array(
//'bannerToken' => $bannerToken,
'attach' => $attach,
'full-date' => $mydate,
'aep' => $aep,
'target' => $targ,
'output' => $output_scrub,
'itemName' => $itemName,
'render-status' => $rendStatus,
'est_render_time' => $_POST['renderEst'],
'frameNumber' => $stillFrame,
'CustomerName' => $_SESSION['first_name'],
'CustomerEmail' => $_SESSION['email'],
'CustomerKey' => $_SESSION['wistiaId'],
'submissionDate' => $datetime,
'submissionId' => $_POST['subId'],
'itemId' => $custItemId,
'matrix' => $matrix,
'fileformat' => $_POST['format'],
'BGColor' => $bg_scrub,
'ColorOne' => $c1_scrub,
'ColorTwo' => $c2_scrub,
'ColorThree' => $c3_scrub,
'Text-One' => $text_one,
'Text-Two' => $text_two,
'Text-Three' => $text_three,
'Text-Four' => $text_four,
'Text-Five' => $text_five,
'Text-Six' => $text_six,
'Text-Seven' => $text_seven,
'Text-Eight' => $text_eight,
'Text-Nine' => $text_nine,
'Text-Ten' => $text_ten,
'Text-Eleven' => $text_eleven,
'Text-Twelve' => $text_twelve,
'HideShowOne' => $show_1_val,
'HideShowTwo' => $show_2_val,
'HideShowThree' => $show_3_val,
'ImageUploadOne' => $image1,
'ImageUploadTwo' => $image2,
'ImageUploadThree' => $image3,
'completion_date' => "CRAP",
'DCjobsFileId' => "CRAP"
);
add_jobs($job_data);//"INSERT INTO `DCjobs` and INSERT INTO `DCjobsArchive`
header('Content-Type: text/html; charset=utf-8');
header('Location: https://www.test.com/ce/thanks.php?est='.$estimatedTime);
exit();
}elseif(empty($errors) === false){
$reportErrors = "<br /><br /><br />Oops, the following errors occured: <br />" . $errors . "<br /><br /> Please click here to try again. <br /><br />";
}
?>
This is the function that inserts and updates the data from the jobdata array
function add_jobs($job_data){
global $db_conx;
array_walk($job_data, 'array_sanitize');
$jobfields = '`' . implode('`, `', array_keys($job_data)) . '`';
$jobdata = '\'' . implode('\', \'', $job_data) . '\'';
mysqli_query($db_conx, "INSERT INTO `DCjobs` ($jobfields) VALUES ($jobdata)");
mysqli_query($db_conx, "INSERT INTO `DCjobsArchive` ($jobfields) VALUES ($jobdata)");
$selectmaxdcjobsid="SELECT FileRowID, submissionDate FROM DCjobs WHERE submissionDate=(SELECT MAX(submissionDate) FROM DCjobs)";
mysqli_query($db_conx, $selectmaxdcjobsid);
while($row=mysqli_fetch_assoc($selectmaxdcjobsid)){
$maxdcjobsfileid=$row['FileRowID'];
$maxdcjobsubdate=$row['submissionDate'];
}
$selectarchiveid="select submissionId, submissionDate from DCjobsArchive where submissionDate='$maxdcjobsubdate'";
while($row=mysqli_fetch_assoc($selectarchiveid)){
$archivesubmissionid=$row['submissionId'];
$archivesubmissiondate=$row['submissionDate'];
}
$update="UPDATE DCjobsArchive SET DCjobsFileId='$maxdcjobsfileid' WHERE submissionId='$archivesubmissionid'";
mysqli_query($db_conx, $update);
}

It looks like you're trying to get the IDs assigned to the rows that you just inserted, so you can fill in a foreign key. You can do that using the MySQL built-in function LAST_INSERT_ID.
function add_jobs($job_data){
global $db_conx;
array_walk($job_data, 'array_sanitize');
mysqli_query($db_conx, "INSERT INTO `DCjobs` ($jobfields) VALUES ($jobdata)");
mysqli_query($db_conx, "INSERT INTO `DCjobsArchive` (DCjobsFileId, $jobfields) VALUES (LAST_INSERT_ID(), $jobdata)");
}

Related

Array to string conversion - Laravel 5.6 Error

I am trying to update values in the DB using values from a JSON file:
Code:
$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);
//check if hospital exist
$name = explode(' ',trim($data['organisationUnits']['organisationUnit']['name']));
// echo $name[0];
$query = Hospital::where('h_name', 'LIKE' , '%' . $data['organisationUnits']['organisationUnit']['name'] . '%')->first();
if($query){
// echo "\n yupo";
$h_id = $query->id;
$h_slug = $query->h_slug;
$nr_orgUnit = $query->nr_orgUnit;
// echo $nr_orgUnit;
$updateHospital = Hospital::find($h_id);
$updateHospital->h_name = $data["organisationUnits"]["organisationUnit"]["name"];
$updateHospital->h_short_name = $data["organisationUnits"]["organisationUnit"]["shortName"];
$updateHospital->h_code = $data["organisationUnits"]["organisationUnit"]["code"];
$updateHospital->h_opening_date = $data["organisationUnits"]["organisationUnit"]["openingDate"];
$updateHospital->h_closed_date = $data["organisationUnits"]["organisationUnit"]["closedDate"];
$updateHospital->h_active = $data["organisationUnits"]["organisationUnit"]["active"];
$updateHospital->h_comment = $data["organisationUnits"]["organisationUnit"]["comment"];
$updateHospital->h_geo_code = $data["organisationUnits"]["organisationUnit"]["geoCode"];
$updateHospital->h_last_updated = $data["organisationUnits"]["organisationUnit"]["lastUpdated"];
$updateHospital->save();
} else {
// echo 'error';
}
JSON DATA:
{"organisationUnits":{
"organisationUnit":{
"id":"01",
"uuid":{
},
"name":"Isagehe Dispensary",
"shortName":"Isagehe Dispensary ",
"code":"17-04-0118",
"openingDate":"1990-01-01",
"closedDate":{
},
"active":"true",
"comment":{
},
"geoCode":{
},
"lastUpdated":{
}
}
}
}
when i try to run the code, i get the following error:
Array to string conversion (SQL: update `ag_hospitals` set `h_closed_date` = , `h_active` = true, `h_comment` = , `h_geo_code` = , `h_last_updated` = where `id` = 41)"
where might i be wrong?
Note i have also tried updating the following way:
$updateHospital = Hospital::where('id', $h_id)->update([
'h_name' => $data['organisationUnits']['organisationUnit']['name'],
'h_short_name' => $data['organisationUnits']['organisationUnit']['shortName'],
'h_code' => $data['organisationUnits']['organisationUnit']['code'],
'h_opening_date' => $data['organisationUnits']['organisationUnit']['openingDate'],
'h_closed_date' => $data['organisationUnits']['organisationUnit']['closedDate'],
'h_active' => $data['organisationUnits']['organisationUnit']['active'],
'h_comment' => $data['organisationUnits']['organisationUnit']['comment'],
'h_geo_code' => $data['organisationUnits']['organisationUnit']['geoCode'],
'h_last_updated' => $data['organisationUnits']['organisationUnit']['lastUpdated']
]);
You need to define that Attribute in Model that store that JSON Data as Array.
Example:
protected $casts = [
'column_name' => 'array'
];

Codeigniter foreach Undefined variable

I want to calculate hargaLama and hargaBaru, then insert it into database. To do so, I retrieve hargaLama from a view in mysql to my controller while hargaBaru is a user input. Even though I'm using foreach I got Undefined variable hargaLama and I also got error
Unknown column 'kodeProduksi' in 'field list'.
Here's my controller:
public function proses_tambahBarang(){
$kode = $_POST['kode'];
$kodeProduksi = $_POST['kodeProduksi'];
$nama = $_POST['nama'];
$tipe = $_POST['tipe'];
$ukuran = $_POST['ukuran'];
$merk = $_POST['merk'];
$satuan = $_POST['satuan'];
$jumlah = $_POST['jumlah'];
$harga = $_POST['hargaSatuan'];
// echo "proses_tambahBarang";
$data_insert = array(
'kodeBarang' => $kode,
'kodeProduksi' => $kodeProduksi,
'namaBarang' => $nama,
'tipeBarang' => $tipe,
'ukuran' => $ukuran,
'merk' => $merk,
'satuan' => $satuan,
'jumlah' => $jumlah,
'hargaSatuan' => $harga,
'keterangan' => 'n/a',
'idUser' => $this->session->userdata('username'),
'waktuMasuk' => 'n/a',
'waktuEdit' => 'n/a'
);
//$cek = $this->mhome->Barang("where kodeBarang = $data_insert[kodeBarang]");
// if($cek >= 1)
// {
$cek = $this->mhome->BarangHistory("where kodeProduksi = '$data_insert[kodeProduksi]'");
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']));
if($cek >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = '$data_insert[kodeProduksi]'");
foreach ($query as $row) {
$hargaLama = $row[0]['hargaSatuan'];
$jumlahLama = $row[0]['jumlah'];
}
$hargaBaru = $data_insert['hargaSatuan'];
$jumlahBaru = $data_insert['jumlah'];
$jumlahBaru = $jumlahBaru + $jumlahLama;
$data_insert['jumlah'] = $jumlahBaru;
$data_insert['waktuEdit'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Updated";
$this->mhome->UpdateData('baranghistory',$data_insert,array("kodeProduksi" => $data_insert['kodeProduksi']));
$this->mhome->UpdateData('barang',$data_insert,array("kodeBarang" => $data_insert['kodeBarang']));
}
// $this->mhome->hitungHargaSatuan("where kodeBarang = '$data_insert[kodeBarang]'");
$hitung = $this->mhome->hitungHargaSatuan($data_insert['kodeBarang']);
if($hitung){
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
if($cek == 0) {
$data_insert['waktuMasuk'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Baru";
$res = $this->mhome->InsertData('barang',$data_insert);
$res2 = $this->mhome->InsertData('baranghistory',$data_insert);
}
if($res >= 1 && $res2 >=1)
{
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
else {
echo "Tambah barang gagal";
}
}
And here's my model:
public function TableSelect($table,$where="")
{
$stmt = $this->db->query('select * from '.$table.' '.$where);
return $stmt->result_array();
}
I am sure you need not to put 0 here
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];//remove [0] from here
$jumlahLama = $row['jumlah'];//remove [0] from here
}
like this.you need to use count on codition because this is returned array.and use result_array() for getting result in array format.
$cek = $this->mhome->BarangHistory("where kodeProduksi = $data_insert['kodeProduksi']")->result_array();
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']))->result_array();
if(count($cek) >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = $data_insert['kodeProduksi']");
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];
$jumlahLama = $row['jumlah'];
}

json decode all pages at once

I have a problem. I want to json decode the API from https://www.easports.com/fifa/ultimate-team/api/fut/item?page=1, but this only contains 24 players and it has 771(!) pages so that will take forever if you do it one player at one. How can I do it all at once. I currently have this script:
<?php
$conn = mysqli_connect("localhost","u1715p547","L0yRM6pd","u1715p547_ps");
mysqli_set_charset($conn,"utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$page_data_url = "https://www.easports.com/fifa/ultimate-team/api/fut/item?page=1";
// Get the JSON file from EASports
$page_data_plain = file_get_contents($page_data_url);
// Decode the JSON file to a PHP array
$page_data_json = json_decode($page_data_plain, true);
// Get the total pages count
$total_pages_count = $page_data_json['totalPages'];
// Loop through each page
for ($page = 1; $page <= $total_pages_count; $page++){
// Get the EASports JSON per specific page
$item_url = 'https://www.easports.com/fifa/ultimate-team/api/fut/item?page='.$page;
// Get the JSON file from EASports
$item_data_plain = file_get_contents($item_url);
// Decode the JSON file to a PHP array
$item_data_json = json_decode($item_data_plain, true);
// Count the amount of items
$total_items_count = $item_data_json['count'];
// Loop through all items, extract the values and insert in DB
for ($c = 0; $c < $total_items_count; $c++) {
$commonname00 = $item_data_json[$c]['commonName'];
$commonname = str_replace("'", "''", $commonname00);
$firstname00 = $item_data_json[$c]['firstName'];
$firstname = str_replace("'", "''", $firstname00);
$lastname00 = $item_data_json[$c]['lastName'];
$lastname = str_replace("'", "''", $lastname00);
$playerimg = $item_data_json[$c]['headshotImgUrl'];
$leagueid = $item_data_json[$c]['league']['id'];
$nationsmall = $item_data_json[$c]['nation']['imageUrls']['small'];
$nationnormal = $item_data_json[$c]['nation']['imageUrls']['medium'];
$nationlarge = $item_data_json[$c]['nation']['imageUrls']['large'];
$nationid = $item_data_json[$c]['nation']['id'];
$clubsmall = $item_data_json[$c]['club']['imageUrls']['normal']['small'];
$clubnormal = $item_data_json[$c]['club']['imageUrls']['normal']['medium'];
$clublarge = $item_data_json[$c]['club']['imageUrls']['normal']['large'];
$clubid = $item_data_json[$c]['club']['id'];
$largeImgUrl = $item_data_json[$c]['headshot']['largeImgUrl'];
$medImgUrl = $item_data_json[$c]['headshot']['medImgUrl'];
$smallImgUrl = $item_data_json[$c]['headshot']['smallImgUrl'];
$largeSpecImgUrl = $item_data_json[$c]['specialImages']['largeTOTWImgUrl'];
$medSpecImgUrl = $item_data_json[$c]['specialImages']['medTOTWImgUrl'];
$pos = $item_data_json[$c]['position'];
$ps = $item_data_json[$c]['playStyle'];
$heig = $item_data_json[$c]['height'];
$weig = $item_data_json[$c]['weight'];
$bd = $item_data_json[$c]['birthdate'];
$age = $item_data_json[$c]['age'];
$acc = $item_data_json[$c]['acceleration'];
$agg = $item_data_json[$c]['aggression'];
$agi = $item_data_json[$c]['agility'];
$bal = $item_data_json[$c]['balance'];
$ball = $item_data_json[$c]['ballcontrol'];
$foot = $item_data_json[$c]['foot'];
$sm = $item_data_json[$c]['skillMoves'];
$cro = $item_data_json[$c]['crossing'];
$cur = $item_data_json[$c]['curve'];
$dri = $item_data_json[$c]['dribbling'];
$fin = $item_data_json[$c]['finishing'];
$fca = $item_data_json[$c]['freekickaccuracy'];
$gkd = $item_data_json[$c]['gkdiving'];
$gkh = $item_data_json[$c]['gkhandling'];
$gkk = $item_data_json[$c]['gkkicking'];
$gkp = $item_data_json[$c]['gkpositioning'];
$gkr = $item_data_json[$c]['gkreflexes'];
$hea = $item_data_json[$c]['headingaccuracy'];
$int = $item_data_json[$c]['interceptions'];
$jum = $item_data_json[$c]['jumping'];
$lop = $item_data_json[$c]['longpassing'];
$los = $item_data_json[$c]['longshots'];
$mar = $item_data_json[$c]['marking'];
$pen = $item_data_json[$c]['penalties'];
$poi = $item_data_json[$c]['positioning'];
$pot = $item_data_json[$c]['potential'];
$rea = $item_data_json[$c]['reactions'];
$shp = $item_data_json[$c]['shortpassing'];
$sho = $item_data_json[$c]['shotpower'];
$slt = $item_data_json[$c]['slidingtackle'];
$spr = $item_data_json[$c]['sprintspeed'];
$stt = $item_data_json[$c]['standingtackle'];
$sta = $item_data_json[$c]['stamina'];
$str = $item_data_json[$c]['strength'];
$vis = $item_data_json[$c]['vision'];
$vol = $item_data_json[$c]['volleys'];
$wf = $item_data_json[$c]['weakFoot'];
$traits = $item_data_json[$c]['traits'][$c];
$traits1 = $item_data_json[$c]['traits']['1'];
$traits2 = $item_data_json[$c]['traits']['2'];
$traits3 = $item_data_json[$c]['traits']['3'];
$traits4 = $item_data_json[$c]['traits']['4'];
$specialities = $item_data_json[$c]['specialities'][$c];
$specialities1 = $item_data_json[$c]['specialities']['1'];
$specialities2 = $item_data_json[$c]['specialities']['2'];
$specialities3 = $item_data_json[$c]['specialities']['3'];
$specialities4 = $item_data_json[$c]['specialities']['4'];
$specialities5 = $item_data_json[$c]['specialities']['5'];
$specialities6 = $item_data_json[$c]['specialities']['6'];
$specialities7 = $item_data_json[$c]['specialities']['7'];
$specialities8 = $item_data_json[$c]['specialities']['8'];
$specialities9 = $item_data_json[$c]['specialities']['9'];
$specialities10 = $item_data_json[$c]['specialities']['10'];
$atk = $item_data_json[$c]['atkWorkRate'];
$def = $item_data_json[$c]['defWorkRate'];
$pty = $item_data_json[$c]['playerType'];
$pace = $item_data_json[$c]['attributes'][$c]['value'];
$shot = $item_data_json[$c]['attributes']['1']['value'];
$pass = $item_data_json[$c]['attributes']['2']['value'];
$drib = $item_data_json[$c]['attributes']['3']['value'];
$deff = $item_data_json[$c]['attributes']['4']['value'];
$phys = $item_data_json[$c]['attributes']['5']['value'];
$nameof00 = $item_data_json[$c]['name'];
$nameof = str_replace("'", "''", $nameof00);
$qua = $item_data_json[$c]['quality'];
$color = $item_data_json[$c]['color'];
$GK = $item_data_json[$c]['isGK'];
$posfull = $item_data_json[$c]['positionFull'];
$price = $item_data_json[$c]['discardValue'];
$id = $item_data_json[$c]['id'];
$baseId = $item_data_json[$c]['baseId'];
$rating = $item_data_json[$c]['rating'];
$sql = "INSERT IGNORE INTO `players`(`commonName`, `firstName`, `headshotImgUrl`, `lastName`, `leagueid`, `nationimageUrlssmall`, `nationimageUrlsmedium`, `nationimageUrlslarge`, `nationid`, `clubimageUrlsnormalsmall`, `clubimageUrlsnormalmedium`, `clubimageUrlsnormallarge`, `clubid`, `headshotlargeImgUrl`, `headshotmedImgUrl`, `headshotsmallImgUrl`, `specialImageslargeTOTWImgUrl`, `specialImagesmedTOTWImgUrl`, `position`, `playStyle`, `height`, `weight`, `birthdate`, `age`, `acceleration`, `aggression`, `agility`, `balance`, `ballcontrol`, `foot`, `skillMoves`, `crossing`, `curve`, `dribbling`, `finishing`, `freekickaccuracy`, `gkdiving`, `gkhandling`, `gkkicking`, `gkpositioning`, `gkreflexes`, `headingaccuracy`, `interceptions`, `jumping`, `longpassing`, `longshots`, `marking`, `penalties`, `positioning`, `potential`, `reactions`, `shortpassing`, `shotpower`, `slidingtackle`, `sprintspeed`, `standingtackle`, `stamina`, `strength`, `vision`, `volleys`, `weakFoot`, `traits0`, `traits1`, `traits2`, `traits3`, `specialities0`, `specialities1`, `specialities2`, `specialities3`, `specialities4`, `specialities5`, `specialities6`, `specialities7`, `specialities8`, `atkWorkRate`, `defWorkRate`, `playerType`, `attributes0value`, `attributes1value`, `attributes2value`, `attributes3value`, `attributes4value`, `attributes5value`, `name`, `quality`, `color`, `isGK`, `positionFull`, `discardValue`, `id`, `baseId`, `rating`, `specialities9`, `specialities10`, `traits4`)
VALUES ('$commonname', '$firstname', '$playerimg', '$lastname', $leagueid, '$nationsmall', '$nationnormal', '$nationlarge',
$nationid, '$clubsmall', '$clubnormal', '$clublarge', $clubid, '$largeImgUrl', '$medImgUrl',
'$smallImgUrl', '$largeSpecImgUrl', '$medSpecImgUrl', '$pos', '$ps', $heig, $weig, '$bd', $age, $acc, $agg, $agi, $bal, $ball, '$foot', $sm, $cro, $cur, $dri,
$fin, $fca, $gkd, $gkh, $gkk, $gkp, $gkr, $hea, $int, $jum, $lop, $los, $mar, $pen, $poi, $pot, $rea, $shp, $sho, $slt, $spr, $stt, $sta, $str, $vis, $vol, $wf,
'$traits', '$traits1', '$traits2', '$traits3', '$specialities', '$specialities1', '$specialities2', '$specialities3', '$specialities4', '$specialities5',
'$specialities6', '$specialities7', '$specialities8', '$atk', '$def', '$pty', $pace, $shot, $pass, $drib, $deff, $phys, '$nameof', '$qua', '$color', '$GK',
'$posfull', '$price', $id, $baseId, $rating, '$specialities9', '$specialities10', '$traits4')";
echo $sql;
if(!$result = $conn->query($sql))
{
die("<script type='text/javascript'>alert(Fault);</script>");
}
}
}
?>
It just gives me this:
INSERT IGNORE INTO `players`(`commonName`, `firstName`, `headshotImgUrl`, `lastName`, `leagueid`, `nationimageUrlssmall`, `nationimageUrlsmedium`, `nationimageUrlslarge`, `nationid`, `clubimageUrlsnormalsmall`, `clubimageUrlsnormalmedium`, `clubimageUrlsnormallarge`, `clubid`, `headshotlargeImgUrl`, `headshotmedImgUrl`, `headshotsmallImgUrl`, `specialImageslargeTOTWImgUrl`, `specialImagesmedTOTWImgUrl`, `position`, `playStyle`, `height`, `weight`, `birthdate`, `age`, `acceleration`, `aggression`, `agility`, `balance`, `ballcontrol`, `foot`, `skillMoves`, `crossing`, `curve`, `dribbling`, `finishing`, `freekickaccuracy`, `gkdiving`, `gkhandling`, `gkkicking`, `gkpositioning`, `gkreflexes`, `headingaccuracy`, `interceptions`, `jumping`, `longpassing`, `longshots`, `marking`, `penalties`, `positioning`, `potential`, `reactions`, `shortpassing`, `shotpower`, `slidingtackle`, `sprintspeed`, `standingtackle`, `stamina`, `strength`, `vision`, `volleys`, `weakFoot`, `traits0`, `traits1`, `traits2`, `traits3`, `specialities0`, `specialities1`, `specialities2`, `specialities3`, `specialities4`, `specialities5`, `specialities6`, `specialities7`, `specialities8`, `atkWorkRate`, `defWorkRate`, `playerType`, `attributes0value`, `attributes1value`, `attributes2value`, `attributes3value`, `attributes4value`, `attributes5value`, `name`, `quality`, `color`, `isGK`, `positionFull`, `discardValue`, `id`, `baseId`, `rating`, `specialities9`, `specialities10`, `traits4`) VALUES ('', '', '', '', , '', '', '', , '', '', '', , '', '', '', '', '', '', '', , , '', , , , , , , '', , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', , , , , , , '', '', '', '', '', '', , , , '', '', '')
You can't. You have to call it X times where X corresponds to number of pages.
You should ask authors if they could give you entire block of data in single call.

How do I add dynamic WHERE clause for search filtering?

I have 7 search parameters although the code below shows only two, Title and Type.
We would like to give our users the ability to search by ANY of the 7 parameters.
They should also be given the ability to search by more than one parameter.
How would I adapt the code below to use a dynamic $where clause?
Example, a user could select where type='some value'.
A user should also be able to select where type='some value' and title='some value'.
Thank you in advance.
function ms_escape_string($data) {
if ( !isset($data) or empty($data) ) return '';
if ( is_numeric($data) ) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/' // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, '', $data );
$data = str_replace("'", "''", $data );
return $data;
}
$strprojectTitle = null;
$strbidType = null;
if(isset($_POST["projectTitle"]))
{
$strprojectTitle = $_POST["projectTitle"];
}
if(isset($_POST["BidType"]))
{
$strbidType = $_POST["BidType"];
}
?>
<?php
$sql = "Select b.ID,convert(char(10),b.BidDate,101) BidDate,convert(char(10),
b.DueDate,101)DueDate,b.BidTitle,b.DueTime,b.BidID,BidIDFile,
d.Department,b.BidType,CASE WHEN b.AwardDate ='01/01/1900' Then NULL ELSe convert(char(10),b.AwardDate,101)END AS AwardDate,
convert(char(10),b.LastUpdate,101) LastUpdate,s.Status
FROM bids b inner join dept d on b.Department=d.DeptID inner join Status s on b.BidStatus=s.StatusId WHERE b.BidTitle = ' . ms_escape_string($strprojectTitle) . ' OR b.BidType = ' . ms_escape_string($strbidType) . ' ";
///****Latest attempt
$fields = array(
'projectTitle' => 'b.BidTitle',
'BidType' => 'b.BidType'
);
$where = array();
foreach($fields as $fieldPost => $fieldDb) {
if(isset($_POST[$fieldPost]) && strlen($_POST[$fieldPost]) > 0) {
$where[] = "`$fieldDb` = '$_POST[$fieldPost]'";
}
}
$sql = "Select b.ID,convert(char(10),b.BidDate,101) BidDate,convert(char(10),
b.DueDate,101)DueDate,b.BidTitle,b.DueTime,b.BidID,BidIDFile,
d.Department,b.BidType,CASE WHEN b.AwardDate ='01/01/1900' Then NULL ELSe convert(char(10),b.AwardDate,101)END AS AwardDate,
convert(char(10),b.LastUpdate,101) LastUpdate,s.Status
FROM bids b inner join dept d on b.Department=d.DeptID inner join Status s on b.BidStatus=s.StatusId
" . ( count($where) > 0 ? " WHERE " . implode(' AND ', $where) : "" );
Remove this part in your code:
$strprojectTitle = null;
$strbidType = null;
if(isset($_POST["projectTitle"]))
{
$strprojectTitle = $_POST["projectTitle"];
}
if(isset($_POST["BidType"]))
{
$strbidType = $_POST["BidType"];
}
And replace it with the one below, which enables a dynamic way of building the WHERE conditions:
## easily add here the fields you have
$fields = array(
'projectTitle' => 'b.BidTitle',
'BidType' => 'b.BidType'
);
$where = array();
foreach($fields as $fieldPost => $fieldDb) {
if(isset($_POST[$fieldPost]) && strlen($_POST[$fieldPost]) > 0) {
$where[] = "`$fieldDb` = '" . ms_escape_string($_POST[$fieldPost]) . "'";
}
}
## Use the $where array in your final SQL query
## important to test if count($where) > 0 in case no search has been made
$sql = "SELECT ..... " . ( count($where) > 0 ? " WHERE " . implode(' AND ', $where) : "" );
A more advanced example to build the WHERE string by supporting multiple search types (for example the search comparators: LIKE %..% and =)
## support multiple search comparators
$fields = array(
'projectTitle' => array('field' => 'b.BidTitle', 'searchType' => 'like'),
'BidType' => array('field' => 'b.BidType', 'searchType' => 'equal')
);
$where = array();
foreach($fields as $fieldPost => $field) {
if(isset($_POST[$fieldPost]) && strlen($_POST[$fieldPost]) > 0) {
if($field['searchType'] == 'like') {
$where[] = "`".$field['field']."` LIKE '%" . ms_escape_string($_POST[$fieldPost]) . "%'";
} else {
$where[] = "`".$field['field']."` = '" . ms_escape_string($_POST[$fieldPost]) . "'";
}
}
}

Something not working as expected in this PHP function

I am trying to pull data from MySQL and this supposed to show complete data but this is showing only one row. This is supposed to show all rows of users. I don’t know what I did wrong:
Here is the code:
function getCashoutRequests($uid, $limit) {
if (!empty( $limit )) {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC LIMIT ' . $limit );
}
else {
$query = mysql_query( '' . 'SELECT * FROM cashouts WHERE uid = ' . $uid . ' ORDER BY id DESC' );
}
if (mysql_num_rows( $query )) {
if ($row = mysql_fetch_object( $query )) {
$row->id;
$amount = $row->amount;
$status = $row->status;
$client_notes = nl2br( $row->user_notes );
$admin_notes = nl2br( $row->admin_notes );
$request_date = $row->request_date;
$payment_date = $row->payment_date;
$fee = $row->fee;
$priority = $hid = $row->priority;
$method = $row->method;
if ($payment_date != '0000-00-00 00:00:00') {
$payment_date = date( 'd M, Y', strtotime( $payment_date ) );
}
$request_date = date( 'd M, Y', strtotime( $request_date ) );
$payHistory []= array( 'id' => $hid, 'cash' => $amount, 'status' => $status, 'method' => $method, 'client_notes' => $client_notes, 'admin_notes' => $admin_notes, 'date' => $request_date, 'payment_date' => $payment_date, 'fee' => $fee, 'priority' => $priority );
}
return $payHistory;
}
return false;
}
On this line you have if:
if ($row = mysql_fetch_object( $query )) {
If you use if that would only go to the first value since if simply tests a condition once. Instead try while like this:
while ($row = mysql_fetch_object( $query )) {
As explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.

Categories