Skipping blank rows with fopen(); - php

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

Related

excel file read rows and columns - php

$arr=array();
$row = -1;
if (($handle = fopen("out.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c = 0; $c < $num; $c++) {
$arr[$row][$c]= $data[$c];
}
}
fclose($handle);
}
I'm using this code to read excel file data, this code counts elements in a row that are divided by comma (,),
Name, Surname, Num, Tel
Name
Surname
Num
tel
but in one field I have word Orginal, and this code also divides element by that word like this:
Orgina
l
and in that way, I receive wrong elemnts, any help?
In the line
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
the 1000 is the maximum length of data to read, as your data (in the example posted) has more than that, it will split the data.
To allow it to read the data properly you can just leave the second and third parameters as defaults ( null for length - in other words any length and the default delimiter is a comma anyway...
while (($data = fgetcsv($handle)) !== FALSE) {

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.

PHP Iterating CSV with different columns

I have a CSV defined like the data this.
"PID", "FName", "LName", "Email"
2425751712402934017,
1037862, "Jason", "Van Hooser", "jvanhooser#example.com"
961741, "Alana", "Traxler", "atraxler#example.com"
1100854, "Emily", "Walcheck", "ewalcheck#example.com"
1166892, "Mary", "Thomas", "mthomas#example.com"
8853065679823467777,
1179079, "Donna", "Thimm", "dthimm#example.com"
927671, "Lillian", "Wasson", "lwasson#example.com"
1175139, "Barry", "Tollison", "btollison#example.com"
1058086, "Christina", "Viktorin", "cviktorin#example.com"
What I need to do is iterate through it and when it comes to the lines where there is only the PID field with the long number, I need to store that in a variable ($wkey) and then use it in an insert statement. I know we could put the value on each row but the process that outputs the file cannot do that.
Hwere is my code:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($flag) {
$flag = false;
continue;
}
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
// Use the sql to insert into the table
}
fclose($handle);
How would I modify this to do what I need?
Here's working code:
// skip header line
$data = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// get wkey for lines that has empty second column
if(trim($data[1]) == "") {
$wkey = $data[0];
}
if(trim($data[1]) != "") {
$import = "INSERT into exp_wb_bulk_registrations(`WebinarKey`, `PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
echo $import."<br />";
}
}
fclose($handle);
You could just check the size of $data array. Something like:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(count($data) == 4){
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
// Use the sql to insert into the table
} else if(count($data) == ?) {
//DO STUFF
}
}
fclose($handle);
Here's my variant:
$wkey = ''; // just for sure
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if(count($data)==1) { // hey, we found a wKey! let's remember it
$wkey = $data[0]; continue;
}
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
}
fclose($handle);

PHP dynamically create CSV: Skip the first line of a CSV file

I am trying to import a CSV file. Due to the program we use, the first row is basically all headers that I would like to skip since I've already put my own headers in via HTML. How can I get the code to skip the first row of the CSV? (the strpos command is to cut off the first field in all the rows.)
<?php
$row = 1;
if (($handle = fopen("ptt.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
if(strpos($data[$c], 'Finished') !== false) {
$c++;
echo "<TR> <TD nowrap>" . $data[$c] . "</ TD>"; }
Else{
echo "<TD nowrap>" . $data[$c] . "</ TD>";
}
}
}
fclose($handle);
}
?>
Rather than using if condition for checking whether it is the first row, a better solution is to just add an extra line of code before the line from where the while loop starts as shown below :
....
.....
fgetcsv($handle);//Adding this line will skip the reading of th first line from the csv file and the reading process will begin from the second line onwards
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
.......
.......
It is just as simple......
As you are keeping track of the row number anyway, you can use continue to skip the rest of the loop for the first row.
For example, add this at the start of your while loop (just above $num = count($data)):
if($row == 1){ $row++; continue; }
There are other ways to do this, but just make sure that when you continue, $row is still being incremented or you'll get an infinite loop!
Please use the following lines of code
$flag = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
//your code for insert
}
Having the flag variable as true and setting it to false will skip the first line of the CSV file. This is simple and easy to implement.
put this inside your while loop:
if ($row == 1) continue;
Add this in the body of the while loop above the $row++;:
if ($row == 1) {
continue;
}
$count = 0;
while (($fields = fgetcsv($handle, 0, ",")) !== FALSE) {
$count++;
if ($count == 1) { continue; }
this worked for me:
$count = 0;
while(! feof($file))
{
$entry = fgetcsv($file, 0, ';');
if ($count > 0) {
//skip first line, header
}
$count++;
}
use this code
// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';
if (isset($_FILES['file']))
{
// get the csv file and open it up
$file = $_FILES['file']['tmp_name'];
//$handle is a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
$handle = fopen($file, "r");
try {
// Database Connection using PDO
$dbh = new PDO("mysql:host=$hostname;dbname=clasdb", $username, $password);
// prepare for insertion
$STM = $dbh->prepare('INSERT INTO statstrackertemp (ServerName, HiMemUti, AvgMemUti, HiCpuUti, AvgCpuUti, HiIOPerSec, AvgIOPerSec, HiDiskUsage, AvgDsikUsage) VALUES (?, ?, ?, ?, ?,?, ?, ?, ? )');
if ($handle !== FALSE)
{
// fgets() Gets a line from file pointer and read the first line from $handle and ignore it.
fgets($handle);
// created loop here
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
$STM->execute($data);
}
fclose($handle);
}
}
catch(PDOException $e)
{
die($e->getMessage());
}
echo 'Data imported';
}
else
{
echo 'Could not import Data';
}
?>

How do i remove the top line in a CSV file (the coloumn headers)?

I have put together a script which will upload a CSV file and then extract the data into an already made table. I want to make it so the first line(the column headers) will not be inserted into the table, but the rest of the data will be.
$fp = fopen($_SESSION['filename'],"r");
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE)
{
$import="INSERT into csv_table(name,address,age) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
fclose($fp);
this is the part of the code i use to extract the data from the csv file.
Thank You very much for any help with this matter!
Just put the following before the while loop to read the first line:
fgetcsv($fp, 1000, ",");
Thereafter the while loop starts with the second line instead.
Underthink it.
Create a boolean flag on the outside, and toggle it once you enter the loop instead of importing, using an if statement.
Simply do a blank read as such:
$fp = fopen($_SESSION['filename'],"r");
$headerLine = true;
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE)
{
if($headerLine) { $headerLine = false; }
else {
$import="INSERT into csv_table(name,address,age) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
}
fclose($fp);
You can use out of loop fgetcsv() function and then, after your array, print value second line:
if (($handle = fopen($target_file, "r")) !== FALSE) {
$i=1;
fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo "<pre>";
print_r($data);
echo "</pre>";
$i++;
}
}

Categories