-1

I'm trying to prevent sql injection in my code. so how can i rewrite this code using prepared statement.

This is my first code that work fine but open to sql injection

<?php
    if(isset($_SESSION['em'])){
     $eml = $_SESSION['em'];
    $query = ("select id,fst,las,uid,pass,email,sts,ocp from Users where id !=0");
    $res = mysqli_query($conn,$query);

    if(mysqli_num_rows($res) > 0){


     while($row = mysqli_fetch_assoc($res)){
    $_SESSION['ids'] = $row['id'];
    echo $row['fst'];
    echo $row['ocp'];
    echo $row['las'];

     }
    }
    }
     ?>

how can i use prepared statement for the same code please

C Francis
  • 43
  • 1
  • 9
  • 2
    It looks like you should refer to here: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). This will show your how to use prepared statements. – MinistryOfChaps Jun 19 '17 at 22:16

1 Answers1

1

If you don't use any values in your queries you don't need prepared statements. Only if you insert some values in your where clause for example you should use it.

https://secure.php.net/manual/en/mysqli.quickstart.prepared-statements.php

here is a complete tutorial how to use it. It's not that much complicated. You have to replace your values with placeholders and then bind your param to your query. For example:

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
René Höhle
  • 26,716
  • 22
  • 73
  • 82