2015-02-23 54 views
1

我正在學習PHP和MySQL,我參與了一個小項目,我正在嘗試使搜索功能搜索我的數據庫。當我嘗試加載我的頁面時,它變爲空白。以下是我的search.php頁面的代碼。mysqli php搜索表單空白

<?php 
$mysqli_db = new mysqli('localhost', 'root', 'password', 'train'); 


$result_tb = ""; 
if (!empty($_POST['SEARCH']) && !empty($_POST['search_value']) { 

    $e = $_POST['search_value']; 

    $query = 'SELECT * FROM train2015 WHERE ' . 
     "name LIKE '%$e%'"; 

$query_result = $mysqli_db->query($query); 

$result_tb = '<table cellspacing="5" cellpadding="5">'; 
while ($rows = $query_result->fetch_assoc()) { 
    foreach ($rows as $k => $v) { 
    $result_tb .= '<tr><td>' . $k . '</td><td>' . $v . '</td></tr>'; 
    } 
} 
$result_tb .='</table>'; 

$mysqli_db->close(); 
} 
?> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Search</title> 
</head> 
<body> 
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
    <table> 
     <tr> 
      <td> 
       <input type="text" name="search_value" size="30" maxlength="30"/> 
      </td> 
      <td> 
       <input type="submit" name="SEARCH" value="Search"/> 
      </td> 
     </tr> 
    </table> 
    </form> 
    <?php echo $result_tb; ?> 
    </body> 
    </html> 

感謝您的幫助。

+0

'如果(isset($ _ POST [ '搜索'])'是更好 – 2015-02-23 15:20:09

+0

僅供參考,使用的是'$ _ SERVER [ 'PHP_SELF'];'不安全使用它是這樣的:? '' – lmarcelocc 2015-02-23 15:20:18

+0

您還缺少'if(!empty($ _ POST ['SEARCH'])&&!empty($ _ POST ['search_value']) >>> http://php.net/manual/en/function.error-reporting.php會告訴你,併發出解析錯誤。 – 2015-02-23 15:22:17

回答

3

你錯過了你的條件語句的結束支架,其應閱讀:

if (!empty($_POST['SEARCH']) && !empty($_POST['search_value'])) 
                  ^right there 

然而,最好使用isset()您的提交按鈕,因此這樣做:

if(isset($_POST['SEARCH']) && !empty($_POST['search_value'])) 

error reporting添加到您的文件頂部,這將有助於發現錯誤。

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

// rest of your code 

哪些會發出解析錯誤。

旁註:錯誤報告只能在分期中完成,而不能生成。


此外,在意見中提到,最好使用更安全:

<?php echo htmlspecialchars($_SERVER['PHP_SELF'];) ?> 

而不是你目前正在使用的形式。


一點題外話:

你應該考慮尋找到mysqli with prepared statements,或PDO with prepared statements他們更安全