Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I′m new in PHP and I′ve realised that my database connection, using a php form (with user and pass text inputs) was totally unsafe:

This was working, but was unsafe:

<?php
$link=mysqli_connect('localhost','xx','xx','xx');
$sql='  SELECT * FROM usuarios 
        WHERE username="'.$_POST['usuario'].'" 
        AND pass="'.$_POST['usuario'].'"
     ';
$rs=mysqli_query($link,$sql);
mysqli_close($link);
?>

So, I′ve read about mysqli_real_escape_string, and decided to try it out:

<?php    
$link=mysqli_connect('localhost','xx','xx','xx');
$usuario=mysqli_real_escape_string($link, $_POST["usuario"]);
$clave=mysqli_real_escape_string($link, $_POST["clave"]);
$sql='  SELECT * FROM usuarios 
        WHERE username="'.$usuario.'" 
        AND pass="'.$clave.'"
     ';
$rs=mysqli_query($link,$sql);
mysqli_close($link);
?>

Is this correct? Is this a good example of how to use mysqli_real_escape_string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
367 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is this correct?

Yes.

Is this a good example of how to use mysqli_real_escape_string?

NO

If ever used, this function have to be encapsulated into some inner processing, and never have to be called right from the application code. A placeholder have to be used instead, to represent data in your query:

$sql='SELECT * FROM usuarios WHERE username=? AND pass=?';

And then, upon processing placeholder marks, this function may be applied (if applicable) but not by itself but along ALL the formatting rules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...