Kevin1990
Kevin1990

Reputation: 31

Query not showing any results

I am trying to display a list of records from MySQL database using PHP, but for some reason I can’t get the desired result. Instead of a full list my select box are small an empty — they contain no options. Where’s the error in my code?

<?php
    $con = mysqli_connect('127.0.0.1', 'root', 'toor', 'monster');
    if(mysqli_connect_errno()) {
        echo 'Failed to connect to MySQL' .   mysqli_connect_errno();
    }
    function query() {

        $result = mysqli_query($con, "SELECT * FROM corporations");
        while($row = mysqli_fetch_array($result)) {
            echo '<option value="' . $row['name'] . '">' .$row['name']. '</option>';
        }
    }
?>

<select name='dropdown'>
    <?php query() ?>
</select>

Upvotes: 1

Views: 45

Answers (1)

Dan Smith
Dan Smith

Reputation: 5685

Variable scope. You're defining the connection string outside of the query function and so you cannot use it inside the function with out first passing in to the function in some way.

This should work:

$con = mysqli_connect('127.0.0.1', 'root', 'toor', 'monster');
if (mysqli_connect_errno())
{
    echo 'Failed to connect to MySQL' . mysqli_connect_errno();
}

function query($con)
{
    $result = mysqli_query($con, "SELECT * FROM corporations");
    while ($row = mysqli_fetch_array($result))
    {
        echo '<option value="' . $row['name'] . '">' . $row['name'] . '</option>';
    }
}

query($con); 

Upvotes: 3

Related Questions