Write JS to database with $_POST

Asked

Viewed 325 times

0

Hello.

I have a PHP script that runs an INSERT in a table of my database.

The $_POST[txt_message] array shown in the code should accept JS content, but it is empty after Submit. He should accept for example a simple Alert('ola')

I searched in the PHP manual how to accept an insecure string in the POST but found nothing about it.

Thank you in advance for your attention.

<?php
session_start();
include("dados_conexao.php"); 

if ($_POST)
{
    echo 'valor: ' . $_POST['txt_mensagem'];
    try { // tenta fazer a conexão e executar o INSERT
        $conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha); //istancia a classe PDO
        $comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('$_POST[txt_de]', '$_POST[txt_para]', '$_POST[txt_mensagem]');";
        echo $comandoSQL;
        $grava = $conecta->prepare($comandoSQL); //testa o comando SQL
        $grava->execute(array());           
    } catch(PDOException $e) { // casso retorne erro
        echo('Deu erro: ' . $e->getMessage()); 
    }
}?> 

Form

<form method="POST" >
			<label for="de">Para: </label>
			<input type="text" name="de">
  
            <label for="para">Para: </label>
			<input type="text" name="para">

			<label for="mensagem">Mensagem: </label>
			<input type="text" name="mensagem">		

			<button type="submit"> Enviar </button>
</form>

  • How is the form that sends the data to that code?

  • Edited, I put HTML in pubic! obg.

  • Do so and see what returns: echo 'valor: <textarea cols=100 rows=50>' . $_POST['txt_mensagem'].'</textarea>'; exit;

1 answer

0

First, to detect if the form was posted, use:

if ($_SERVER['REQUEST_METHOD'] === 'POST'){

The name of your field in the form is mensagem and not txt_mensagem, so the line echo 'valor: ' . $_POST['txt_mensagem']; doesn’t work.

In the QUERY mount, in addition to the wrong names, arrays in a string must be embedded in parentheses, and also missing quotes in field names...

Substitute:

$comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('$_POST[txt_de]', '$_POST[txt_para]', '$_POST[txt_mensagem]');";

For:

$comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('{$_POST['de']}', '{$_POST['para']}', '{$_POST['mensagem']}');";

Your revised PHP code:

<?php
session_start();
include("dados_conexao.php"); 

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
     $_POST['de'] = addslashes($_POST['de']);
     $_POST['para'] = addslashes($_POST['para']);
     $_POST['mensagem'] = addslashes($_POST['mensagem']);
    echo 'valor: ' . $_POST['mensagem'];
    try { // tenta fazer a conexão e executar o INSERT
        $conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha); //istancia a classe PDO

        $comandoSQL = "INSERT INTO tb_mensagens (de, para, mensagem) VALUES ('{$_POST['de']}', '{$_POST['para']}', '{$_POST['mensagem']}');";

        echo $comandoSQL;

        $grava = $conecta->prepare($comandoSQL); //testa o comando SQL
        $grava->execute(array());           
    } catch(PDOException $e) { // casso retorne erro
        echo('Deu erro: ' . $e->getMessage()); 
    }
}
?> 

Any doubt or error, regarding this question, just comment here below.

  • The answer given above?

  • Dear Allan, I appreciate your time and dedication in analyzing and reviewing my code. I implemented the way you proposed and the page normally performs the Inserts in the database, however, what I need is for the page to accept JS commands. If I write the text "Hello World", everything works fine, but if I try to write "<script> Alert('Hello World')</script>" the page does not accept this string. Grateful!

  • Try using double quotes as single quotes are already being used in the content: <script> Alert("Hello World")</script>

  • Or you can treat the POST first with addslashes. Create a line for each post right after the first IF, example: $_POST['de'] = addslashes($_POST['de']);

  • I updated the answer. Test and inform if it is working.

Browser other questions tagged

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