user181275
user181275

Reputation: 13

Retrieve data from database in an array

Is there any php function that will let me retrieve data from mysql in numeric array. If there's no function for that, how can I do it?

I am trying to retrieve a list of email from a database, but I need to retrieve those emails in a numeric array. I tried this but it's not working.

    $a=mysql_connect("X","X","X");
    mysql_select_db("X",$a);
    function num(){
     $email=mysql_query("select email from X");
     while($re=mysql_fetch_array($email)){
      print $re[0];
      print "<br>";
     }
    }
    num();

Upvotes: 0

Views: 12458

Answers (4)

maiorano84
maiorano84

Reputation: 11951

mysql_fetch_array returns both numerical and associative indexes. Jeroen is correct, in that you can set a second parameter to define what kind of indexing you would like, but consider using this for numerical indexing:

while($re=mysql_fetch_row($email)){

And this for associative indexing:

while($re=mysql_fetch_assoc($email)){

As for your function, you can do something like this:

$a=mysql_connect("X","X","X");
mysql_select_db("X",$a);
$emails = num("select email from X");
function num($query){
    $email=mysql_query($query);
    $results = array();
    while($re=mysql_fetch_assoc($email)){
        $results[] = $re;
    }
    return $results;
}
print $emails[8]['email'];

You should also stop using the mysql_* functions, and consider switching to something like PDO.

Upvotes: 1

Roman
Roman

Reputation: 3843

For an array with numerical keys:

mysql_fetch_row()

Upvotes: 0

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91942

function num(){
 $email=mysql_query("select email from X");
 $result = array();
 while($re=mysql_fetch_array($email)){
  $result[] = $re[0];
 }
 return $result;
}

Upvotes: 0

Jeroen
Jeroen

Reputation: 13257

Replace this line:

while($re=mysql_fetch_array($email)){

With this one:

while($re=mysql_fetch_array($email, MYSQL_NUM)){

Upvotes: 2

Related Questions