Page 1 of 1

Query help?

Posted: Wed Apr 16, 2008 7:57 am
by php_novice
Hello,

I was wondering if someone could help me with some code. I want to simply call out a headline from my database. The first, then the second etc...

Code: Select all

 
<? 
// select all records ordered by date 
  $topStory = mysql_fetch_array(mysql_query("Select * FROM  tble ORDER BY id LIMIT 6"));
  $topHead = $topStory['headline'];
?> 
<body>
<? echo $topHead['0']; ?><br />
<? echo $topHead['1']; ?><br />
<? echo $topHead['2']; ?><br />
<? echo $topHead['3']; ?><br />
<? echo $topHead['4']; ?><br />
<? echo $topHead['5']; ?><br />
 
Howeverm it pulls out the first headline letter, then the second! Can anyone help me. I'd really like to do it like this and not in a while loop.

Thank you

Re: Query help?

Posted: Wed Apr 16, 2008 8:06 am
by aceconcepts
What happens if you remove the single quotes:

Code: Select all

 
# <? echo $topHead[0]; ?><br />
# <? echo $topHead[1]; ?><br />
# <? echo $topHead[2]; ?><br />
# <? echo $topHead[3]; ?><br />
# <? echo $topHead[4]; ?><br />
# <? echo $topHead[5]; ?><br />
 

Re: Query help?

Posted: Wed Apr 16, 2008 8:11 am
by php_novice
Nothing, still does the same thing:-(

Re: Query help?

Posted: Wed Apr 16, 2008 8:19 am
by aceconcepts
instead of echoing the value try printing it as an array e.g.

Code: Select all

 
print_r($topStory);
 
And then post it in the forum.

Re: Query help?

Posted: Wed Apr 16, 2008 11:41 am
by flying_circus
php_novice wrote:

Code: Select all

 
<? 
// select all records ordered by date 
  $topStory = mysql_fetch_array(mysql_query("Select * FROM  tble ORDER BY id LIMIT 6"));
  $topHead = $topStory['headline'];
?> 
<body>
<? echo $topHead['0']; ?><br />
<? echo $topHead['1']; ?><br />
<? echo $topHead['2']; ?><br />
<? echo $topHead['3']; ?><br />
<? echo $topHead['4']; ?><br />
<? echo $topHead['5']; ?><br />
 
Couple of things I suspect:

1. Are you getting any results from your query?
Try:

Code: Select all

<?php
print mysql_num_rows(mysql_query("Select * FROM  tble ORDER BY id LIMIT 6"));
?>
You're looking for a value greater than 0. If it's 0 (or errors), there is a problem with your query or no data in the table.

2. Not all php configurations support short tags. It's best practice to use '<?php' and '?>' instead of '<?' and '?>'

3. The code (the way you have it) will only return an array from 1 row of data. It looks like you want 6 different headlines, so you need to do something like this:

Code: Select all

<?php
  $topHead = array();
 
  $res = mysql_query("Select * FROM  tble ORDER BY id LIMIT 6");
  while($topStory = mysql_fetch_array($res)) {
    $topHead[] = $topStory['headline'];
  }
 
  // Finally, call each iteration of the $topHead array
  echo $topHead[0];
  echo $topHead[1];
  echo $topHead[2];
  echo $topHead[3];
  echo $topHead[4];
  echo $topHead[5];
?>