2017-04-02 40 views
0

我在表中有多個行,名爲optionals,我試圖在一個函數中逐一獲取它們。 表包含:從PDO函數數組獲取變量到另一頁

id | name | stock 
1 | article1 | 500 
2 | article2 | 255 

functions.php

function getStocks($mysqli) 
{ 
    $stmt = $mysqli->query("SELECT * FROM optionals"); 
    $result = $stmt->fetch_all(); 

    //get the first row values 
    $nameOptional1 = $result[0][1]; 
    $stockOptional1 = $result[0][2]; 

    //get the second row values 
    $nameOptional2 = $result[1][1]; 
    $stockOptional2 = $result[1][2]; 

    ... //and code continues until I reached the last row 
} 

一個var_dump($result[0])顯示:

C:\wamp64\www\functions.php:42: 
array (size=3) 
    0 => string '1' (length=1) 
    1 => string 'article1' (length=19) 
    2 => string '500' (length=3) 

我想在index.php顯示例如,,但我無法做到這一點。我想是這樣的:

include_once "functions.php";

$nameOptional1 = getStocks($mysqli);

echo $nameOptional1;

2.這是一個很好的方法來獲得使用預處理語句中的每一行的值?如果不是,最好的辦法是什麼?由於Sql注入的不可行性,我只是轉而使用PHP準備好的語句。

+1

你在函數中返回這些變量還是返回它?是否爲你安裝了MySQL本地驅動程序['fetch_all()'](http://php.net/manual/en/mysqli-result.fetch-all.php)?你是否通過php的錯誤報告和查詢來檢查錯誤?如果沒有用戶輸入,則不需要使用準備好的語句。 –

+0

是的,有用戶輸入。 –

+1

看到你發佈的代碼,這似乎並不是這樣。但是,如果涉及用戶輸入,請使用它們。順便說一句,你回答了幾個問題。 –

回答

0
function getStocks($mysqli) 
{ 
    $sql = $mysqli->query("SELECT * FROM optionals"); 
    $result=mysqli_query($con,$sql); 

    // Fetch all 
    mysqli_fetch_all($result,MYSQLI_ASSOC); 

    //get the first row values 
    $nameOptional1 = $result[0][1]; 
    $stockOptional1 = $result[0][2]; 

    //get the second row values 
    $nameOptional2 = $result[1][1]; 
    $stockOptional2 = $result[1][2]; 

    ... //and code continues until I reached the last row 
} 
相關問題