0

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();
1
  • I tried this to put these emails in a numeric array but it won't work $fr=explode("<br>",num()); Commented May 12, 2012 at 15:58

4 Answers 4

2

Replace this line:

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

With this one:

while($re=mysql_fetch_array($email, MYSQL_NUM)){
Sign up to request clarification or add additional context in comments.

2 Comments

When I try to print a specific email I get this error: undefined offset: 8 (If I try "print $re[8]";)
Of course, that's because $re is one row, so you are printing the 8th column of that row
1

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.

Comments

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

Comments

0

For an array with numerical keys:

mysql_fetch_row()

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.