我有一个包含3列的SQL表:client_id
,domains
和comment
。在我的PHP页面上,我有一些文本框,允许用户从表中搜索特定的客户端ID或域。但是,在搜索时,它会带回表中的每个结果,而不仅仅是例如client_id
78的结果。
我尝试将值硬编码到语句中,如下所示:
$sql = "SELECT client_id, domain, comment FROM FirstAttempt WHERE client_id = '78' OR domain = 'sausage'";
这很好用。
我的问题是;如何编辑该行代码,以便搜索输入到文本框中的内容?
我的完整代码在下面..
ini_set('display_errors', 1); error_reporting(E_ALL);
$servername = "localhost";
$username = "Dylanc";
$password = "xxxx";
$dbname = "FirstAttempt";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT client_id, domain, comment FROM FirstAttempt WHERE client_id = '78' OR domain = 'sausage'";
$result = mysqli_query($conn, $sql);
if (!$result) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Client ID: " . $row["client_id"]. " - Domain: " . $row["domain"]. "Comments:" . $row["comment"];
}
} else {
echo "0 results";
}
$conn->close();
使用该php的形式就是这个......
<form action="Search-Call.php" name="FirstAttempt" method="POST">
<font face="impact" color="white">Client ID:</font>
<input type="text" name="client_id" ><br>
<br>
<font face="impact"color="white">Domain:</font>
<input type="text" name="domain"><br>
<br>
<input type="submit" value="Send" name="submit">
<input type="reset" value="Reset">
</form>
答案 0 :(得分:0)
你必须替换这行代码:
$sql = "SELECT client_id, domain, comment FROM FirstAttempt WHERE client_id = '78' OR domain = 'sausage'";
由此:
$client_id = $conn->real_escape_string($_POST['client_id']);
$domain = $conn->real_escape_string($_POST['domain']);
$sql = "SELECT client_id, domain, comment FROM FirstAttempt WHERE client_id = '$client_id' OR domain = '$domain'";
当然,您可能希望在构建SQL查询之前添加更多验证代码(超过$ client_id和$ domain变量)。