0

i am tryng to select 5 mysql rows from the database and display them like $row[1] ect.... in php i am not sure how to do it an someone lead me down the right way please Ok i hav looked a bit more

i wanted it to come out 1 - 5 and i wanted it to display the names

 $result = mysql_query("SELECT * FROM table  ORDER BY id DESC") or die (mysql_error()); 
 while ($row = mysql_fetch_array($result)) { 
  $name = $row['name'];

  $arr = array("somearray" => array(1 => 5, 2 => 9, 3 => 42, 4 => 42, 5 => 42));
  echo $arr["somearray"][1];
  echo $arr["somearray"][2];
  echo $arr["somearray"][3];
  echo $arr["somearray"][4];
  echo $arr["somearray"][5];

  }
1
  • dont have any thats why i am asking for help Commented Oct 23, 2009 at 18:15

4 Answers 4

3

I think the OP wants five ROWS, not COLUMNS. Here is the correct code, assuming you already have a mysql connection open:

$sql = 'SELECT *
    FROM table_name
    ORDER BY col_name
    LIMIT 5';

$result = mysql_query($sql);

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {

    $row[] = $line;

}

// print (access individual rows: $row[0] ... $row[4])
var_dump($row);
Sign up to request clarification or add additional context in comments.

Comments

0

From php.net : https://www.php.net/manual/en/function.mysql-fetch-row.php

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

Comments

0

Try using MySQL's LIMIT clause to limit your results to 5 rows. And use PHP's mysql_fetch_assoc() (returns an associative array) instead of mysql_fetch_row() (returns a numerically indexed array). Also, it's good practice to free the memory associated with the result using mysql_free_result().

$result = mysql_query("SELECT * FROM mytable ORDER BY id DESC LIMIT 5") or die (mysql_error()); 
while ($row = mysql_fetch_assoc($result)) { 
    $name = $row['name'];
    echo $name;
}
mysql_free_result($result);

Comments

0

If you only need to select 5 rows from MySQL you can do this:

SELECT * 
  FROM Table
ORDER BY column
LIMIT 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.