【发布时间】: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进行排序的任何具体原因?