Jason Wood Jason Wood - 6 months ago 8
PHP Question

Array for a SQL database using PHP

Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:

Type....rent_price
a..........100
b..........200
c..........300


I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.

$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");

for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>

<?php echo $set[0];?>
<?php echo $set1[1];?>

Answer

You loop through the results twice, without resetting. Try to loop only once:

$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");

$set = array ();
$set1 = array ();

while ($row = $result->fetch_assoc())
{
  $set[] = $row['type'];
  $set1[] =$row['rent_price'];
}
?>

<?php echo $set[0];?>
<?php echo $set1[1];?>