2017-09-01 103 views
-2

我在使用bind_param()時不斷收到跟隨錯誤,並試圖用一切方法解決它,但似乎沒有任何效果。當在php中使用bind_param()時出現錯誤

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

這裏是我的代碼

$output = ''; 
$output2 = ''; 
$output3 = ''; 

    if(isset($_POST['search'])) { 
    $search = $_POST['search']; 
    $search = preg_replace("#[^0-9a-z]i#","", $search); 



    if ($stmt = $db->prepare("SELECT * FROM Users WHERE name LIKE '%$search%'")){ 
    $stmt->bind_param("s", $search); 
    $count = $stmt->num_rows(); 
    $stmt->execute(); 


    if($count == 0){ 
     $output = "There was no search results!"; 

    }else{ 

     while ($rows = $stmt->num_rows) { 

     $name = $row ['name']; 
     $location = $row ['location']; 
     $gender = $row ['gender']; 
     $date_of_birth = $row ['date_of_birth']; 
     $picture = $row['url']; 



     $output .='<form action="header.php" method="post"><div class="row"><div class="col-sm-3">'.$name.'<br>'.$location.'<br>'.$gender.'<br>'.$date_of_birth.'</div>'; 

     $output2 = '<div class="col-sm-3"><img src="upload/'.$picture.'"width="180" height="144" /></div></div>'; 

     $output3 = '<input id="add_friend" name= "addfriend" type="submit" value="Add As Friend" /></form>'; 

     } 

    } 
    } 
+4

你沒有佔位符,但綁定一個值。 – Qirel

+0

請詳細解釋一下 – Rebekah

+3

請打開手冊。 –

回答

1

您需要將值綁定到查詢字符串的佔位符?。然後你需要看看你傳遞給bind_param()的參數 - 第一個參數應該是變量的類型 - 在這種情況下,$search只是一個字符串,所以第一個參數應該是s

此外,您應該注意,$stmt->num_rows屬性,而不是一種方法。除非先存儲結果,否則此屬性可能不準確(也就是說,它可能會在取得結果之前顯示零行),首先使用$stmt->store_result()。在執行之後,這兩者都需要到達

然後你需要使用bind_param()綁定結果。這意味着綁定查詢選擇的每一列。因此,最好選擇你正在尋找的特定列,而不是做SELECT *。當您現在獲取時,它應該是提供給while的單個參數,而不將其分配給變量。

$search = "%$search%"; 
if ($stmt = $db->prepare("SELECT name, location, gender, date_of_birth, url FROM Users WHERE name LIKE ?")){ 
    $stmt->bind_param("s", $search); 
    $stmt->execute(); 
    $stmt->bind_result($name, $location, $gender, $date_of_birth, $picture); 
    $stmt->store_result(); 
    $count = $stmt->num_rows; 

    if ($count == 0) { 
     $output = "There was no search results!"; 
    } else { 
     while ($stmt->fetch()) { 
      // You can use $name, $location, $gender, $date_of_birth, $picture here 
      $output .='<form action="header.php" method="post"><div class="row"><div class="col-sm-3">'.$name.'<br>'.$location.'<br>'.$gender.'<br>'.$date_of_birth.'</div>'; 

      $output2 = '<div class="col-sm-3"><img src="upload/'.$picture.'"width="180" height="144" /></div></div>'; 

      $output3 = '<input id="add_friend" name= "addfriend" type="submit" value="Add As Friend" /></form>'; 
     } 
    } 
} 
+0

感謝您解釋,但我現在似乎得到以下錯誤致命錯誤:超過30秒的最大執行時間 – Rebekah

+0

你仍然有'while($ rows = $ stmt-> num_rows){''在代碼中的某處?因爲如果'$ stmt-> num_rows'大於零,那會運行到無窮大。 – Qirel

+1

我仍然有它,我現在已經把它拿出來,它已經解決了這個問題,謝謝你的幫助 – Rebekah

相關問題