Because when I get syntax error when doing INSERT INTO in mysql?

-1

This is the function in php that I use to insert data in my users table

<?php
include 'includes/conexion.php';
$usuario = $_POST["usuario"];
$contraseña = $_POST["contraseña"];

$consulta = "INSERT INTO usuarios (id_usuario, nombre_usuario, contraseña_usuario) VALUES ('','$usuario','$contraseña')";

if($conexion->query($consulta)){
    header("location: registar.php?created");
}else{      
    echo "Error al ingresar datos del post ".$consulta.$conexion->error;
    exit();
}

? >

And what I get is this

  

Connect to the Error database when entering data from the post INSERT INTO   users (user_id, user_name, user_password) VALUES   ('', 'abisur', 'aiShinozaki23') You have an error in your SQL syntax;   check the manual that corresponds to your MariaDB server version for   the right syntax to use near ' a_user) VALUES   ('', 'abisur', 'aiShinozaki23') 'at line 1

You can explain to me why this happens, since you already check the fields and they are correct

    
asked by Abisur Diaz Ramirez 23.04.2018 в 06:02
source

1 answer

1
  

When you declare in your table an id of incremental type and that apart is   primary key, it is neither necessary to declare the name of the column nor   its value; therefore your query should look like this:

<?php
include 'includes/conexion.php';
$usuario = $_POST["usuario"];
$contraseña = $_POST["contraseña"];

$consulta = "INSERT INTO usuarios (nombre_usuario, contraseña_usuario) VALUES ('$usuario','$contraseña')";

if($conexion->query($consulta)){
    header("location: registar.php?created");
}else{      
    echo "Error al ingresar datos del post ".$consulta.$conexion->error;
    exit();
}
  

As you can see remove the name of the column and the quotes   empty that you left where you pass the values

In the case that your id field is neither an incremental point nor a primary key by default; that you have declared it as varchar or int nadamas, then your query should look like this:

  

Where as notes you pass a value of 1 instead of the single quotes that   I still do not understand why you put

<?php
include 'includes/conexion.php';
$usuario = $_POST["usuario"];
$contraseña = $_POST["contraseña"];

$consulta = "INSERT INTO usuarios (id_usuario, nombre_usuario, contraseña_usuario) VALUES (1,'$usuario','$contraseña')";

if($conexion->query($consulta)){
    header("location: registar.php?created");
}else{      
    echo "Error al ingresar datos del post ".$consulta.$conexion->error;
    exit();
}
  

When you enter numeric values like in this case it could be the id,   you do not need to put it in quotation marks; otherwise, if it is   date or strings of text then if you use the quotes

     

To yourself do not use special characters like ñ, accents or any   another symbology that your database manager can not understand if   you did not configure it properly

    
answered by 23.04.2018 / 06:18
source