Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to make an array sort of thing with PHP with my while loop so I can do variables like this $title[1] that would show the first piece of data from the while loop. This is the code I have got.

require("connect.php");
$query = mysql_query("SELECT * FROM `cms_news` LIMIT 3")or die(mysql_error());
while($row = mysql_fetch_assoc($query))
{



}

I know its only a basic while loop, but I honestly don't know how I would go about doing this.

share|improve this question
 
What's in input, what's need on output ? –  zeflex yesterday
 
print_r($row); in the while loop, that should get you started –  Dagon yesterday
add comment

3 Answers

require("connect.php");
$array = array();
$query = mysql_query("SELECT * FROM `cms_news` LIMIT 3")or die(mysql_error());
while($row = mysql_fetch_assoc($query))
{
    array_push($array, $row['columnNameHere'];
}

This will put all variables with the column name 'columNameHere' in the array.

I'm not very sure if this is what you meant, but I guess I'm close

share|improve this answer
add comment

I think I understand were you are heading - you want each field accesible independently? Create some arrays that corresponds to each field :

$title = array();
$name = array(); 
//..etc

$query = mysql_query("SELECT * FROM `cms_news` LIMIT 3")or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
    $title[]=$row['title'];
    $name[]=$row['name'];
    //etc, dont know the fieldnames
}

//now you can
echo $title[1];
echo $name[2];

the arrays are zerobased

share|improve this answer
add comment
require("connect.php");
$query = mysql_query("SELECT * FROM `cms_news` LIMIT 3")or die(mysql_error());
$all_rows = array(); //make an empty array
while($row = mysql_fetch_assoc($query))
{
    $all_rows[] = $row; //add the row to the end of my array
}

Now you can look at $all_rows[0] for the first row, $all_rows[1] for the second row and so on. If you are just going to loop through the array to do things however, you should have just done those things in the while loop.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.