0

how to prevent sql injection by using escape string or other method?? i do have some codes, but i not sure how to do? any help?

<?php
                            if (isset($_POST['submit'])){
                            session_start();
                            $username = $_POST['username'];
                            $password = $_POST['password'];
                            $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
                            $result = mysql_query($query)or die(mysql_error());
                            $num_row = mysql_num_rows($result);
                                $row=mysql_fetch_array($result);
                                if( $num_row > 0 ) {
                                    header('location:dashboard.php');
                            $_SESSION['id']=$row['user_id'];
                                }
                                else{ ?>
                            <div class="alert alert-danger">Access Denied</div>     
                            <?php
                            }}
                            ?>
lye yan nian
  • 143
  • 2
  • 12
  • You need to validate/sanitize your POST vars first of all, and upgrade to mysqli/PDO rather than mysql – EternalHour Nov 03 '14 at 08:05
  • first, using plain password is evil. Id recommend to get familiar with some orm rather then reinventing wheel – Serg Nov 03 '14 at 08:07
  • 1
    Don't use mysql. This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. About your question, [check this answer](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – jherran Nov 03 '14 at 08:07
  • search before asking. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?lq=1 – Josua Marcel C Nov 03 '14 at 08:11
  • I am still new to PHP for your informations. a lot of things still need to be picked up. yes i am using the old tutorial to do these codes. thanks for telling me all this – lye yan nian Nov 03 '14 at 08:16

2 Answers2

3

Use PDO and not the old mysql function which is deprecated and will be removed in the future:

$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO table ( field1, field2, field3)
                 VALUES ( :field1, :field2, :field3";

$q = $conn->prepare($sql);
$q->execute(array(':field1'=>$field1,
                 ':field2'=>$field2,
                 ':field3'=>$field3
                 ));
Grant
  • 2,413
  • 2
  • 30
  • 41
0

you can pass these two POST variables in escape method

 $username = mysql_real_escape_string($_POST['username']);
 $password = mysql_real_escape_string($_POST['password']);
Paul
  • 8,974
  • 3
  • 28
  • 48
A.B
  • 20,110
  • 3
  • 37
  • 71