Error in MSQLI Insert

Asked

Viewed 233 times

1

I am switching from mysql_to mysqli, everything works(update and delete) more on Insert not saved.... where is the error?

Insert archive:

include("config/con_mysqli.php");


$sigla                  = $_REQUEST['sigla'];
$nome                   = $_REQUEST['nome'];    


mysqli_set_charset($con,"utf8");

$sql = "insert into setores(sigla,nome) values('$sigla','$nome')";



@mysqli_query($con,$sql);



echo json_encode(array(
    'idsetor' => mysqli_insert_id($con),
    'sigla' => $sigla,
    'nome' => $nome
));
  • See if this looks like a mistake like this: mysqli_query($con,$sql) or die(mysqli_error($con));. Do not use @ because it hides the error so you do not see the error message.

  • I am using easyui datagrid, so even if you have error does not appear....

  • Access this php file directly, you can put the fixed values to $sigla and $nome test-only.

  • {"idsector":48,"acronym":null,"name":null} returned that.... saved direct.

  • you didn’t forget to put the $_POST['nome'] something like that? at least you don’t have that code in the question.

  • not.... it works perfectly with mysql_ but has some problem in mysqli

  • edited there... had forgotten to show this part.....

  • 1

    worked was something with the mysqli_set_charset($con,"utf8");

Show 3 more comments

1 answer

0


First of all, let’s get down to the basics. You are leaving the procedural mode of mysqli_query for object-oriented. I commented this case a short time ago in this question.

The problem is that you are still messing up the procedural way with the object-oriented one when working with mysqli_query.

How would it be right to work with the object-oriented `mysqli_query:

Connection (Not that yours is wrong)

// Conecta ao banco de dados
$mysqli = new mysqli('127.0.0.1', 'usuario', 'senha', 'banco');

Validating the connection

// Verifica se ocorreu algum erro
if (mysqli_connect_errno()) {
    die('Não foi possível conectar-se ao banco de dados: ' . 
         mysqli_connect_error());
    exit();
}

Try to use the Prepared Statements. Make your life easier

/* Prepared statement, Primeiro parte prepare o sql.
Verifique se não ocorreu erro */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
    echo "Falha no Prepare: (" . $mysqli->errno . ") " . $mysqli->error;
}

// Segunda parte passe os parâmetros e execute a query
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Falha no bind_param: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Falha ao executar a query: (" . $stmt->errno . ") " . $stmt->error;
}

One more example. Another thing, avoid using the @ at the bank or anywhere in your code. Omitting errors and warnings only harms you to produce a good code.

I hope it helps you.

Browser other questions tagged

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