How to use Plupload for insert statements in PHP - php

I have a php porgram which inserts data from an excel file to the mysql database but it doesn't work with files bigger than 4 MB and since I do not have access to the php.ini file I thought of chunking the insert statements. I found plupload but didn't figure out how to use it for insert statements. Any other method would be fine as well.
function insertRow($conn, $row, $header) {
// find indexes
// vorname
$firstNameIndex = array_search('vorname', $header, true);
// name / nachname
$lastNameIndex = array_search('name', $header, true);
if($lastNameIndex === false) $lastNameIndex = array_search('nachname', $header, true);
// anrede
$anredeIndex = array_search('anrede', $header, true);
// street
$streetIndex = array_search('straße', $header, true);
// Hausnummer
$hausnummerIndex = array_search('hausnummer', $header, true);
// Telefon
$telefonIndex = array_search('telefon', $header, true);
// PLZ
$plzIndex = array_search('plz', $header, true);
// ORT
$ortIndex = array_search('ort', $header, true);
$anrede = $row[$anredeIndex];
$firstName = $row[$firstNameIndex];
$lastName = $row[$lastNameIndex];
$street = $row[$streetIndex];
$houseNumber = $row[$hausnummerIndex];
$telefon = $row[$telefonIndex];
$plz = $row[$plzIndex];
$ort = $row[$ortIndex];
$title = 'unbekannt';
$geburtsdatum = 0;
$hnr_zusatz = "";
$timestamp = time();
$sql = <<<EOSQL
INSERT INTO adressen (anrede, vorname, nachname, strasse, hnr, telefon1, id_lieferung, priv_gew,
status, titel, geburtsdatum, hnr_zusatz, plz, ort, telefon2, mail, sperrung, sperrgrund, optin,
optindat, timestamp, zusatz1) VALUES ("$anrede", "$firstName", "$lastName", "$street",
"$houseNumber", "$telefon", 0, 0, 0, "$title", $geburtsdatum, "$hnr_zusatz", "$plz", "$ort", 0, "",
0, 0, 0, 0, $timestamp, 0);
EOSQL;
if (!$conn->query($sql) === TRUE) {
echo "Error: cant add this row " . $sql . "<br/>" . $conn->error;
print_r($row);
echo "___________________<br/>";
}
}
I know this isn't safe at all and I am open for sql injections but I will change that after this. Thank you in advance.

Related

How to insert a big amount of data in mysql database via PHP

I have this function to insert some data in my mysql database:
function insertRow($conn, $row, $header) {
// find indexes
// vorname
$firstNameIndex = array_search('vorname', $header, true);
// name / nachname
$lastNameIndex = array_search('name', $header, true);
if($lastNameIndex === false) $lastNameIndex = array_search('nachname', $header, true);
// anrede
$anredeIndex = array_search('anrede', $header, true);
// street
$streetIndex = array_search('straße', $header, true);
// Hausnummer
$hausnummerIndex = array_search('hausnummer', $header, true);
// Telefon
$telefonIndex = array_search('telefon', $header, true);
// PLZ
$plzIndex = array_search('plz', $header, true);
// ORT
$ortIndex = array_search('ort', $header, true);
$anrede = $row[$anredeIndex];
$firstName = $row[$firstNameIndex];
$lastName = $row[$lastNameIndex];
$street = $row[$streetIndex];
$houseNumber = $row[$hausnummerIndex];
$telefon = $row[$telefonIndex];
$plz = $row[$plzIndex];
$ort = $row[$ortIndex];
$title = 'unbekannt';
$geburtsdatum = 0;
$hnr_zusatz = "";
$timestamp = time();
$sql = <<<EOSQL
INSERT INTO adressen (anrede, vorname, nachname, strasse, hnr, telefon1, id_lieferung, priv_gew,
status, titel, geburtsdatum, hnr_zusatz, plz, ort, telefon2, mail, sperrung, sperrgrund, optin,
optindat, timestamp, zusatz1) VALUES ("$anrede", "$firstName", "$lastName", "$street",
"$houseNumber", "$telefon", 0, 0, 0, "$title", $geburtsdatum, "$hnr_zusatz", "$plz", "$ort", 0, "",
0, 0, 0, 0, $timestamp, 0);
EOSQL;
if (!$conn->query($sql) === TRUE) {
echo "Error: cant add this row " . $sql . "<br/>" . $conn->error;
print_r($row);
echo "___________________<br/>";
}
}
It works for small data but when I try it with a file more than 4 MB it doesn't work. I do not have access to the php.ini file sadly. These inserts come originally from an excel file. I wanted to try plupload but didn't understand how to implement it to my method.

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.

php response is taking too long time

I have some problem with getting results from VFP database results... The time which is taking by my php script is veeeery long - about 30 minutes, but it should be much shorter...
So there is the code which is responsible for taking database results:
$connect = odbc_connect("RIS", "", "", SQL_CUR_USE_DRIVER) or die("Error in connection ". odbc_errormsg($connect));
$array = array();
$info = array();
$from = $_GET['from'];
$to = $_GET['to'];
$rez_nap = odbc_exec($connect, "
select
pacientid as pac_pk,
datanapr,
ocered,
rtgapparat,
doctor as doc_naprav,
pk_na,
data_opis,
arst_opis as id_arst_opis
from
napravlenie
where
not arst_opis == '0000' and
not arst_opis == '' and
datanapr between {^".$from."} and {^".$to."}
") or die(odbc_errormsg());
while($row_nap = odbc_fetch_array($rez_nap))
{
echo "<pre>";
var_dump($row_nap);
$rez_opis = odbc_exec($connect, "
select
opis as opisanie,
doctor as doc_opis
from
opisanie_rtg
where
pacientid = '".$row_nap["pac_pk"]."' and
data = '".$row_nap["data_opis"]."' and
ocered = '".$row_nap["ocered"]."'
") or die(odbc_errormsg());
while($row_desc = odbc_fetch_array($rez_opis))
{
$op = explode('##$', $row_desc['opis']);
$opisanie = iconv( "cp1257", "utf-8", trim( addslashes($op[1]) ) );
$t_nr_i = substr($op[0], 12);
$ttt = explode("[", $t_nr_i);
if ( strlen($ttt[0]) > 12 )
{
$tt_nr_is = explode("-", $ttt[0]);
$t_nr_is_t = substr($tt_nr_is[0], 0, 8);
$t_nr_is_t_2 = substr($tt_nr_is[0], 8, 5);
$row_desc["nr_is"] = $t_nr_is_t."-".$t_nr_is_t_2;
}
else
{
$t_nr_is_t = substr($ttt[0], 0, 8);
$t_nr_is_t_2 = substr($ttt[0], 8, 5);
$row_desc["nr_is"] = $t_nr_is_t."-".$t_nr_is_t_2;
}
$row_desc['opis'] = $opisanie;
/////////////////////////////////////////////////////////////////////////////////////////////////////
$rez_apparat = odbc_exec($connect, "
select
kod,
gruppa,
imy,
prefiks
from
apparatura
where
kod = '".$row_nap["rtgapparat"]."'
") or die("Error in apparatura.dbf - ". odbc_errormsg($connect));
while($row_apparat = odbc_fetch_array($rez_apparat))
{
$rez_app_gruppa = odbc_exec($connect, "
select
gruppa,
prefiks,
apparati
from
apparat_gruppa
where
gruppa = '".$row_apparat["gruppa"]."'
") or die(error_logs("Error in apparat_gruppa.dbf - ".odbc_errormsg($connect)));
while($row_app_gruppa = odbc_fetch_array($rez_app_gruppa))
{
$rez_personal = odbc_exec($connect, "
select
s_name as doc_opis_name,
f_name as doc_opis_surname
from
personal
where
number = '".$row_nap["id_doc_opis"]."'
") or die(error_logs("Error in personal.dbf - ".odbc_errormsg($connect)));
while($row_personal = odbc_fetch_array($rez_personal))
{
$row_personal["doc_opis_name"] = iconv("cp1257", "utf-8", trim($row_personal["doc_opis_name"]));
$row_personal["doc_opis_surname"] = iconv("cp1257", "utf-8", trim($row_personal["doc_opis_surname"]));
$row_personal["filial"] = "r15";
$info[] = array_merge($row_nap, $row_desc, $row_apparat, $row_app_gruppa, $row_personal);
}
}
}
}
}
echo json_encode($info);
odbc_close($connect);
the database has about ~80-90k rows with data, and I'm using odbc driver to connect to VFP database, also the database is on the remote server... Any advices what I'm doing wrong? Because I can't figure what I'm doing wrong... Thanks for any advice and help!
P.S Also I need to convert that response into JSON and then save it to MySQL database...
EDIT 1
I have the second indexes:
pacientid, data_opis, ocered into the pacient table, opisanie and napravlenie

FPDF - Generate multiple pdf in a single creation

I am trying to generate multiple (in cluster) pdf reports using fpdf in a single click in a php form.
The test_center is the cluster of separate reports. When the submit button is clicked, it will call the php file of fpdf. And my codes aren't working yet.
So far in my php:
<?php
$program="select distinct test_center from sa_sase_result where school_year = '$content' ";
$prog=mysql_query($program);
while($row = mysql_fetch_array($prog))
{
echo '<option>' .$row['test_center'] . '</option>';
}
$message = null;
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(!isset($_POST['depchair'])) {
} else if($_POST['depchair']=="") {
} else {
$input_depchair = addslashes($_POST['depchair']);
$input_depchair = addslashes($_POST['depchair']);
$pro_email="select control_no from sa_student_infoe y where y.test_center = '$input_depchair'";
$pro_address=mysql_query($pro_email);
$address = mysql_result($pro_address, 0);
}
}
?>
EDIT: Here's the generate_pdf.php file.
<?php
require('fpdf/fpdf.php');
mysql_connect("localhost", "root", "1234") or die(mysql_error());
mysql_select_db("final") or die(mysql_error());
$query = "SELECT * FROM sa_student_infoe, sa_student_edubg, sa_sase_result, sa_accounts";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$control_no[] = $row['control_no'];
$surname[] = $row['surname'];
$fname[] = $row['fname'];
$mname[] = $row['mname'];
$app_no[] = $row['activation_code'];
$schoolyear[] = $row['schoolyear'];
$schl[] = $row['high_school'];
$schl_ad[] = $row['address_school'];
$apt[] = $row['aptitude'];
$mth[] = $row['math'];
$lng[] = $row['language'];
$sci[] = $row['science'];
$totgrd[] = $row['total_grade'];
$sx[] = $row['sex'];
}
$ctrl_no = array_shift( $control_no );
$sname = array_shift( $surname );
$firstname = array_shift( $fname );
$midname = array_shift( $mname );
$appno = array_shift( $app_no );
$schyear = array_shift( $schoolyear );
$school = array_shift( $schl );
$school_ad = array_shift( $schl_ad );
$aptitude = array_shift( $apt );
$math = array_shift( $mth );
$lang = array_shift( $lng );
$science = array_shift( $sci );
$gr = array_shift( $totgrd );
$sex = array_shift( $sx );
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','', 12);
$pdf->Cell(0, 0,'Mindanao State University', 0, 1, 'C');
$pdf->Cell(0, 10,'System Admission and Scholarship Examination (SASE)', 0, 1, 'C');
$pdf->Cell(0, 20,'REPORT OF RATING', 0, 1, 'C');
$pdf->Cell(30,5,'Control No:');
$pdf->Cell(100,5,$ctrl_no);
$pdf->Cell(30,5,'School Year:');
$pdf->Cell(-160,5,$schyear);
$pdf->Cell(30,15,'Activation Code:');
$pdf->Cell(10,15,' ' . $appno);
$pdf->Cell(50,40,$sname);
$pdf->Cell(50,40,$firstname);
$pdf->Cell(-120,40,$midname);
$pdf->Cell(15,50,'____________________________________________________________________');
$pdf->Cell(50,60,'LASTNAME');
$pdf->Cell(50,60,'FIRSTNAME');
$pdf->Cell(-50,60,'MIDDLENAME');
$pdf->Cell(-65,90,$school);
$pdf->Cell(67,100,'____________________________________________________________________');
$pdf->Cell(-15,110,'SCHOOL');
$pdf->Cell(-52,140,$school_ad);
$pdf->Cell(57,150,'____________________________________________________________________');
$pdf->Cell(-25,160,'SCHOOL ADDRESS');
$pdf->Cell(.1,190,'--------------------------------------------------------------------');
$pdf->Cell(-35,200,'--------------------------------------------------------------------');
$pdf->Cell(17,230,'AP(30):');
$pdf->Cell(18,230,$aptitude);
$pdf->Cell(17,230,'LU(80):');
$pdf->Cell(18,230,$lang);
$pdf->Cell(17,230,'MA(40):');
$pdf->Cell(18,230,$math);
$pdf->Cell(17,230,'SC(30):');
$pdf->Cell(18,230,$science);
$pdf->Cell(18,230,'GR(180):');
$pdf->Cell(-300,230,$gr);
$pdf->Cell(-10,260,'SEX:');
$pdf->Output("pdf_reports/SASE_report_rating/".$ctrl_no.".pdf", "F");
?>
js:
$("#id_of_generate_it_button").click(function () {
var N = 10;// ten pdf files will be generated and stored to the disk
for (i = 0; i < N; i++) {// 'the loop' -- walk thru all parallel generation processes connected to the event
parameter = N;// just to definite each single generated file
$.get("generate.php?q=parameter", function (data) {// start the ajax process to generate single document
// ?q=parameter i wrote just for passing to the php file some dependent parameter for each single file
// pdf #i generated
});
}// end for parallel generating N pdf files to the disk
});//end click
in generate.php:
$query = "SELECT * FROM sa_student_infoe, sa_student_edubg, sa_sase_result, sa_accounts WHERE some_field = ' . $_REQUEST['q'] . '";// single record from all

mysqli_query insert and update within array not working

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

Categories