简体   繁体   中英

How do I skip empty result or errors in this loop?

I do have a loop which store data into mysql...

/connect to your database 
//read your text file into an array, one entry per line

$lines = file('name.txt'); 

//loop through each website URL you read from the file 
foreach ($lines as $name) { 

//do some code
//Insert data to MySQL
 mysql_query("INSERT INTO table (data1,data2) VALUES ('$data1','$data2')");

} 

My problem is when the code returns empty..then it gives error and stop...so how can I skip this and continue to next name so loop wont stop until it finished?

foreach($lines as $line){
    if(empty(trim($line)){ continue; }
    // do your insert, etc.
}

If all you you want to do is check for an empty line, this will do that.

Good luck!

You could try opening the file like so:

file('name.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

which might work, according to the documentation for file on php.net.

Empty-Check: if(trim($var) == '')

if you want to use if(empty(trim($var))) , please read the manual entry for empty:

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

Skip the rest of the current loop iteration : If you can check this then you can use continue . This skips the actual loop and continues with the next.

Reading files : As Phoenix mentioned, the following code gives you an array which represents the file:

// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

FILE_IGNORE_NEW_LINES removes \\n, but lets some empty elements in your array. FILE_SKIP_EMPTY_LINES and FILE_IGNORE_NEW_LINES together remove empty line. empty means only \\n is in this line! If you have a space character in it, it's not empty!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM