2017-09-01 39 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

相关问题