Page 1 of 1

substr not doing what the manual says for me! [SOLVED]

Posted: Sat Mar 17, 2007 4:16 pm
by andym01480

Code: Select all

echo "Uncut query: $query2 <p>";
$query2=substr($query2,0,-1); //should just get rid of the last character?
echo "Cut query: $query2<p>";
produces:

Uncut query: INSERT INTO `caldate`(`startdate`,`enddate`,`starttime`,`endtime`,`event_id`) VALUES('2007-03-19','2007-03-19','00:00','12:00','41'), ('2007-03-20','2007-03-20','00:00','12:00','41'), ('2007-03-21','2007-03-21','00:00','12:00','41'), ('2007-03-22','2007-03-22','00:00','12:00','41'), ('2007-03-23','2007-03-23','00:00','12:00','41'), ('2007-03-24','2007-03-24','00:00','12:00','41'),

Cut query: INSERT INTO `caldate`(`startdate`,`enddate`,`starttime`,`endtime`,`event_id`) VALUES('2007-03-19','2007-03-19','00:00','12:00','41'), ('2007-03-20','2007-03-20','00:00','12:00','41'), ('2007-03-21','2007-03-21','00:00','12:00','41'), ('2007-03-22','2007-03-22','00:00','12:00','41'), ('2007-03-23','2007-03-23','00:00','12:00','41'), ('2007-03-24','2007-03-24','00:00','12:00','41'),

which kills the mysql_query because of the last comma.

So what have I done wrong? The manual has this!

Code: Select all

$rest = substr("abcdef", 0, -1);  // returns "abcde"

Posted: Sat Mar 17, 2007 4:20 pm
by Kieran Huggins
maybe collect them in an array then implode(',',$vals); ?

Posted: Sat Mar 17, 2007 4:28 pm
by andym01480
I built the query in the first place using a loop, so could just do individual queries.
I thought it would be neater that way, but would need to loose the last comma. Why doesn't substr do it?

Posted: Sat Mar 17, 2007 4:31 pm
by Kieran Huggins
likely because you have an invisible \n character in there after the last ,

Posted: Sat Mar 17, 2007 4:35 pm
by andym01480
Afraid not!

Code: Select all

$query2=trim(substr($query2,0,-1));
didn't clear it!

Posted: Sat Mar 17, 2007 4:37 pm
by Kieran Huggins
you have those in the wrong order...

Code: Select all

$query2=substr(trim($query2),0,-1);

Posted: Sat Mar 17, 2007 4:52 pm
by andym01480
Absolutely :roll: and it worked. Thanks!

Posted: Sat Mar 17, 2007 5:10 pm
by nickvd
Kieran Huggins wrote:maybe collect them in an array then implode(',',$vals); ?
Agreed...

Code: Select all

for ($i=this;$i<=that;$i++) {
  $values[] = "('2007-03-19','2007-03-19','00:00','12:00','41')";
}
$sql = 'INSERT INTO ..... blah blah ..... VALUES '.implode(',',$values);
Works much nicer in my opinon. :D

Posted: Sat Mar 17, 2007 5:23 pm
by andym01480
Agreed - looks like tidier code to me! 'Tis modified.