简体   繁体   中英

storing values from mysql table into an array in php

I googled around and found no valid solutions. Hope someone here will help. This is my code:

            <?php 
        include "../includes/connection.php";
        $sql_select="SELECT title FROM questions";

        if (!$result=mysql_query($sql_select))
        {
        echo "Error<br>" . mysql_error($sql_select);
        die();
        }
        if (mysql_num_rows($result)==0) {
            echo "No questions!";
        } 
        else {

            $titles = mysql_fetch_array($result);
            print_r($titles);
        }
        ?>

For the purpose of my web application I need to put question titles into a new array. I thought mysql_fetch_array() function creates an array by itself, but I guess I was wrong. Any help? Thanks

You need to move $titles = mysql_fetch_array($result); into a loop like this:

$titles = array();
while ($title = mysql_fetch_array($result)) {
    $titles[] = $title;
}

Another note, remove the argument you've placed in mysql_error() .

$result = mysql_query('select * from table');

$table = array();
while($r = mysql_fetch_array($result) {
    $row = array();
    foreach($r as $k=>$v) {
         $row[$k] = $v;
    }
    array_push($table,$row);
    unset($row);
}

$table will be a 3d array representation of your table. $table[0]['title'] will be the title of it's first 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