如何在PHP中执行搜索?

时间:2015-12-31 09:05:40

标签: php mysql

我想使用php从数据库执行搜索,当我输入名称arun时,它应搜索名称arun并显示名称为arun的结果,当我输入名称和电子邮件时,它应搜索姓名和电子邮件,并且应该显示单个结果,因为电子邮件是唯一的字段我写了以下代码,但它不工作可以有人帮助我吗? 如果任何人给出Downvote和为什么,请添加评论?

<?php

if (isset($_SESSION['message11'])) {
    echo $_SESSION['message11'];
    unset($_SESSION['message11']);
}
?>

<?php

include('connection.php');
$name = $_POST['name'];
$email = $_POST['email'];
$qualification = $_POST['qualify'];
$sql = "SELECT * FROM form WHERE Name ='$name' OR EmailAddress = '$email' OR Qualification = '$qualification' ";
$result = $conn->query($sql);

if (!empty($_POST)) {
    if ($result->num_rows === 0) {
        echo '<p style="margin-left:340px">no records</p>';
    }
}



while ($row = $result->fetch_assoc()) {
    $_SESSION["snum"] = $row['sno'];
    $_SESSION["nam"] = $row['Name'];
    $_SESSION["quali"] = $row['Qualification'];
    $_SESSION["emai"] = $row['EmailAddress'];

    echo '<br>';
    echo '<form name="friend" action="received.php" method="post">';
    echo '<input style="margin-left:340px;padding-bottom:10px" type="checkbox" value="' . $row['sno'] . '" name="friend[]">&nbsp;user Details</input>';
    echo '<br>';
    echo '<br>';
    echo '<div class="container" style="border-style:solid; border-width:medium;width: 550px;">';
    echo '<br>';
    echo 'Name: ' . $row['Name'];
    echo '<br /> EmailAddress: ' . $row['EmailAddress'];
    echo '<br /> Qualification: ' . $row['Qualification'];
    echo '<br /> DOB: ' . $row['DOB'];
    echo '<br/>';
    echo '<br/>';

    echo '<br/>';
    echo '<br/>';

    echo '</div>';
    echo '<br/>';
}

if (!empty($_POST)) {
    echo '<button style="margin-left:340px" type=""submit">invite</button>';
}
echo '</form>';
$conn->close();
?>

2 个答案:

答案 0 :(得分:0)

您正在向三个字段添加OR条件,即使用户未输入这些字段。

使用条件以便sql只搜索输入的字段。

使用array()

$sql = "SELECT * FROM form WHERE ";
$conditions = array();
if (! empty($name)) {
  $conditions[] = "Name ='$name'";
}
if (! empty($email)) {
  $conditions[] = "EmailAddress ='$email'";
}
if (! empty($qualification)) {
  $conditions[] = "Qualification ='$qualification'";
}
$sql .= ! empty($conditions) ? implode(' OR ', $conditions) : '1';
$result=$conn->query($sql);

答案 1 :(得分:-1)

尝试此 LIKE 将有效搜索内容。

简单和最佳实践。

SELECT * FROM form WHERE Name LIKE '%".$name."%' OR EmailAddress LIKE '%".$email."%' OR Qualification LIKE '%".$qualification."%'