我在这里学习 php 和 OOP 编程。我正在尝试修改以下工作代码以防止 sql 注入。其他人向我展示了如何使用 PDO 的想法。但我很难让它发挥作用。
基本上这个功能是通过$uid
和$password
检查用户。我究竟做错了什么?
用户函数.php
<?php
class DB_Functions {
private $db;
function __construct() {
require_once 'db_connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
public function getUser($uid, $password) {
$result = mysql_query("SELECT * FROM users WHERE id = '$uid' AND pswd = '$password'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
return false;
}
}
}
?>
修改代码
<?php
class DB_Functions {
private $db;
function __construct() {
require_once 'db_connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
public function getUser($uid, $password) {
$stmt = $db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
$stmt->execute(array($uid, $password));
return $stmt->fetch();
}
}
?>
检查用户(index.php)
require_once 'include/db_functions.php';
$db = new DB_Functions();
if ($tag == 'login') {
$uid =mysql_real_escape_string($_POST['id']);
$password =mysql_real_escape_string($_POST['pswd']);
// check for user
$user = $db->getUser($uid, $password);
if ($user != false) {
$response["success"] = 1;
$response["user"]["id"] = $user["id"];
echo json_encode($response);
} else {
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}