I’m learning php and OOP programming here. I have below working code I am trying to modify to prevent sql injection. Other people showed me the idea of how to use PDO. But I’m having difficulty getting it to work.
Basically this function is to pass the $uid and $password to check the user.
What am I doing wrong?
user_function.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;
}
}
}
?>
modified code
<?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();
}
}
?>
check for user (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);
}
You’re using PDO, so you can’t use
mysql_real_escape_string(). You don’t need to escape the parameters, as PDO will automatically escape them for you in your prepared query.So, just call
getUser()like this: