我使用一个简单的表单对数据库中的表运行数据库查询。连接似乎没有问题。该表单呈现时没有任何问题。然而,当我转到页面时,我收到一个错误,说明我正在尝试获取非对象的属性。这是一条特殊的线路:
if ($result->num_rows > 0){
echo "$result";
}
有什么想法吗?
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result= '';
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customer WHERE Client LIKE '%$searchq%'";
$result = $conn->query($sql);
}
//Display results
if ($result->num_rows > 0) {
echo "$result";
}
else {
echo "0 results";
}
?>
<html>
<head>
</head>
<body>
<form action="Index.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
</body>
</html>
它相当直接。为了清楚起见,我注意到:
// You make it a variable here, with the assumption
// $_POST['search'] will transform it into an object later
$result= '';
// If there is a search variable try to search database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customer WHERE Client LIKE '%$searchq%'";
// All is good if the condition is met
$result = $conn->query($sql);
// This has to go here because you have turned $result into an object now
if ($result->num_rows > 0) {
// Likely you will draw an error here, this is probably an array
// that you will need to iterate over using while()
echo "$result";
}
}
/*
// If you leave it here, if the search is not being done, you've
// assigned $result = '' so you are doing ->num_rows on empty
if ($result->num_rows > 0) {
echo "$result";
}
*/