Hey, im new to PHP (started last week) ive got 10 lines of info in a SQLDB im doing the same thing to all 10:

$db_line1 = mysql_query("SELECT * FROM messages WHERE message_id='1'");
$line1 = mysql_fetch_array($db_line1);
unset ($line1['0']);
unset ($line1['1']);
unset ($line1['2']);

$db_line2 = mysql_query("SELECT * FROM messages WHERE message_id='2'");
$line2 = mysql_fetch_array($db_line2);
unset ($line2['0']);
unset ($line2['1']);
unset ($line2['2']);

Etc. etc. all the way to $line10, could i use something like the "foreach" function?


What are you unset-ting there...?

Written by deceze

well when i use mysql_fetch_array it returns the value something twice, once with the collum name and once with one of the numbers.

Written by Diesal11

That's why you use mysql_fetch_assoc. :) Carefully read the manual: php.net/manual/en/function.mysql-fetch-array.php

Written by deceze

ahh ok thanks! im still learning XD

Written by Diesal11

mysql_fetch_assoc is actually slower then mysql_fetch_array($src,MYSQL_ASSOC);, just add the 2nd param.

Written by RobertPitt

@RobertPitt: Where did you get that from?

Written by halfdan

...and how much "slower" are we talking?

Written by deceze

I benchmarked it before, ill do another benchmark now.

Written by RobertPitt

I cant benchmark it atm, i have not got a server installed at work. buti have benchmarked it before as i said on a post that mysql_fetch_assoc should be better and someone said that something that made me benchmark it, and ever since i have changed my ways, @deceze - Surprisingly.

Written by RobertPitt

Accepted Answer

EDIT following author's comment

Take all rows at once

    $db_line = mysql_query("SELECT * FROM messages WHERE message_id >= '1'" .
                           " AND message_id <='10'");

    $rows = array();

    while ($line = mysql_fetch_assoc($db_line))
       $rows[$line['message_id']] = $line;

This way you have an array of rows (ie an array of arrays).

To get the row for message_id 3, just do

   $row = $rows[3];

and to access the (for instance) name column,



Written by ring0
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki