Protect from sql Injection in php

Asked

Viewed 1,769 times

0

I have this code to insert:

$name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
$unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';
if (!empty($name) && !empty($unid)) {  
    echo 'true';
} else {
    echo 'false';
}    
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE);
    //Count total number of rows
    $rowCount = $query->num_rows;   
$conn->close(); 

Wanted to protect from sql Injection, someone can help?

2 answers

1


Try this

//trim ignora uso de espaço antes e depois da palavra ou frase
          //strip_tags não interpreta o uso de tags dentro do input
         $nome = trim(strip_tags($_POST['nome']));
         $cronica = trim(strip_tags($_POST['cronica']));
         $sintomas = trim(strip_tags($_POST['sintoma']));
         $descri = trim(strip_tags($_POST['desc']));
         $insert = "INSERT INTO tb_doenca(nome_doenca,doenca_cronica,sintomas_doenca,desc_doenca) VALUES (:nome,:cronica,:sintomas,:descri)";

         try{
          //Proteção contra SQLINJECT
          $result = $con->prepare($insert);
          $result->bindParam(':nome',$nome,PDO::PARAM_STR);
          $result->bindParam(':cronica',$cronica,PDO::PARAM_STR);
          $result->bindParam(':sintomas',$sintomas,PDO::PARAM_STR);
          $result->bindParam(':descri',$descri,PDO::PARAM_STR);
          $result->execute();

I took it from a code I had before... try to replace the values

1

I am not an expert in Protection for SQL Injection, but I will share a code that helped me a lot.

function protect( &$str ) {
 /*** Função para retornar uma string/Array protegidos contra SQL/Blind/XSS Injection*/
        if( !is_array( $str ) ) {                      
                $str = preg_replace( '/(from|select|insert|delete|where|drop|union|order|update|database)/i', '', $str );
                $str = preg_replace( '/(&lt;|<)?script(\/?(&gt;|>(.*))?)/i', '', $str );
                $tbl = get_html_translation_table( HTML_ENTITIES );
                $tbl = array_flip( $tbl );
                $str = addslashes( $str );
                $str = strip_tags( $str );
                return strtr( $str, $tbl );
        } else {
                return array_filter( $str, "protect" );
        }
}

Just filter all the data coming from $_POST and $_GET

  • and in this case just put the function inside php where I have the code and protect?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.