简体   繁体   中英

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();

Replace this line:

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

With this one:

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

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.

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

对于具有数字键的数组:

mysql_fetch_row()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM