dongyied24121 2016-01-22 21:29
浏览 31

从PHP中的SQL表中获取单个结果

First I am grateful for the help I received with my question last week, but there's still something I haven't quite figured out.

When I enter a word or term in my search box, to be handled by the code below...

<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {    
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT ID, FirstName, LastName FROM `table` LIMIT 0, 30 ";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result)>0) { 
  // output data of each row
  while($row=mysqli_fetch_assoc($result)) { 
    echo "ID: " . $row["ID"]. " - Name: " . $row["FirstName"]. " " . $row["LastName"]. "<br>"; 
    } 
} else { 
echo "0 results"; 
} 

mysqli_close($conn);
?>

I get all the possible results listed from my SQL table.

So, how do I limit the results to those the end user has entered? I know that I should use either a LIKE or WHERE statement.

If it helps, I am creating a database of medical professionals, their practice names, and locations.

  • 写回答

2条回答 默认 最新

  • duandun2218 2016-01-22 21:47
    关注

    Assuming you have a form that looks like this:

    <form action="" method="post">
        Search: <input name="search" type="text">
    </form>
    

    You could extend your SQL as follows:

    $sql = "SELECT ID, FirstName, LastName FROM `table` ";
    if (isset($_POST['search'])) {
        $search = mysqli_real_escape_string($conn, $_POST['search']);
        $sql .= " WHERE FirstName LIKE '%$search%'
                     OR LastName LIKE '%$search%' ";
    }
    $sql .= " LIMIT 0, 30 ";
    $result = mysqli_query($conn, $sql);
    // ... etc.
    

    To be clear, the "... etc." means that your outputting code remains as-is:

    if (mysqli_num_rows($result)>0) { 
        // output data of each row
        while($row=mysqli_fetch_assoc($result)) { 
            echo "ID: " . $row["ID"]. " - Name: " . $row["FirstName"]. " " . $row["LastName"]. "<br>"; 
        } 
    } else { 
        echo "0 results"; 
    } 
    
    mysqli_close($conn);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数