peterb
March 25, 2010, 1:04pm
1
Hello all,
I have a table that I am trying to extract a year from the rows if they exist.
e.g.
1857, the saga of new technology
I have tried to extract and do a type change but it doesn’t seem to work.
// show oldest book
$count5 = mysql_query("select subject from $db_name.$table_name ") or die();
$row5 = mysql_num_rows($count5);
// get current year
$curr_year = date('Y');
for($i=0;$i<$row5;$i++) {
$temp = substr($row['subject'], 1, 6);
$subject_year = (int)$temp;
/*
if ($subject_year > 1000 && $subject_year < $curr_year){
$oldest_book[$i] = substr($row['subject'], 1, 4);
}else{
$oldest_book[$i] = "";
}
*/
}
It only displays zeroes. The subject is a utf-8 string coming out of a table array.
Can someone tell me what I’m doing wrong?
substring index starts at position 0 (zero) not position 1.
Change the
substr($row['subject'], 1, 6)
to
substr($row['subject'], 0, 6)
peterb
March 25, 2010, 1:56pm
3
Hello zalucius,
Thanks for responding. It appears that you caught one of my mistakes.
Here is the corrected version.
// get books by year to determine oldest book
$result = mysql_query("select subject from $db_name.$table_name ")
or die('Query failed: ' . mysql_error()."<br /><br />");
// # of rows returned
$numofrows = mysql_num_rows($result);
// create array
$oldest_book = array();
// get current year for comparison
$curr_year = date('Y');
// extract year and compare
for($i=0;$i<$numofrows;$i++) {
$row5 = mysql_fetch_array ($result);
$temp = substr($row5["subject"], 0, 6);
$subject_year = (int)$temp;
//print $i." - ".$subject_year."<br />";
//if ($subject_year > 1000 && $subject_year < $curr_year)
if ($subject_year != 0)
{
$oldest_book[$i] = $subject_year;
}else{
$oldest_book[$i] = "";
}
}
//print "<pre>";var_dump($oldest_book);print "</pre>";
Have you considered a change to your database, and store the year in a seperate field?
peterb
March 25, 2010, 2:44pm
5
That would be a nice suggestion but I have simply inherited this from the people who use it. Another reason for this was because not every record includes a year.
Not a problem, thanks.