Problem at the time of popular elements in the database

Asked

Viewed 132 times

0

I was doing a project of a chat in php, with ajax, but my code it does not insert anything to the database, only I have no idea what it is, and before you think that I did not search, I tried to bring the js variable to php, but I could not, I tried to change the sql command, but it wasn’t either. So I come to ask a help from you, it’s not chewed at all, because I’ve done it, that’s just the problem (The bank does not populate).

Thanks in advance for your attention.

index php.

<!DOCTYPE html>

<html>

<head>
<meta charset="utf-8">

<title>Sistema de Chat</title>

<link rel="stylesheet" href="style.css"/>

<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">

</script>

</head>

<body>

<?php
    session_start();
    $_SESSION['username'] = "Henrique Nunes";

?>

<div id="tela">
    <h1>Bem vindo ao chat</h1>

    <div class="tela_chat">

        <div id="chat">

        </div>

        <form method="POST">
            <textarea name="mensagem" cols="30" rows="7" class="textarea">

            </textarea>
        </form>

    </div>

</div>

<script>

    /*  -- JQUERY NO TEXTAREA --
        Essa parte o jquery vai pegar o número da tecla digitada
        e se o número for 13(enter) ele vai enviar
    */

    $('.textarea').keyup(function (e) {

        if ( e.which === 13 ){ //Se a tecla for igual a 13(enter)
           $('form').submit(); //Envie pra o formulário o que foi digitado
       }

    });

    $('form').submit(function () {

        var mensagem = $('.textarea').val();

        $.post('manipuladores/mensagens.php?
action=enviarMensagem&mensagem='+ mensagem, function (
            response
        ){

            alert(response);

        });

        return false;

    });

</script>



</body>


</html>

config.php

<?php

$dbhost = 'localhost';
$dbnome = 'chat';
$dbusuario = 'root';
$dbsenha = '1234';

try{
    $db = new 
PDO("mysql:dbhost=$dbhost;dbname=$dbnome","$dbusuario","$dbsenha");
}catch ( PDOException $e){
    echo ("<label style='color:red;'> Erro: </label> ".$e->getMessage(). "
<br><p style='color:red;'>Recomenda-se buscar na internet o código do erro.
</p>");
}



?>

.php messages (inside the handlers folder)

<?php

include_once ('../config.php');

switch ( $_REQUEST['action']){
case "enviarMensagem":

    //global $db;

    $comandoSQL = $db->prepare('INSERT INTO mensagens SET mensagem = ?');
    var_dump($comandoSQL);
    $comandoSQL->execute([$_REQUEST['mensagem']]);
    var_dump($comandoSQL);

break;
}

Information from the database name: chat; table used: messages;

messages is composed of:

id: PK, AI
usuario: VARCHAR(45)
mensagem: TEXT
data: TIMESTAMP

2 answers

1

I believe you’re not putting it in the bank so: INSERT INTO mensagens SET mensagem = ?. Instead of SET use : INSERT INTO mensagens (mensagem) VALUES (:MENSAGEM);

$comandoSQL = $db->prepare('INSERT INTO mensagens (mensagem) values (:MENSAGEM)');
$comandoSQL->bindParam(":MENSAGEM",$_REQUEST['mensagem']);
$comandoSQL->execute();
  • It didn’t work either ;-;

  • Apparently you are not using bindParam() for the message value. Try to do so: $commandSQL = $db->prepare('INSERT INTO messages (message) values(:MESSAGE)'); $commandSQL->bindParam(":MESSAGE",$_REQUEST['message']);

  • Nothing... I even gave a var_dump($commandSQL->execute()); and he returned me in the bool(false) response. Just like the comments of the answer above yours, it is as if the database is not connected...

  • Strange. I edited my answer with the correct excerpt. I replicated your code here on my localhost, and that way that I quoted it is entering into the bank... Did you ever give a SELECT directly in phpMyAdmin? Because in JS Alert() it really isn’t showing.

  • Yes, there is no record :( I will try on another PC, it is not possible...

  • I tried here on my other pc and not popula either ;-;

Show 1 more comment

1


Error is in class constructor PDO. You are passing the value dbhost to indicate the database server, but the correct one is host. Thus:

$db = new PDO("mysql:dbname=$dbnome;host$dbhost","$dbusuario","$dbsenha");

Another thing, avoid passing the message via GET and then capture with the global variable $_REQUEST.

Use in this way:

$.post("manipuladores/mensagens.php?action=enviarMensagem", {
    mensagem: $('.textarea').val()
}, function(response) {
    alert(Response);
})

And in the PHP you can capture that way:

$comandoSQL->execute([$_POST['mensagem']]);
  • I changed it the way you said it, but it’s not populated yet. Could I force some error to give me an exit with var_dump() to be clearer and understand what is happening ?

  • @Henriquen.Mendes check if PDOException returns some error; Also check the data of your connection to the database; You can also use $db->errorInfo();

  • When I add var_dump($db->errorInfo()); it returns this to me in the sponse: array(3){ [0] => string(0) "" [1] => NULL [2] => NULL }

  • @Henriquen.Mendes give one var_dump in $comandoSQL->execute([$_REQUEST['mensagem']]); and add $comandoSQL->errorInfo(); after execute()

  • I var_dump $commandSQL->execute([$_POST['message']]); and it returned in the answer "bool(false)" and when I did $commandSQL->errorInfo(); it returns this: array(3){ [0] => string(5) "3D000" [1] => int(1046) [2] => string(20) "In the database Selected" }

  • I do not understand, because I can connect to the database...

  • @Henriquen.Mendes Check the contents of the variable $dbnome and if the database with the value of $dbnome exists.

  • The names are equal $dbnome = 'chat'; and the bank name in phpmyadmin is chat as well. How strange

  • @Henriquen.Mendes I changed my answer, if possible check again the form of connection.

Show 5 more comments

Browser other questions tagged

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