我正在使用一个简单的表单在我的数据库中的表上运行数据库查询。连接似乎不是问题。表单呈现没有任何问题。当我进入页面时,我收到一个错误,指出我正在尝试获取非对象的属性。这是被调用的特定行:
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>
答案 0 :(得分:0)
这是相当直接的。我已经注意到了清晰度:
// 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";
}
*/