How to get one column of mysql_query results into an array?

前端 未结 4 590
误落风尘
误落风尘 2021-01-28 02:04

I\'m selecting a single column from a MySQL table with mysql_query(). Is there already a function for getting the results into an array, or will I have to iterate t

相关标签:
4条回答
  • 2021-01-28 02:24

    You have to iterate.

    If you moved into the 21st century, and used mysqli, there's a mysqli_fetch_all() function.... and you'd be able to use prepared statements

    0 讨论(0)
  • 2021-01-28 02:25

    you can do this with mysqli_fetch_all and array_column

    $r = mysqli_query($c,"SELECT bug_name FROM bugs WHERE color='red'");
    $bug_names = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"bug_name");
    
    0 讨论(0)
  • 2021-01-28 02:39

    Nothing like that built in, you will need to do this manually.

    0 讨论(0)
  • 2021-01-28 02:39

    you can use mysql_result function still need to do some coding

    mysql_result($result,$row_num,$fieldname) ;
    

    retrieves $row_num 'th columes $field_name field .

    and following snippet can be taken as an example

    $con =mysql_connect($host,$uname,$passwd);
    mysql_select_db($dbname,$con);
    $result = mysql_query($query,$con);
    $arr = array();
    $numrows = mysql_num_rows($result);
    for($i=0;$i<$numrows;$i++) {
        $arr[] = mysql_result($result,$i,$fieldname);
    }
    

    this stores every elements of column $fieldname to array $arr

    0 讨论(0)
提交回复
热议问题