php连接数据库显示列表并根据地输入查讯实例

发布于 2023-02-18  164 次阅读


已请求,请等待...

<?php
$servername = "localhost";
$username = "cs";
$password = "123456";
$dbname = "cs";
 
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
 
// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
} 
echo "连接成功";

$sql = "SELECT id, nass FROM cass";
$result = $conn->query($sql);
 
if ($result->num_rows > 0) {
    echo "<table><tr><th>ID</th><th>Name</th></tr>";
    // 输出每行数据
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["nass"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 结果";
}

// 搜索框
echo '<form action="" method="get">
<input type="text" name="nass" placeholder="搜索nass">
<input type="submit" value="搜索">
</form>';

$nass = $_GET['nass'];
$sql = "SELECT id, nass FROM cass WHERE nass LIKE '%$nass%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>ID</th><th>Name</th></tr>";
    // 输出每行数据
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["nass"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 结果";
}

$conn->close();
?>