2014-02-09 121 views
2
public function insert_new_listing($listing_assoc_array) { 
    global $public_connection; 
    $date = (string) date("Y-m-d"); 
    $hit_count = 0; 
    if ($stmt = new mysqli_stmt($public_connection, 'INSERT INTO laptops (brand_name, title, description, price, discount, last_change_date, hit_count) VALUES (?,?,?,?,?,?,?)')) { 
     /* bind parameters for markers */ 
     $stmt->bind_param(
       "sssdisi", 
       $listing_assoc_array['brand_name'], 
       $listing_assoc_array['title'], 
       $listing_assoc_array['description'], 
       $listing_assoc_array['price'], 
       $listing_assoc_array['discount'], 
       $date, 
       $hit_count 
     ); 

     /* execute query */ 
     $stmt->execute(); 

我收到錯誤:變量數與準備語句中的參數數不匹配。變量數與準備語句中的參數數不匹配

我在準備語句和bind_param中有正確的數字(7),所以我不知道爲什麼會發生這種情況。

+1

我的印象是,第一個參數是指定要注入的變量的類型..? [link](http://www.php.net/manual/en/mysqli-stmt.bind-param.php) – Angelo

+0

視爲['mysqli_stmt']](http://php.net/manual/class.mysqli -stmt.php)沒有文檔化的公共構造函數,我會堅持使用'$ public_connection-> prepare()'而不是'new mysqli_stmt()'。我知道這可能是現在的工作,但這些是可以改變的一些事情,恕不另行通知 – Phil

回答

3

正如我在上面的評論中提到的那樣,new mysqli_stmt()永遠不會返回虛假的值。您應該改爲使用mysqli::prepare方法,例如...

public function insert_new_listing(mysqli $conn, array $listing) { 
    $stmt = $conn->prepare('INSERT INTO laptops (brand_name, title, description, price, discount, last_change_date, hit_count) VALUES (?,?,?,?,?,NOW(),0)'); 
    if (!$stmt) { 
     throw new Exception($conn->error, $conn->errno); 
    } 
    /* bind parameters for markers */ 
    $stmt->bind_param('sssdi', 
     $listing['brand_name'], 
     $listing['title'], 
     $listing['description'], 
     $listing['price'], 
     $listing['discount']); 

    /* execute query */ 
    if (!$stmt->execute()) { 
     throw new Exception($stmt->error, $stmt->errno); 
    } 

你可能注意到,我用文字0NOW()代替結合$hit_count$date。看不到任何理由綁定已知的靜態值。

我也傳遞了mysqli實例作爲方法依賴項,而不是依賴於全局變量。

+1

Downvoter關心評論這*接受的*答案? – Phil

相關問題