这个代码有什么问题,总是打印结果0.当在phpmyadmin中直接运行查询时,我得到了正确的结果[重复]

I am working on an ajax script, and this php code is giving real tough time by always printing 0 results.

I doubted query so I directly ran it in phpmyadmin and got a row of results. so definitely nothing wrong with query.

Any help?

function processDrpdown($selectedVal) {
    $sql = "SELECT id, name FROM mdl_question_categories where parent = $selectedVal";    
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            echo "Name: " . $row["name"]. "<br>";
            echo "ID: " . $row["id"]. "<br>";
        }
    } else {
        echo "0 results";
    }
    mysqli_close($conn);
    // echo $selectedVal;
}
</div>

When I have to guess what $selectedVal contains I would suggest to make it sql injection save. Maybe this also solves your problem:

$query = "SELECT id, name FROM mdl_question_categories where parent = ?";

if ($stmt = mysqli_prepare($link, $query)) {
    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $selectedVal);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $id, $name);

    if (mysqli_stmt_num_rows($stmt) > 0) {
        /* fetch values */
        while (mysqli_stmt_fetch($stmt)) {
            echo "Name: " . $name. "<br>";
            echo "ID: " . $id . "<br>";
        }
    } else {
        echo "0 results";
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

Beside that: I suggest you use the object oriented style of mysqli. It looks like you are closing the connection after this function but I don't see where you open the connection. You should pass the connection to the function or create it inside the function.

$conn = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

processDrpdown($conn, $selectedVal);

/* close connection */
$conn->close();

Please also have a look at the manual regarding prepared statements: https://www.php.net/manual/en/mysqli.prepare.php

Prepared statements are by the way much easier with PDO but it's an extra module and we don't know if it is installed in your php instance.