[英]Getting error when trying to fetch data from MySQL using PHP
當嘗試使用PHP從Mysql數據庫中獲取數據時,以下代碼將顯示一條消息:
出現錯誤:
未定義的變量結果。
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
echo <<<_END
<form action="fetchdata.php" method="post"><pre>
Enter Country <input type="text" name="field">
<input type="submit" value="Display Records">
</pre></form>
_END;
if (isset($_POST['field'])) {
$field=$_post($conn,'field');
$query="SELECT * FROM customers WHERE Country = '$field'";
$result=$conn->query($query);
if (!$result) die($conn->error);
}
$rows = $result->num_rows;
代替
$field=$_post($conn,'field');
也許你是說
$field=$_POST['field'];
另外,即使未定義$ result,也要在最后使用$ result:
$rows = $result->num_rows;
同樣,您從不輸出任何數據並進行打印。 您只需將其存儲在變量中。
無論如何:通過將表單數據直接寫到查詢字符串中所進行的操作很危險。 我建議您與命名參數一起使用PDO 。 也可能閱讀有關SQL注入的信息 。
這是另一個有關SQL注入的stackoverflow問題,答案很好。 它包括PDO和mysqli: https : //stackoverflow.com/a/60496/6637731
不知道如何完成對此代碼的請求,一個猜測是isset($_POST['field'])
返回false
,因此變量$result
從未定義,但是無論如何您在$result->num_rows
使用它。
您在以下行中犯了一個錯誤。 它應該是
$field=$_POST['field'];
不
$field=$_post($conn,'field');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.