2016-02-12 66 views
1

我使用mysqli來執行db查詢。這是我的代碼:綁定中的參數與綁定字段的數量不匹配?

if($stmt = $connection->prepare("SELECT * FROM table1 WHERE code = ?")) 
{ 
    $find = "Op"; 
    $stmt->bind_param("s", $find); 
    $stmt->execute(); 
    $stmt->bind_result($res); 
    $stmt->fetch(); 
    echo "Res => " . $res; 
    $stmt->close(); 
} 

現在的問題是,在這條線:$stmt->bind_param("s", $find); 我得到這個錯誤:

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

注:$connection包含與數據庫建立連接。我做錯了什麼?

+1

你'bind_param()'是好的。問題出在'$ stmt-> bind_result($ res);'。將'SELECT'語句從'SELECT * FROM ...'更改爲'SELECT column1 FROM ...' –

+0

@RajdeepPaul好吧,如果我設置了一個特定的列,如'SELECT column_name'工作,我想'bind_result'我應該設置我想從數據庫中檢索的確切列數?稍後,重複一遍。 – Sandokan

+0

是的,這是正確的。 –

回答

0

你的bind_param()方法很好。問題是這種說法,

$stmt->bind_result($res); 

SELECT聲明你正在做SELECT * FROM ...但在->bind_result()方法你想結果只有一個列與變量綁定$res

所以你prepare()的說法應該是這樣的:

$stmt = $connection->prepare("SELECT column1 FROM table1 WHERE code = ?") 

以後,如果你想通過它循環,你可以這樣做:

while ($stmt->fetch()) { 

    // your code 
    // echo $res . "<br />"; 

} 
-1

按照這樣的正確方法:

<?php 
/* Execute a prepared statement by binding PHP variables */ 
$calories = 150; 
$colour = 'red'; 
$sth = $dbh->prepare('SELECT name, colour, calories 
    FROM fruit 
    WHERE calories < ? AND colour = ?'); 
$sth->bindParam(1, $calories, PDO::PARAM_INT); 
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12); 
$sth->execute(); 
?> 

在你的情況下,它會是這樣:修改

if($stmt = $connection->prepare('SELECT * FROM table1 WHERE code = ?')) 
{ 
    $find = 'Op'; 
    $stmt->bind_param(1, $find, PDO::PARAM_STR); 
    $stmt->execute(); 
    // Fetch column data 
    // $result = $sth->fetchColumn(2); 
    // Fetch all data 
    // $result = $sth->fetchAll(); 
    // echo "<pre>"; 
    // print_r($result); 
    // Fetch only some columns data. 

    $stmt->bindColumn(2, $cals); 

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) { 
     print $cals . "</br>"; 
    }  
} 

注:

You can specify, how many column data you want.

例子:

You have columns like colone, coltwo, colthree, colfour in your table. You write query : select * from tablename. Now you want to show only 2 column (colone,colthree), you can use bindcolumn(). You have to use like this : $stmt->bindColumn('colone', $cal1);$stmt->bindColumn('colthree', $cal3);*

+0

用你正確的方式*你沒有解決手頭的問題。不,問題不在' - > bind_param()'方法中。 –

+0

檢查我更新的答案@RajdeepPaul – Monty

+0

不幸的是,它仍然沒有解決原始問題。請閱讀[我的答案](http://stackoverflow.com/a/35366163/5517143)。順便說一句,我不是那個低估了這個答案的人。 –

相關問題