Problems inserting data into a table in Mysql (PHP)

Asked

Viewed 100 times

0

I can’t enter data into my table, and the commands are all right, right connection, but it doesn’t enter the data. I already redid the table to see if it was some configuration or name error, but it remains the same

Follows the code:


<?php

include 'conexao.php';
include 'script/password.php';

$nomeusuario = $_POST['nomeusuario'];
$mail = $_POST['mailusuario'];
$senha = $_POST['senhausuario'];
$nivel = $_POST['nivelusuario'];
$status = 'Ativo';

$sql = "INSERT INTO usuarios (nome_usuario,mail_usuario,senha_usuario,nivel_usuario,status) values ('$nomeusuario','$mail',sha1('$senha'),$nivel,'$status')";

$inserir = mysqli_query($conexao, $sql);

?>

  • What error appears on your screen?

  • Make an echo $sql; and try to run the result in direct text in the database and send the error message for us to analyze.

1 answer

0


Look I’ve always preferred to use PDO to connect to the bank, I’ll give you an example of how you can use PDO instead of using mysqli.

Your.php connected file would look like this

<?php

$dns = "mysql:dbname=nomeDoBanco;host=localhost"; //informe o nome do banco e o local
$dbuser = "usuario"; //informe o usuario
$dbpass = "senha"; //informe a senha

try {
    $pdo = new PDO($dns, $dbuser, $dbpass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}

your second code snippet would be like this

<?php

//alterar para include_once pois caso o arquivo já esteja incluído ele não fara a inclusão novamente.
include_once('conexao.php'); 
include_once('script/password.php');

//adicionar o "addslashes" pois já ajuda um pouco contra injeção de SQL
$nomeusuario = addslashes($_POST['nomeusuario']);
$mail = addslashes($_POST['mailusuario']);
$senha = addslashes($_POST['senhausuario']);
$nivel = addslashes($_POST['nivelusuario']);
$status = 'Ativo';

$sql = "INSERT INTO usuarios (nome_usuario, mail_usuario, senha_usuario, nivel_usuario, status) values ('$nomeusuario', '$mail', sha1('$senha'), $nivel, '$status')";

$sql = $pdo->query($sql);

?>

using this way any error of inclusion in the database will be displayed clearly and you can easily handle.

Browser other questions tagged

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