Page 1 of 1

fgets() drops lines

Posted: Wed Feb 08, 2006 4:33 pm
by Iganorf
Can anybody see anything in this code that would cause fgets() to drop specific lines?

Code: Select all

$fp = fopen( $filename , "r" );
	if ($fp) {
		fgets( $fp, 4096 );
		while ( !feof( $fp ) ) {
			$line = fgets( $fp, 4096 );
			$buf = explode( "\t", $line );
			
			$query = "INSERT INTO $table VALUES (
			'',
			'',
			'$buf[0]',
			'$buf[1]',
			'$buf[2]',
			'$buf[3]',
			'$buf[4]',
			'$buf[5]',
			'$buf[6]',
			'$buf[7]',
			'$buf[8]',
			'$buf[9]',
			'$buf[10]',
			'$buf[11]',
			'$buf[12]',
			'$buf[13]',
			'$buf[14]',
			'$buf[15]',
			'$buf[16]',
			'$buf[17]',
			'$buf[18]',
			'$buf[19]',
			'$buf[20]',
			'$buf[21]',
			'$buf[22]',
			'$buf[23]',
			'$buf[24]',
			'$buf[25]',
			'$buf[26]',
			'$buf[27]' )";
			$result = mysql_query($query);
		}
		fclose($fp);
	}
I know that the lines end with a newline, and it's always the same lines that get dropped. And yes, I purposefully drop the very first line.

Posted: Wed Feb 08, 2006 4:46 pm
by Iganorf
Nevermind. Man I'm so stupid!

A very select few of the strings that I was inserting into the database had single quotes in them, causing the MySQL query to fail.
How stupid!

Posted: Wed Feb 08, 2006 6:49 pm
by raghavan20
make sure you escape strings with mysql_real_escape_string() with PHP or you can use quote available with mysql...

Code: Select all

QUOTE(str)

Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotes and with each instance of single quote (‘'’), backslash (‘\’), ASCII NUL, and Control-Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotes.

mysql> select quote("o'reilly");
+-------------------+
| quote("o'reilly") |
+-------------------+
| 'o\'reilly'       |
+-------------------+
1 row in set (0.00 sec)

Posted: Wed Feb 08, 2006 11:53 pm
by josh
the mysql QUOTE() function is not a way to escape data going into a mysql_query() function, it must be escaped before it even reaches mysql

Posted: Thu Feb 09, 2006 4:37 am
by raghavan20
jshpro2 wrote:the mysql QUOTE() function is not a way to escape data going into a mysql_query() function, it must be escaped before it even reaches mysql
I agree with you now I thought of a case like this where QUOTE would be a problem...

Code: Select all

//a data like this, 0"reilly
$query = "insert into sometable values ($theabovedata)";
in the above case, it would give up an error...it is good to escape in PHP itself...but then where QUOTE is used???

Posted: Thu Feb 09, 2006 9:33 am
by feyd
when you want the ~thing escaped?