I have the following code set up and mysql_num_rows echos 2 as it should be. I would like to somehow access the second row which has been selected but can't figure out how. echo $lTitl always returns the title from the first row in the random order, but i would also like to access rows after that. how do i do this?
$sql = "SELECT id, seller, title, kondition, price, shippingcost FROM items WHERE active='1' ORDER BY rand() LIMIT 2";
$item_query = mysql_query($sql, $connect);
foreach ($row = mysql_fetch_assoc($item_query) as $test) {
$id = $row["id"];
$seller = $row["seller"];
$lTitl = $row["title"];
$lCond = $row["kondition"];
//$lPrimIma = $row["primaryimage"];
$lPric = $row["price"];
$lShip = $row["shippingcost"];
}
echo $lTitl;
You can do something like this by storing values in array when looping
You need to use mysql_fetch_all
for retrieving more than one column.
Note that mysql functions are deprecated. Use mysqli or PDO instead
.
foreach ($row = mysql_fetch_all($item_query) as $test) {
$id[] = $row["id"];
$seller[] = $row["seller"];
$lTitl[] = $row["title"];
$lCond[] = $row["kondition"];
//$lPrimIma = $row["primaryimage"];
$lPric[] = $row["price"];
$lShip[] = $row["shippingcost"];
}
echo $lTitl[0]; // will print first row
echo $lTitl[1]; // will print second row
Switch to fetch_all
foreach (mysql_fetch_all($item_query) as $row) {
$id = $row['id'];
// Do all the stuff you want to do here
}
And for the love of Programming, stop using mysql_ functions! See the big red box here:
The result saved into $test
. You have to change into this:
while ($test = mysql_fetch_assoc($item_query)) {
$id = $test["id"];
$seller = $test["seller"];
$lTitl = $test["title"];
$lCond = $test["kondition"];
//$lPrimIma = $test["primaryimage"];
$lPric = $test["price"];
$lShip = $test["shippingcost"];
}
$one = mysql_fetch_assoc($item_query);
$second = mysql_fetch_assoc($item_query);
echo $one["title"]; // first title
echo $second["title"]; // second title
**EDIT**
$titles = array();
while ($row = mysql_fetch_assoc($item_query)) {
$title[] = $row['title'];
}
foreach($titles as $title){
echo $title;
}