使用 PHP 變量搜索 SQL 數據庫 (Use PHP variable to search through SQL database)


問題描述

使用 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 LifeofBobSanjay Kumar N SThomas RolletKiwiJuicer)

參考文件

  1. Use PHP variable to search through SQL database (CC BY‑SA 2.5/3.0/4.0)

#post #MySQL #Database #PHP #web-scripting






相關問題

將 xml 從經典 asp 發佈到 asp.net (Posting xml from classic asp to asp.net)

POST 和 PUT HTTP 請求有什麼區別? (What's the difference between a POST and a PUT HTTP REQUEST?)

使用 formdata 發布數組 (Posting array using formdata)

儘管表單,Django POST dict 為空 (Django POST dict empty despite form)

表單提交為空 (Form submission empty)

ajax post 只看到第一個參數 (ajax post only sees first param)

使用 PHP 變量搜索 SQL 數據庫 (Use PHP variable to search through SQL database)

表單不通過 Post 發送數據 (Form not sending data through Post)

在 PHP 中使用 cURL 的 RAW POST (RAW POST using cURL in PHP)

使用 php 和 curl 更新 mediawiki (using php and curl to update mediawiki)

在 python 中開發時,如何在 post 請求中使用“format=json&data=”? (How do I use "format=json&data=" in post requests when developing in python?)

Nodejs GET 和 POST 在實時服務器中混合,但在 localhost 中工作 (Nodejs GET and POST mixed up in live server but working in localhost)







留言討論