Arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Arrays

Post by SidewinderX »

I have this code that grabs some info from a database and prints it out. There aren't errors with the following code.

Code: Select all

$result = $db->sql_query("SELECT * FROM `".$prefix."_stories` $querylang ORDER BY `sid` DESC LIMIT 0,4");
for($i = 0; $row = $db->sql_fetchrow($result); $i++) {
  $sid = intval($row['sid']);
  $title = stripslashes(ne_check_html(ne_convert_text($row['title']), 0));
  echo $title . "<br />";
  
}
The above code will print out 4 $titles on a new line, but thats now that I want. I want the 4 titles to be stored as an array so I can display them differently. I tried this, which makes sense to me, but it didn't work

Code: Select all

$result = $db->sql_query("SELECT * FROM `".$prefix."_stories` $querylang ORDER BY `sid` DESC LIMIT 0,4");
for($i = 0; $row = $db->sql_fetchrow($result); $i++) {
  $sid = intval($row['sid']);
  $title = stripslashes(ne_check_html(ne_convert_text($row['title']), 0));
//Array
  $news[i] = $title;  
}
//print the first element
echo $news[0];
Since the array is in the for loop, should it do

Code: Select all

$news[0] = "Article 1"
$news[1] = "Article 2"
$news[2] = "Article 3"
$news[3] = "Article 4"
Assuming Article 1-4 is the value of title at the ith time during the loop, echoing $news[0] should result in "Article 1" should it not? Its not working :?:

Please helo :D
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

You're missing the dollar sign on your $i in the array assignment.

try:

Code: Select all

$result = $db->sql_query("SELECT * FROM `".$prefix."_stories` $querylang ORDER BY `sid` DESC LIMIT 0,4");
while($row=$db->sql_fetchrow($result);){
  $news[]=$row;
}
it's cleaner, and you'll have the entire array at your disposal.
Post Reply