0

In mySQL I have a table with 8 rows, id and status.

$make=mysql_query("SELECT id, status FROM data order by id");

My question is how can I avoid using the foreach or any loop to echo the data, but instead to ave something like

<?php echo $row['status with the id 5']; ?>

and in another place of the page to echo the status with id 8 ?

EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • You can make 2 query's one with id = 5 and the other with id = 8 :D – Rizier123 Dec 18 '14 at 19:38
  • First of all... Why are you getting a collection of data, when you want just 1 row? – Populus Dec 18 '14 at 19:38
  • @Rizier123 is there any way to avoid multiple queries? because the example with 2 status is a sample – EnexoOnoma Dec 18 '14 at 19:39
  • @Populus I want to avoid multiple queries if possible – EnexoOnoma Dec 18 '14 at 19:39
  • You could select all the data first and store the result set to an associative array with the primary id as key. – Œlrim Dec 18 '14 at 19:40
  • @Œlrim yes this something I could do.. Can you help me with the code ? – EnexoOnoma Dec 18 '14 at 19:41
  • What code do you have currently? – Tim Dearborn Dec 18 '14 at 19:42
  • 1
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). – Jay Blanchard Dec 18 '14 at 19:42

1 Answers1

0

You can utilize the following pattern:

$contents = [];

foreach($results as $result) {
    $contents[$result->id] = $result;
}

$results contains the MySQL result set. $contents will be the associative array. It would be more comfortable if you swapped that to a function or class which works for all the tables you want to access applying this pattern. Depending on which database class you use, it might be necessary to cast the key to an integer, otherwise there will be problems accessing the index if it is passed as a string.

Note that you furthermore should migrate your code to MySQLi or PDO first.

If your table is likely to become very big, you should not implement this. Instead, it would be better if you checked in the first place which entries will be needed and load those explicitly with an IN() query.

Œlrim
  • 535
  • 2
  • 13