I have created my own mvc pattern based on the codeigniter framework style. My problem now is that i want to prevent from SQL injection, and for that purpose i would like to use mysql_real_escape_string(). But for when i use it, it keeps erroring since it apparently don't have a the "link/source" to the database?
I get the php error:
Warning: mysql_real_escape_string(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /hsphere/local/home/../dev/simple_blog/models/users_model.php on line 8
Warning: mysql_real_escape_string(): A link to the server could not be established in /hsphere/local/home/../dev/simple_blog/models/users_model.php on line 8
I don't quite understand why though, since i can get stuff in and out of my DB but for some reason i can't protect it???
Here is my function giving the error
public function getUserByName($username){
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM ".$this->db_table." WHERE username='".$username."' LIMIT 1";
$q = $this->db->query($sql);
if($q->rowCount() > 0){
foreach($q->fetch() as $key => $row){
$data[$key] = $row;
}
return $data;
}
}
As you can see I use mysql_real_escape_string() at the top, and then later on, do query stuff. Anyone know why this don't work and if yes, how would i fix it?
NOTE: Im not a shark to PDO, and $this->db is the PDO class.
To use mysql_real_escape_string
you'll need to connect to the database server first, using the MySQL Functions, which you probably don't have done.
You are mixing up two completely different PHP extensions: mysql and PDO!
Also, you don't need to escape strings, when using PDO prepared statements, that's done via PDO for you.
An example using PDO:
$userDataStmt = $this->database->prepare('SELECT * FROM ' . $this->db_table . ' WHERE username = :username LIMIT 1');
$userDataStmt->bindValue(':username', $username);
$userDataStmt->execute();
if(!$userDataStmt->rowCount() <= 0)
{
$result = $userDataStmt->fetchAll();
}