To prevent SQL injection in PHP:
You can achieve this using any of this way:
For MySQLi (MySQL):
$stmt = $dbConnection->prepare('SELECT id, username, email_id FROM users WHERE type = ?');
$stmt->bind_param('s', $userType); // bind parameters
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Note: For MySQLi use can use either Procedural style or Object oriented style(Recommended)
For PDO (PDO is the universal solution for any supported database driver):
$stmt = $this->db->prepare('SELECT id, username, email_id FROM users WHERE type =:user_type');
$stmt->bindValue(':user_type', $userType);
$stmt->execute();
$user_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($user_list as $key => $list) {
echo '<a href="'. $list['id'].'">' . $list['email_id']. '</a></br>';
}
PDO Connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from users') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
And For you the Linking parameter for mysqli
like
$text = $db->mysqli_real_escape_string($text);
Example:
//Escaping characters
$db->real_escape_string('This is an unescaped "string"');
//There is an alias function that you can use which is shorter and less to type:
$db->escape_string('This is an unescape "string"');