PHP SQL:使用 PDO 查找最小值


PHP SQL: Find smallest value using PDO

我正在尝试使用 PDO 连接在我的 SQL 记录中查找最小值。 记录是 varchar,因此必须转换为 int 才能找到最小记录。 我被困在这个问题上:

mysql_fetch_assoc() expects parameter 1 to be resource, array given

问题是我不知道如何从PDO连接获取资源。 查询有效。

<?php
//load and connect
require("config.inc.php");
        //change varcar to ints and put into array
        $query = "SELECT score FROM easy";
        $stmt   = $db->prepare($query);
        $result = $stmt->execute();
        $rows = $stmt->fetchAll();
        $scoreArray = array();
        $index = 0;
            while($row = mysql_fetch_assoc($rows)){
             $scoreArray[$index] = intval($row);
             $index++;
        }
        $smallest = min($scoreArray);
        $response["success"] = 0;
        $response["message"] = "The min is: ".$smallest;
        echo(json_encode($response));
?>
  1. 您需要将字段转换为 int。
  2. 通过 SQL 查找最小值:

    SELECT min(score) FROM easy
    

虽然从数据库中选择所有记录并在PHP中处理它们不是要走的路。这违背了最基本的原则。数据挖掘是数据库的工作。

    $query = "SELECT min(score) FROM easy";
    $stmt   = $db->prepare($query);
    $result = $stmt->execute();
    $min    = $stmt->fetchColumn();
使用

PDO 时不要使用 mysql_fetch_assoc

取代

while($row = mysql_fetch_assoc($rows)){

foreach ( $rows as $row ){