簡體   English   中英

我如何使用PDO進行mysqli查詢?

[英]How can i do that mysqli query with PDO?

我嘗試使用遞歸函數進行構建,該函數顯示執行縮進的選項菜單類別。 它在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>

由於查詢中沒有不安全的數據,因此無需使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM