0

I was looking for information about parameterized queries, the problem is that I cant find basic examples to follow in php.

Is this correct?

PHP

 $email= $_POST["email"]; //or mysqli_real_escape_string($_POST["email"]);?

SQL

 SET @email = '$email';
 SELECT email FROM users WHERE email=@email

Whit this configuration would be enough to avoid sql injections?

Dan
  • 517
  • 1
  • 3
  • 13
  • 1
    No. If you're concatenating strings into a query string *at all* you're *not* using prepared statements and *you're vulnerable to SQL injection*. – Sammitch Jun 21 '18 at 18:10
  • So, to let this clear, the only way to avoid sql injection is by using prepared statements with mysqli or pdo? – Dan Jun 21 '18 at 19:44

2 Answers2

1

using bind_param is a way to avoid injection like such in php

$stmt = $dbConnection->prepare(' SELECT email FROM users WHERE email=?');
$stmt->bind_param('s', $email); // 's' is string

$stmt->execute();
$result = $stmt->get_result();
//do something with $result

with what you asked in the comment, I think that might work, Im not sure off the top of my head. Another way for multiple in PDO is like

$stmt= $dbh->prepare('SELECT email, user, status, is_new 
                    FROM users 
                    WHERE email=:email 
                    AND user=:user 
                    AND status=:status 
                    AND is_new=:is_new');
$stmt->bindParam(':email ', $calories);
$stmt->bindParam(':user', $user);
$stmt->bindParam(':status', $status);
$stmt->bindParam(':is_new', $is_new);

$stmt->execute();
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
t..
  • 1,101
  • 1
  • 9
  • 22
  • Ok, I understand better, thank you. I have this question, if I want to use for example `email=? AND user=? AND status=? AND is_new=?` do I need to us `bind_param("ssss",$email,$user,$status,$is_new)`...4 "s" together? – Dan Jun 21 '18 at 16:15
  • 1
    If they are all strings then yes, otherwise you need to use the corresponding letter. Check the types part on the php documentation. http://php.net/manual/en/mysqli-stmt.bind-param.php – Dimitris Filippou Jun 21 '18 at 16:22
  • 1
    @Dan I think so, I added another way that might work that way in my edit :) – t.. Jun 21 '18 at 16:23
0

In this case you are open to SQL injection and you would need to use

mysqli_real_escape_string($_POST["email"]);

To insure that SQL Injection would not be possible. However using PDO would be another option. http://php.net/manual/en/book.pdo.php

I hope this helps.

Mo Star
  • 231
  • 2
  • 14