我怎么能用PDO做mysqli查询?

问题描述 投票:0回答:1

我尝试使用递归函数构建,显示缩进的选项菜单类别。它在mysqli查询中工作得很好,但是我怎么能在PDO查询中做到这一点?

对于任何帮助谢谢。

我改变了一些行,我也改变了正确的数据库连接到PDO,但没有工作。

改变了行:

$dbc = $db->prepare("SELECT * FROM categories ORDER BY title");
$dbc->execute(array());

while (list($id, $parent_id, $category) = $dbc->fetchAll(PDO::FETCH_ASSOC)) {

我的mysqli查询需要更改为PDO:

$db = mysqli_connect("localhost","","","");

echo '<select name="parent_id">
      <option value="">Select</option>';

function make_list ($parent,$depth) {

    global $option;


    foreach ($parent as $id => $cat) {

        $whitespace = str_repeat(' - ', $depth * 1);
        echo '<option value="' . $cat['id'] . '">'. $whitespace . $cat['category'] . '</option>';

        if (isset($option[$id])) {

            make_list($option[$id], $depth+1);

        }
    }
}

$dbc = mysqli_query($db, "SELECT * FROM categories ORDER BY title");

$option = array();

while (list($id, $parent_id, $category) = mysqli_fetch_array($dbc, MYSQLI_NUM)) {

    $option[$parent_id][$id] =  array('category' => $category, 'id' => $id, 'parent_id' => $parent_id);

}
make_list($option[0], $depth = 0);

echo '</select>';

这里有错误消息:

第36行:foreach($ parent为$ id => $ cat){

第56行:while(list($ id,$ parent_id,$ category)= $ dbc-> fetchAll(PDO :: FETCH_ASSOC)){

第58行:$ option [$ parent_id] [$ id] = array('category'=> $ category,'id'=> $ id,'parent_id'=> $ parent_id);

第61行:make_list($ option [0],$ depth = 0);

<select name="parent_id">
      <option value="">Select</option><br />
<b>Warning</b>:  Illegal offset type in <b>/Users/test/Documents/functions/pdo-optionmenu.php</b> on line <b>58</b><br />
<br />
<b>Notice</b>:  Undefined offset: 0 in <b>/Users/test/Documents/functions/pdo-optionmenu.php</b> on line <b>56</b><br />
<br />
<b>Notice</b>:  Undefined offset: 1 in <b>/Users/test/Documents/functions/pdo-optionmenu.php</b> on line <b>56</b><br />
<br />
<b>Notice</b>:  Undefined offset: 2 in <b>/Users/test/Documents/functions/pdo-optionmenu.php</b> on line <b>56</b><br />
<br />
<b>Notice</b>:  Undefined offset: 0 in <b>/Users/test/Documents/functions/pdo-optionmenu.php</b> on line <b>61</b><br />
<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/Users/test/Documents/functions/pdo-optionmenu.php</b> on line <b>36</b><br />
</select>
php mysqli pdo
1个回答
0
投票

由于您的查询中没有不安全的数据,因此无需使用prepare,使用简单的query函数:

$dbc = $db->query("SELECT * FROM categories ORDER BY title");

接下来,fetchAll立即获取所有结果。您需要逐行获取。如果是query,可以这样做

foreach ($dbc as $row) {
    print_r($row);
}

或者使用fetch方法:

while ($row = $dbc->fetch()) {
    print_r($row);
}
© www.soinside.com 2019 - 2024. All rights reserved.