dongzan0108 2019-05-11 05:40 采纳率: 0%
浏览 54
已采纳

这个代码有什么问题,总是打印结果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>
  • 写回答

1条回答 默认 最新

  • douqian6315 2019-05-11 06:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题