Error recording information in the data bank

Asked

Viewed 23 times

-1

Hello, I just started learning php and mysql. At the moment I’m trying to make a kind of posting system, but I’m not able to record the information in DB. If you can help me find what’s wrong, it’ll be great :).

A form is submitted and the action sends to that file:

<?php

require_once('db.class.php');

$titulo = $_POST['titulo'];
$texto_postagem = $_POST['descricao'];

date_default_timezone_set('America/Sao_Paulo');
$data = date("d/m/Y");
$hora = date("H:i");

$objDb = new db();
$link = $objDb-> conecta_mysql ();

$sql = "insert into postagens(titulo, descricao, data, hora) values($titulo', '$texto_postagem', '$data', '$hora') ";

//executar a query
if(mysqli_query($link, $sql)){
    echo 'Postagem armazenada com sucesso';
} else {
    echo 'Erro ao registrar postagem!';
}

?>

And this file calls this:

<?php
class db {

    private $host = 'localhost';

    private $usuario = 'root';

    private $senha = '';

    private $database = 'sistema_postagens';

    public function conecta_mysql(){

        $con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);


        if(mysqli_connect_errno()){
            echo 'Erro ao tentar se conectar com o BD MySQL: '.mysqli_connect_error();  
        }

        return $con;

    }
}
?>

When it runs, echo 'Error while registering post!'

  • 1

    If you don’t know what’s wrong, don’t mask the error with a message that doesn’t help you at all. Instead of displaying messages like "Vish! Gave error" display the actual error message with the function mysqli_error. In fact, there’s a simple quotation mark missing before $titulo in your SQL.

  • Thank you so much! I managed to find the error with mysqli_error :)

1 answer

0

You forgot the quotation marks at the beginning of the title in values

<?php

require_once('db.class.php');

$titulo = $_POST['titulo'];
$texto_postagem = $_POST['descricao'];

date_default_timezone_set('America/Sao_Paulo');
$data = date("d/m/Y");
$hora = date("H:i");

$objDb = new db();
$link = $objDb-> conecta_mysql ();
//AQUI VOCÊ ESQUECEU Da aspas mude $titulo' para '$titulo'
$sql = "insert into postagens(titulo, descricao, data, hora) values('$titulo', '$texto_postagem', '$data', '$hora') ";

//executar a query
if(mysqli_query($link, $sql)){
    echo 'Postagem armazenada com sucesso';
} else {
    echo 'Erro ao registrar postagem!';
}

Browser other questions tagged

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