简体   繁体   中英

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>

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); 

Change this

while($row = mysqli_fetch_array($result)) {

with this

while($row = mysqli_fetch_assoc($result)) {

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