Getting out of the inner loop and contnuing with the outer loop - php

i have a while loop which is fetching data from csv.Inside while loop there is a condition(if condition) if the condition is true foreach loop will get executed where we want to insert one row at a time into the database.This should continue for every row of the csv. if I have 10 rows in csv,it should insert all 10 rows in the database.But mycode is inserting the first row 10 times.
$handle = fopen($_FILES['upcsv']['tmp_name'], "r");
$count = count(file($_FILES['upcsv']['tmp_name']));
fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$clt = mysql_query("select MCLNTLKNOFLG,MCLNTDKTRNGFRM,MCLNTDKTRNGTO from mclientmst where MCLNTCD ='".$data[1]."'");
if(mysql_num_rows($clt)>0)
{
$clts = mysql_fetch_array($clt);
if($clts['MCLNTLKNOFLG']==1)
{
$i=1 ;
foreach(range ($clts['MCLNTDKTRNGFRM'], $clts['MCLNTDKTRNGTO']) as $num)
{
$dkt = mysql_query("select XCMPCD from xdockethdr where XDKTNO ='$num'");
$ndkt = mysql_query("select XCMPCD from xtempdockethdr where XDKTNO ='$num'");
if(mysql_num_rows($dkt)==0 && mysql_num_rows($ndkt)==0)
{
$date = explode('/',$data[3]);
$dt = $date[2].'-'.$date[1].'-'.$date[0];
$dktid = mysql_query("select MAX(XDKTID) as maxid from xtempdockethdr");
$maxid = mysql_fetch_array($dktid);
$max = $maxid['maxid'] +1;
$query = mysql_query("insert into xtempdockethdr (XCMPCD,XCLNTCD,XDKTNO,XCNSGCD,XDKTPUDATE,XDKTPUTIME,XDKTNOPKGS,XDKTMODLV,XDKTHTOCONCD,XDKTDCTVAL,XDKTDIMWT,XDKTACTWT,XUNIQUEID,XDKTID) VALUES ('".$data[0]."','".$data[1]."','".$num."','".$data[2]."','".$dt."','".$data[4]."','".$data[5]."','".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."','".$data[11]."','".$max."')");
$i++;
}
}
}
}
}
fclose($handle);
header('Location:upload_docketentry.php');

You need to set a break; after your code.
It will close first loop (foreach) and goes down.
Add continue 2; after sql inserts.
this will end this loop and goes to the begining of while loop and continue work.
$handle = fopen($_FILES['upcsv']['tmp_name'], "r");
$count = count(file($_FILES['upcsv']['tmp_name']));
fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) // **#1 point**
{
$clt = mysql_query("select MCLNTLKNOFLG,MCLNTDKTRNGFRM,MCLNTDKTRNGTO from mclientmst where MCLNTCD ='".$data[1]."'");
if(mysql_num_rows($clt)>0)
{
$clts = mysql_fetch_array($clt);
if($clts['MCLNTLKNOFLG']==1)
{
$i=1 ;
foreach(range ($clts['MCLNTDKTRNGFRM'], $clts['MCLNTDKTRNGTO']) as $num)
{
$dkt = mysql_query("select XCMPCD from xdockethdr where XDKTNO ='$num'");
$ndkt = mysql_query("select XCMPCD from xtempdockethdr where XDKTNO ='$num'");
if(mysql_num_rows($dkt)==0 && mysql_num_rows($ndkt)==0)
{
$date = explode('/',$data[3]);
$dt = $date[2].'-'.$date[1].'-'.$date[0];
$dktid = mysql_query("select MAX(XDKTID) as maxid from xtempdockethdr");
$maxid = mysql_fetch_array($dktid);
$max = $maxid['maxid'] +1;
$query = mysql_query("insert into xtempdockethdr (XCMPCD,XCLNTCD,XDKTNO,XCNSGCD,XDKTPUDATE,XDKTPUTIME,XDKTNOPKGS,XDKTMODLV,XDKTHTOCONCD,XDKTDCTVAL,XDKTDIMWT,XDKTACTWT,XUNIQUEID,XDKTID) VALUES ('".$data[0]."','".$data[1]."','".$num."','".$data[2]."','".$dt."','".$data[4]."','".$data[5]."','".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."','".$data[11]."','".$max."')");
$i++;
// continue 2; // Goes to #1
// break; // Goes to #2
}
} // #2 point
var_dump(__LINE__); // This will executed if you place break operator
}
}
}
fclose($handle);
header('Location:upload_docketentry.php');

Related

how to insert multiple array in mysql table

Im trying to insert array in mysql table... but my code doesn't work
$File = 'testfile.csv';
$arrResult = array();
$handle = fopen($File, "r");
$row = 0;
if(empty($handle) === false) {
while(($data = fgetcsv($handle, 1000, ";")) !== FALSE){
$arrResult[] = $data;
$num = count($data); //2100 resultats in my testfile
$row++;
if($row>1){ //ignore header line
for ($c=0; $c < $num; $c++) { //start loop
$sql = '
INSERT INTO MyTable (name, class, level, ability)
VALUES ("'.$data[0].'","'.$data[1].'","'.$data[2].'","'.$data[3].'")
';
$Add=$db->query($sql);
}
}
}
fclose($handle);
};
Result in Mytable:
1,Hero1, Warrior, 65, vitality;
2,Hero1, Warrior, 65, vitality;
3,Hero1, Warrior, 65, vitality;
4,Hero1, Warrior, 65, vitality;
...
You don't need the inner for loop. You're inserting the same row multiple times, since $count is the number of fields in the CSV.
And instead of checking $row each time through the loop, you can simply read the first line and ignore it before the loop.
if(empty($handle) === false) {
fgets($handle); // skip header line
while(($data = fgetcsv($handle, 1000, ";")) !== FALSE){
$sql = '
INSERT INTO MyTable (name, class, level, ability)
VALUES ("'.$data[0].'","'.$data[1].'","'.$data[2].'","'.$data[3].'")
';
$Add=$db->query($sql);
}
}
// remove `for` loop
if($row>1){ //ignore header line
$sql = '
INSERT INTO MyTable (name, class, level, ability)
VALUES ("'.$data[0].'","'.$data[1].'","'.$data[2].'","'.$data[3].'")
';
$Add=$db->query($sql);
}
And of course move to prepared statements to make your code more secure.

CSV import only for certain amount then exceed data go into another table

I have a problem here. I don't know how to give an appropriate question title. So here is my problem.
I have a set of csv data. Let's say 30 data. The condition is I want only 20 data goes to Table A and another 10 data goes to Table B.
Do you have any example on how to work with this logic? Can it be done by combining while loop and if statement? By the way, it is a PHP and I'm still a newbie programmer. Hopefully someone can help me. Thank you.
Edited:
My current code
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($leftPax > 0)
{
$registrantBean = new z_EventRegistrants();
$registrantBean->last_name = $data[1];
$registrantBean->id_no = $data[0];
$registrantBean->phone_mobile = $data[2];
$registrantBean->email1 = $data[3];
$registrantBean->gender = $data[4];
$registrantBean->date_of_birth = $data[5];
$registrantBean->age = $data[6];
$registrantBean->race = $data[7];
$registrantBean->z_eventregec5erations_ida = $registrationBean->id;
$registrantBean->save();
$count++;
error_log(print_r($_REQUEST['session'], 1));
foreach($_REQUEST['session'] as $aid=>$sid)
{
$attendanceBean = new z_EventAttendances();
$attendanceBean->name = $registrantBean->last_name;
$attendanceBean->z_eventsessions_z_eventattendancesz_eventsessions_ida = $sid;
$attendanceBean->z_eventactivities_z_eventattendances_1z_eventactivities_ida = $aid;
$attendanceBean->z_eventregistrations_z_eventattendancesz_eventregistrations_ida = $registrationBean->id;
$attendanceBean->z_eventregistrants_z_eventattendancesz_eventregistrants_ida = $registrantBean->id;
$attendanceBean->save();
}
}
else
{
$waitlistBean = new z_EventWaitlists();
$waitlistBean->name = $data[1];
$waitlistBean->save();
}
}
What I want, the 20 data will go to z_EventRegistrants and the other 10 will go to z_EventWaitlist.
You need to asked some where in your code if the $count == 20
`
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($leftPax > 0 && $count <= 20)
{
$registrantBean = new z_EventRegistrants();
$registrantBean->last_name = $data[1];
$registrantBean->id_no = $data[0];
$registrantBean->phone_mobile = $data[2];
$registrantBean->email1 = $data[3];
$registrantBean->gender = $data[4];
$registrantBean->date_of_birth = $data[5];
$registrantBean->age = $data[6];
$registrantBean->race = $data[7];
$registrantBean->z_eventregec5erations_ida = $registrationBean->id;
$registrantBean->save();
$count++;
error_log(print_r($_REQUEST['session'], 1));
foreach($_REQUEST['session'] as $aid=>$sid)
{
$attendanceBean = new z_EventAttendances();
$attendanceBean->name = $registrantBean->last_name;
$attendanceBean->z_eventsessions_z_eventattendancesz_eventsessions_ida = $sid;
$attendanceBean->z_eventactivities_z_eventattendances_1z_eventactivities_ida = $aid;
$attendanceBean->z_eventregistrations_z_eventattendancesz_eventregistrations_ida = $registrationBean->id;
$attendanceBean->z_eventregistrants_z_eventattendancesz_eventregistrants_ida = $registrantBean->id;
$attendanceBean->save();
}
}
else
{
$waitlistBean = new z_EventWaitlists();
$waitlistBean->name = $data[1];
$waitlistBean->save();
}
}
}
`

while inside while runs just once

I have a problem with this code, the thing is that the inner while just runs once while the outer while does it right. What could be the problem?
Note: $producto_id is an array with ids.
$st_column = 0;
$nd_column = 1;
$posicionArray = 0;
if (($handle = fopen($ruta, "r")) != FALSE) {
fgetcsv($handle);
mysqli_query($link, "BEGIN");
while($producto_id[$posicionArray]){
$ins_producto = mysqli_query ($link, "INSERT INTO productos (encuesta_id, producto_id, nom_producto) VALUES ('".$encuesta_id."', '".$producto_id[$posicionArray]."', '".$nombre_producto[$posicionArray]."')");
while (($data = fgetcsv($handle, 0, "$delimiter")) != FALSE) {
if($producto_id[$posicionArray] == $data[$st_column]){
$ins_cupon = mysqli_query ($link, "INSERT INTO cupones (encuesta_id, producto_id, cupon, estado) VALUES ('".$encuesta_id."', '".$producto_id[$posicionArray]."', '".$data[$nd_column]."', 0)");
}
}
$posicionArray ++;
}
fclose($handle);
}
I believe you have a csv, which holds ids and coupons. It seems you are trying to go through your producto_id array and check if that exists in your CSV. This is what I would do:
CSV:
id,cupon
1,15165165
1,16516151
2,16841684
PHP:
function turn_csv_to_array($csv) {
$result = array();
if (($h = fopen($csv, "r")) != FALSE) {
$header = fgetcsv($h);
while ($row = fgetcsv($h)) {
$result[] = array_combine($header, $row);
}
fclose($h);
}
return $result;
}
$coupons = turn_csv_to_array("test.csv");
$product_ids = [1, 2, 3, 4];
foreach ($product_ids as $pid) {
// INSERT PRODUCT TO PRODUCT_DB
foreach ($coupons as $c) {
if ($pid == $c['id']) {
// INSERT PRODUCT TO COUPONS_DB
}
}
}
It all depends on what you meant by:
($data = fgetcsv($handle, 0, "$delimiter")
if you meant:
($data == fgetcsv($handle, 0, "$delimiter"))
that is the value of data is equal to the result of fgetcsv
then your code is wrong. and switch to "=="
if you mean:
($data = fgetcsv($handle, 0, "$delimiter"))
and fgetcsv can return a "0" then that is why.
using "assignments" in the middle of if statements is always bad practice.
if you do an assignment in the middle of your if statement, the value of the assignment is passed on to the boolean expression. Any value other than 0 is considered true. otherwise a 0 is considered false.

Skipping blank rows with fopen();

I currently have some code like this:
$handle = fopen($_FILES['file']['tmp_name'], "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if($i > 0) {
$sql = "
insert into TABLE(A, B, C, D)
values ('$data[0]', '$data[1]', '$data[2]', '$data[3]')
";
$stmt = $dbh -> prepare($sql);
$stmt->execute();
}
$i++;
}
fclose($handle);
This allows me to write to a certain table the contents of a CSV file, excluding the first row where all the names are. I want to be able to extract only the filled rows. How would I use so using this code?
fgetcsv returns an array consisting of a single null if the rows are empty
http://www.php.net/manual/en/function.fgetcsv.php
so you should be able to do a check based on that.
if ($data[0]===null)
{
continue;
}
or something like that
fgetcsv() returns an array with null for blank lines so you can do something like below.
$handle = fopen($_FILES['file']['tmp_name'], "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if (array(null) === $data) { // ignore blank lines
continue;
}
if($i > 0) {
$sql = "
insert into TABLE(A, B, C, D)
values ('$data[0]', '$data[1]', '$data[2]', '$data[3]')
";
$stmt = $dbh -> prepare($sql);
$stmt->execute();
}
$i++;
}
fclose($handle);
Based on the documentation, fgetcsv will return an array consisting of a single null value for empty rows, so you should be able to test the return value against that and skip blank lines that way.
The following example code will skip processing blank lines. Note that I have changed the file and removed some other logic to make it more easily testable.
<?php
$handle = fopen("LocalInput.txt", "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if($data== array(null)) continue;
var_dump($data);
$i++;
}
fclose($handle);
?>

CSV - not uploading all records

I'm trying to parse a small CSV file and insert the records into MySQL.
The problem I'm having is that the CSV has 150 rows, but only 2 seem to be inserted:
$file = new SplFileObject($uploadedFile);
$separator = ',';
$rowCounter = 1;
$errors = array();
$fh = fopen($uploadedFile, 'r');
if(!$fh) die('File no good!');
// Get headings
$headings = fgetcsv($fh, 0, ',');
$num_cols = count($headings);
$num_rows = 1;
// Read the file as csv
while ($row = $file->fgetcsv($separator)) {
//missed product if num columns in this row not the same as num headings
if (count($row) != $num_cols) {
$row = array_pad($row, $num_cols, NULL);
}
for ($i=0; $i<count($headings); $i++) {
$raw_prod[$headings[$i]] = $row[$i];
}
$item = new Item();
$item->name = $raw_prod['NAME'];
$item->age = $raw_prod['AGE'];
$item->location = $raw_prod['LOCATION'];
$item->save();
}
If I var_dump($item) I get all 150 records, but only 2 ever get inserted.
I just don't understand why this is happening
Thanks
This line
while ($row = $file->fgetcsv($separator)) {
should be
while (($row = $file->fgetcsv($separator)) !== false) {

Categories