18910140161

php - Is it sufficient to prevent SQL injection? - Stack Overflow

顺晟科技

2022-10-19 11:24:26

214

I want to collect client's information from a form.

I am using mysqli_real_escape_string to prevent SQL injection.

Is it sufficient?

IF NOT, how can one do so?

$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
||||

There are multiple ways this can be done... I'd prefer using Jquery/Ajax with an 2 seconds interval and then use an element selector to display the result from database.

Below is a code from our JS file that will do the interval and function to get started: index.js

$(document).ready(function(){
     setInterval(function(){
         fetchMessages()
     },2000);

     //every 2000 milliseconds (2seconds) this function will be called
     function fetchMessages(){
          $.ajax({
               //url refers to the php page that will be handling the sql query
               url: 'messages.php',
               //method is the same as you would in your <form method="POST">
               method: 'POST',
               //data is optional, this is equivalent to having a name attribute 
               //to the submit button that we'll use to test if the name is set 
               //and then pass the other two values, $name & $friend_name, as 
               //data that you use in your query


               data: {'messages':'messages'},
               //I am not sure where you get your name, if your objective is 
               //just to fetch message not send, I have no idea how you get but 
               //then you can include it in the data object as key/value pair 
               //like I did with `messages` because obviously it will be used in 
               //the php/sql scripts
               success:function(response){
               //When we get a response from database, we view it here
                    if(response == ''){
                         //if no message was returned display error message
                         $('#renderMsg').html('<b>0 Messages Found</b>');
                    }else{
                         //else display the message layout
                         $('#renderMsg').html(reponse);
                    }
               }
          })
     }
});

Below is the message.php file that we use to fetch messages from DB.

message.php

<?php
     //normal include your DB connection
     include 'connection.php';
     //create an $output variable to hold dynamic HTML layout
     $output = '';

     //Below we test the 'message' property from the data object we used in JS
     if(isset($_POST['messages'])){
          //I am not sure where you getting the $friend_name from but you can 
          //use the data object in the JS file to send it here along the name 
          //and the 'message' post message
          $sql = "SELECT * FROM chat where sender='$name' AND 
                  reciever='$friend_name' OR sender='$friend_name' AND 
                  reciever='$name' /*ORDER BY id DESC LIMIT 1000*/";

          $result = mysqli_query($mysqli, $sql);
      
          while ($row = mysqli_fetch_assoc($result)) {
              //instead of using echo, we can create a dynamic HTML layout var
              /* echo  $row["sender"].'  to--->';
              $output = $row["reciever"];
              $output .=  $row["timing"].' ';
              $output .= $row["massage"].'<br>';*/
              $output .= '<div><strong>'.$row["sender"].'</strong><br>';
              $output .= '<div style="color:#00e3ae;">'.$row["massage"].'</div> 
                         <div style="text-align:right;"> 
                         <a>'.$row["timing"].'</a></div><hr></div>';                          
          }
          echo $output;
     }
?>

The last step will be the HTML you've provided above that will be used by JS to display anything received from the DB via messages.php

index.php

<div class="bg-dark text-info px-4 py-2 text-center">
    <div class="col-lg-5 mx-auto" style="border:2px solid #00e3ae;height: 
     500px;text-align:left;padding:10px;overflow-y: scroll;" id="chat">
         <div style="background-color: #00e3ae;height: 20px;"></div><br>
             <!-- the div below is where we display everything we got 
             via JS using -->
             <!-- the id selector '#renderMsg' -->
             <div id="renderMsg"></div>
             <form action="massage.php" method="POST">
             <input name="friend_name" value="<?php echo $friend_name; ?>" 
              hidden>
              
             <input type="text" name="massage" required 
              style="width:70%;height:100%;">
              
              <button type="submit" class="btn btn-outline-info btn-lg px-4 me- 
              sm-3 fw-bold">send</button>                                     
           </div>
      </div>
 </div>

This is pretty messy and probably won't be what you are looking for but I once did a project like that and this should be enough to get you started. As you'd notice I didn't change any of your code such as the html layout and the SQL query, I just wanted to provide a solution that will help you find the right direction towards what you are exactly trying to achieve, I hope this will be enough. If not, please feel free to ask any question.

EDIT: regarding the added piece of enquiry In my personal experience I've never experienced problems using mysqli_real_string_escape() But I'd like to suggest that you use PDO which gives you the advantage of using prepared statements. Also I've read somewhere that SQL injections mostly attack certain character set and for this you can define your character set in the client side using: $mysqli->set_charset("utf8"); or $mysqli->set_charset("utf8mb4"); which supports a lot of unicode characters but this has worked for me on mysql version 5.2 and higher, I've never used it on anything lower so I can't be certain.

Thanks!

||||

in your html add the following:

<script>
    setInterval(() => {
        fetch(TheNameOfYourPhpFile)
            .then((r) => r.text())
            .then((r) => (document.getElementById(TheIdOfYourDiv).innerHTML = r))
            .catch((e) => console.log(e));
    }, 2000);
</script>
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航