How do I not allow "" and "" in my Insert [closed]

-1

Well, I have an INSERT, and I would like to have someone else type in the text something with "<" or ">"

Code:

    $autor_id   = $_POST ["autor_id"];  
    $texto  = $_POST ["texto"];
    $query = "INSERT INTO 'videos' ( 'autor_id' , 'texto', 'id' ) 
    VALUES ('$autor_id', '$texto', '')";

    mysql_query($query,$conexao);
    
asked by anonymous 26.07.2015 / 09:09

4 answers

0

I prefer to use regular expressions for this type of verification.

Example:

$texto = "Este <é> <um teste >>>para remover<><><><><> caracteres <>";
$resultado = preg_replace("/[<>]/", "", $texto);
echo $resultado;
//Este é um teste para remover caracteres
    
26.07.2015 / 22:59
1

Instead of avoiding < and > you could convert them to the time of reading (remember INSERT is better to keep the original as it was written), then the moment you use SELECT, the < and > will be converted to &lt; and &gt; , thus avoiding injecting HTML into the page, but being able to keep the text as close as the author wrote.

Another thing you should do is to prevent not only the "injection" of HTML, but also the "injection" of mysql (or syntax failures), use mysql_real_escape

$autor_id   = mysql_real_escape($_POST["autor_id"]);
$texto  = mysql_real_escape($_POST["texto"]);
$query = "INSERT INTO 'videos' ( 'autor_id' , 'texto', 'id' ) VALUES ('$autor_id', '$texto', '')";

mysql_query($query,$conexao);

In reading use htmlspecialchars , example:

$query = 'SELECT autor_id, id, texto FROM 'videos' LIMIT 30';
$consulta = mysql_query($query, $conexao);

while ($linha = mysql_fetch_assoc($consulta)) {
     echo 'texto: ', htmlspecialchars($linha['texto']), '<br>';
}

Ancient Api of Mysql for PHP vs PDO and Mysqli

As I've said a few times in SOpt:

The php mysql_ API will be discontinued (it does not mean that mysql will be discontinued, just the PHP API) because it has been replaced with mysqli_* , so it is highly recommended that you update your codes to use or mysqli or pdo

Advantages of mysqli

  • Object-oriented interface
  • Prepared Statements support
  • Support for multiple Statements
  • Transactions support
  • Improved debugging capability
  • Embedded Server Support

Advantages of PDO

As stated by @Kazzkiq :

  • Advantages:

    • It works with 12 different database drivers (4D, MS SQL Server, Firebird / Interbase, MySQL, Oracle, ODBC / DB2, PostgreSQL, SQLite, Informix, IBM, CUBRID)
    • Object Oriented API;
    • It has named parameters;
    • Has client-side prepared statements (see disadvantages below)
  • Disadvantages:

    • Not as fast as MySQLi ;
    • By default, it simulates prepared statements (you can enable the native version when configuring its connection to the database, but if the native version does not work for some reason, it resumes the prepared statements without triggering errors or warnings More details here

Why upgrade your codes

As I said in this response , it should be noted that mysql_ functions do not receive any more updates, such as fixes and improvements and this is the vital point for you not to use mysql_ anymore, because in the near future it will no longer exist for new versions of PHP.

In other words, if you continue to mysql_ functions (without i ), two situations can happen with your projects:

  • There may be security holes in the mysql_ or bugs API.
  • When the mysql_ API is disabled, your scripts will stop working, which will cause you a lot of headache, as you will have to redo multiple codes.

How to use mysqli with your code

The insertion may look like this:

$autor_id   = mysqli_real_escape_string($_POST["autor_id"]);
$texto  = mysqli_real_escape_string($_POST["texto"]);
$query = "INSERT INTO 'videos' ( 'autor_id' , 'texto', 'id' ) VALUES ('$autor_id', '$texto', '')";

mysqli_query($query,$conexao);

In reading use htmlspecialchars , example:

$query = 'SELECT autor_id, id, texto FROM 'videos' LIMIT 30';
$consulta = mysqli_query($query, $conexao);

while ($linha = mysqli_fetch_assoc($consulta)) {
     echo 'texto: ', htmlspecialchars($linha['texto']), '<br>';
}

However you can use prepared statements , so you will not have to use mysqli_real_escape_string , data entry example:

    <?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit;
    }

    $autor_id = $_POST["autor_id"];
    $texto    = $_POST["texto"];

    if ($stmt = $mysqli->prepare("INSERT INTO 'videos' ( 'autor_id' , 'texto', 'id' ) VALUES (?, ?, '')")) {

        $stmt->bind_param('i', $autor_id);
        $stmt->bind_param('s', $texto);

        $stmt->execute();

        while ($linha = $result->fetch_assoc()) {
            echo 'texto: ', htmlspecialchars($linha['texto']), '<br>';
        }
        $stmt->close();
    }

    $mysqli->close();

Documentation:

27.07.2015 / 00:28
0

I recommend checking both in PHP, as already answered, and in javascript.

In javascript because neither the form nor is sent, does not use network, internet and nor resources of its server toa, only the browser of the visitor. The visitor also does not lose the data and you do not need any effort to put the data renovo in the form. In PHP for the smarties who undergo the javascript check, who is there just to help them

To do the javascript you can use the onsubmit property of the form:

...
<script type="text/javascript">
function checaTexto() {
  var strtexto;
  strtexto = document.getElementById("texto").value;  
  if ((strtexto.search("<") != -1) || (strtexto.search(">") != -1)) {
    alert("O texto não pode conter os caracteres '<' e '>'.");
    return false;
  }
}
</script>
...
<form id="formid" onsubmit="return checaTexto()" action="pagina.php">
<textarea id="texto" name="texto">
...

There are several other ways to do this, use jQuery to assign the event, this variable to the form reference, and so on. The example is just one of the ways.

In PHP, as indicated by the Hardcoder I think it would be appropriate, since you asked for an "error" when sending such characters.

    
26.07.2015 / 23:45
0

Try to use this:

if (strpos($_POST["texto"],'>') !== false || strpos($_POST["texto"],'<') !== false) {

    echo "Foi detetato > ou < no post!";
    die();
}else{
     // Executa sql aqui.
}
    
26.07.2015 / 13:14