anon
anon

Reputation:

HTML & PHP | Filling a select with a query

I have a function that uses mysqli function that is as follows:

public function GetProjectOptions()
{
    $return = "";
    $sql = "SELECT `id`, `project_name` FROM `projects`;";
    $rs  = static::$link->query($sql);
    $return .= '<select class="form-control" name="project">';
    while ($result = mysqli_fetch_assoc($rs));
    {
        $return .= "<option value='" . $result['id'] . "'>" . 
                    $result['project_name'] . "</option>";
    }
    $return .= '</select>';
    return $return;
}

The purpose of this function is to create the options and select that will be used for the Projects on my site, I know that there are 4 projects currently stored in the table, but they do not return in this function, what have I done wrong?

EDIT:

Link to screen output: (http://i.imgur.com/YIYiheH.png)  
Link to code output: (http://i.imgur.com/RZsUIwQ.png)  
Link to code usage: (http://i.imgur.com/4J9rvd7.png)

(Wouldn't let me do normal links)

Upvotes: 0

Views: 54

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74219

I found the problem.

Remove the semi-colon here

while ($result = mysqli_fetch_assoc($rs));
                                         ^

that's why it's not throwing an error, because it's considered as valid syntax.

Your loop is being stopped/terminated by it.

Upvotes: 3

Sean Ryan
Sean Ryan

Reputation: 1

What I think Jay and Styphon mean by their comment is that you don't do any error checking within your SELECT query. Are you sure your query is executing properly? I understand this is a relatively simple query and that you're positive there are four projects currently stored in your table, but it's always a good habit to check. Try this:

public function GetProjectOptions()
{
    $return = "";
    $sql = "SELECT `id`, `project_name` FROM `projects`;";
    $rs  = static::$link->query($sql);
    $return .= '<select class="form-control" name="project">';
    if($rs){
        while ($result = mysqli_fetch_assoc($rs));
        {
            $return .= "<option value='" . $result['id'] . "'>" . $result['project_name'] . "</option>";
        }
        $return .= '</select>';
    }else{
        $message  = 'Invalid query: ' . mysqli_error() . "\n";
        $message .= 'Whole query: ' . $sql;
        die($message);
    }

    return $return;
}

I hope this helps!

Upvotes: 0

Related Questions