【问题标题】:PDO Results to arrayPDO 结果到数组
【发布时间】:2015-06-24 07:07:01
【问题描述】:

我从普通的 MYSQL 转移到 PDO MYSQL 并开始使用准备好的语句。使用我的旧系统,我能够查询数据库并将信息存储在数组中。然后我会使用 usort 按金额对表格进行排序。

自从我移至 PDO 后,我在使用阵列时遇到了问题,我摆脱了它。我的原始代码如下:

$sql = "SELECT name, item, cash, props FROM Donators";
$result = $conn->query($sql);
$result_array = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $result_array[] = $row;
        //var_dump($result_array);
    }
} else {
    echo "You have yet to join our servers!";
}
$conn->close();

function custom_sort($a,$b) {
    return $a['cash']<$b['cash'];
 }
usort($result_array, "custom_sort");

这会导致表格按“现金”列排序。下面的代码来自我的 PDO 代码。

    try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT name, item, cash, props FROM Donators"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    $result_array = array();
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
       $result_array[$k] = $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

function custom_sort($a,$b) {
    return $a['cash']<$b['cash'];
 }
//print_r($result_array);
usort($result_array, "custom_sort");
$length = count($result_array);

usort 会导致这个错误:

Warning: Illegal string offset 'cash'

打印数组 $result_array 显示

Array ( [name] => Жэка90 [item] => none [cash] => 1000 [props] => 0 )

【问题讨论】:

  • 您选择不在查询中使用ORDER BY 进行排序的任何具体原因?

标签: php mysql arrays pdo


【解决方案1】:

我使用以下代码:

// In case an error occured during statement execution, throw an exception
if (!$stmt->execute()) {
    // Error handling with $stmt->errorInfo()
}

// Fetch all results
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

之后处理数据不需要foreach循环。

【讨论】:

    【解决方案2】:

    将 for 循环更改为

    foreach($stmt->fetchAll() as $k=>$v) { 
    

    解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 2015-08-26
      • 1970-01-01
      相关资源
      最近更新 更多