問題描述
使用 PHP 變量搜索 SQL 數據庫 (Use PHP variable to search through SQL database)
我有一個名為 $addressdb 的數據庫。我想通過用戶輸入的結果($usersName)搜索該數據庫上的表。我的錯誤可能真的很愚蠢。我是 mySQL 的新手。
<?php
//IF THE LOGIN is submitted...
if ($_POST['Login']){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "addressdb";
$usersName = $_POST['users'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
$result = mysqli_query($conn, $sql);
...
我的錯誤行是
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
更具體地說是變量調用。
參考解法
方法 1:
Best approach is :
$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'";
Here it is not so applicable since you are passing the plain text. But when taking data from html page you should use this way.
方法 2:
Try something like this :
$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'";
方法 3:
You need to use quotes around your $userName.
$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'";
But to be clear, you should escape your user input at least with mysqli_real_escape_string($conn, $userName);
(by LifeofBob、Sanjay Kumar N S、Thomas Rollet、KiwiJuicer)