我正在使用PHP为MySQL数据库构建一个小型Web界面。一个任务是允许用户能够将字符串输入到文本字段中,系统应该返回名称中包含该字符串的任何表的名称。但是,我的问题是,每次进入Web界面时,它都会默认显示所有表名。这是我的完整代码。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<style>
.error {color: #FF0000;}
</style>
<body>
<h1>This is H1</h1>
<?php
$servername = "xxx";
$username = "xxx";
$password = xxx;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$search = $searchErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["search"])) {
$searchErr = "Search keyword is required";
} else {
$search = test_input($_POST["search"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Search Keyword</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Search: <input type="text" name="search" value="<?php echo $search;?>">
<span class="error">* <?php echo $searchErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit"> </form>
<?php
echo '<h2> Search Result: </h2>';
$searchSQL = "SELECT table_name FROM information_schema.tables
WHERE LOWER(table_name) LIKE LOWER('%$search%')
AND table_schema = 'xxx'";
$result = $conn->query($searchSQL);
echo '<form method="POST" action="show_columns.php">'; // opening form tag
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$table_name = $row['table_name'];
echo "<input type='submit' name='table_name' value='$table_name' /> <br/>";
}
} else {
echo ' ';
}
echo '</form>'; // closing form tag
?>
</body>
</html>
例如,每次进入Web端时,搜索结果都会显示所有表名。我假设它可能需要空字符串作为搜索关键字?有关如何解决它的任何想法?提前谢谢!
答案 0 :(得分:0)
这可能不是最干净的解决方案,但我在执行搜索查询之前添加了一个条件
if ($search!='')
{$result = $conn->query($searchSQL);}
else {...}
...
问题解决了。感谢您的所有建议。