1

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

3
  • 1
    What are you getting when you do the print_r? Commented Dec 15, 2010 at 22:23
  • 1
    @Farid: He probably gets one result. Commented Dec 15, 2010 at 22:25
  • 2
    FYI don't pass the $sql_select string to mysql_error. Check the docs. Commented Dec 15, 2010 at 22:26

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

I can't accept it sooner than I'm allowed to. I will, don't worry :)
I would still declare $titles as $titles = array(). Makes the code easier to understand.
@Felix: Good point, it also makes sure there aren't any problems with other variables of that name defined previously.
2
$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.

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.