0

I usually put manual sqli parameter checks in place (i.e to check if input is a valid email).

Although in this case, I need to put a user message into my DB

How would this work?

I tried this code, but the whole input gets erased somehow.

<?php

$text = "Hello World";

echo "$text is now ";

$text = stripslashes($text);
$text = mysqli_real_escape_string($text);

echo $text;

?>

Thannk you!

blue ice
  • 173
  • 1
  • 3
  • 9

1 Answers1

0

To prevent SQL injection in PHP:

You can achieve this using any of this way:

  1. 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)

  2. 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"');
Bruce
  • 1,647
  • 4
  • 20
  • 22