试图用PHP学习预处理语句,但我无法让它工作

时间:2017-11-14 20:41:21

标签: php sql mysqli prepared-statement php-7

下面是我的函数listRecordsMatching($ accNo),它连接到我的mySQL服务器以匹配具有特定帐号的所有记录。我知道我的问题在于我编写SQL的方式。

我的表格结构如下:(int)id,(string)check-no,(double)amount,(date)check-date,(string)customer,(int)account。

注意:conn()是我的配置文件中的一个全局函数,它返回连接到我的服务器的mysqli对象。

编辑:由于conn()函数导致一些混淆:

EDIT2:我找到了答案。执行$ stmt-> execute()之后,我必须将结果绑定到变量才能使用它们。 $ stmt-> bind_results($ var1,$ var2,...)

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$GLOBALS['conn'] = $conn;
function conn(){
    return $GLOBALS['conn'];
}


function listRecordsMatching($accNo){
    //prepare statement
    $stmt = conn()->prepare("SELECT * FROM `mfs-cheque-app`.`cheques` WHERE `account` = ?");
    $stmt->bind_param('i', $accNo);
    $stmt->execute();
    $row=$stmt->fetch(PDO::FETCH_ASSOC);
    var_dump($row) // outputs NULL
    echo "<form id='records'>1";
    while(true){
        if (!$row) break;
        $c = new Cheque($row['cheque-no'],$row['amount'],$row['cheque-date'],$row['customer'],$row['account']);
        echo $c->list(); // outputs formatted html
    }
    echo "2</form>";
}
OUT>>> NULL<form id="records">12</form>

1 个答案:

答案 0 :(得分:1)

您正在使用2个不同的变量$accNo$account ...更改其中一个以匹配另一个变量,它可能会开始工作。