【发布时间】:2015-04-05 23:58:04
【问题描述】:
我正在阅读这本书“Luke Welling Laura Thomson 第四版的 PHP 和 MySQL Web 开发”第 751 页,供熟悉这本书的读者阅读。 然而,书中提供的解决方案是使用 MySQLi DB 连接器,它在测试时工作正常。我想在我的一个使用 PHP PDO 连接器的项目中采用这个解决方案,但是我在尝试得出与教科书相同的结果时遇到了问题。我正在寻求一些帮助来转换 MySQLi 连接器以处理 PDO 过程。这两个示例都使用 MySQL DB。我不确定自己做错了什么并且寻求的帮助很少。
我正在尝试让我的 PDO 过程为子 ID 上的扩展数组生成与原始教科书数组相同的结果。
// Example taken from the text book
function expand_all(&$expanded) {
// mark all threads with children as to be shown expanded
$conn = db_connect();
$query = "select postid from header where children = 1";
$result = $conn->query($query);
$num = $result->num_rows;
for($i = 0; $i<$num; $i++) {
$this_row = $result->fetch_row();
$expanded[$this_row[0]]=true;
}
}
// The print_r form the text book example looks like this:
// result:
mysqli_result Object ( [current_field] => 0 [field_count] => 1
[lengths] => [num_rows] => 3 [type] => 0
)
// expended:
Array ( [0] => 1 ) Array ( [0] => 2 ) Array ( [0] => 4 )
//--------------------------------------------------------------//
// Know, here is my new adopted changes for using PHP PDO connector
function expand_all(&$expanded)
{
// mark all threads with children to be shown as expanded
$table_name = 'header';
$num = 1;
$sql = "SELECT postid FROM $table_name WHERE children = :num";
try
{
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindParam(":num", $num, PDO::PARAM_INT);
$_stmt->execute();
$result = $_stmt->fetchAll(PDO::FETCH_ASSOC);
// get the $expanded children id's
foreach ($result as $key => $value)
{
foreach ($value as $k => $val)
{
$expanded[$k] = $val;
}
}
return $extended;
}
catch(PDOException $e)
{
die($this->_errorMessage = $e);
}
//close the database
$this->_dbConn = null;
}
// The print_r for the result looks like this:
Array ( [0] => Array ( [children_id] => 1 )
[1] => Array ( [children_id] => 2 )
[2] => Array ( [children_id] => 4 )
)
// The return extended print_r for the children id's
// look like this:
Array ( [children_id] => 4);
【问题讨论】:
-
那么你看到了什么不同?