I have the following code:
if($_POST['id']=="id")
{
$nomb_idm=$_POST['nombre'];
$n_idm=$_POST['id'];
$nivel_ide=$_POST['nivel'];
$pass_ide=$_POST['pass'];
$correo_idm= $_POST['correo'];
$usuario_ide= $_POST['usuario'];
$idfto=$_POST['id'];
$ide_consult = "SELECT * FROM usuarios WHERE id=".$idfto."" ;
$ide_result = $conexion->query($ide_consult);
while( $ide_fila = $ide_result->fetch_array() )
{ $idm=$ide_fila['id_foto'];}
if($idfto===$idm){
$msj="El usuario existe , crear con un numero de registro diferente o borrar el existente";
header("Location: index.php?msj=".$msj."");
}else{
$ide_permisos = "INSERT INTO permisos(id, nivel, smenu, status)
SELECT permisos_default.nivel,permisos_default.smenu,permisos_default.status
FROM permisos_default
WHERE permisos_default.nivel LIKE '%{$nivel_ide}%'";
$ide_p_result = $conexion->query($ide_permisos);
$msj="Usuario Creado con Exito";
header("Location: index.php?msj=".$msj."");
}
}
With this code, what I do is that when I send the user's id, I use it to assign permissions to a table that I call permissions, but taking permissions_default from the table through the user level.
The code inserts the user but does not insert the permissions in the permissions table.
My problem is related to this code:
$ide_permisos = "INSERT INTO permisos(id, nivel, smenu, status)
SELECT permisos_default.nivel,permisos_default.smenu,permisos_default.status
FROM permisos_default
WHERE permisos_default.nivel LIKE '%{$nivel_ide}%'";
$ide_p_result = $conexion->query($ide_permisos);
Any suggestion or help please
Thank you so much.!
The problem you're experiencing is that you're not adding the
id
user's to the query:In this way, each element of the template of the level you have in will be copied
permisos_default
usingpermisos
the oneid
of the desired user. The aliasid
is not necessary, but it will be useful for debugging where each value should go or what that number refers to.Online example: https://www.db-fiddle.com/f/ihomAdT8uTaUrjAvr6oAhG/0
Let's look at each instruction separately:
The
INSERT
has four columns indicated , while in theSELECT
you are selecting only three . The query will not work that way. Ifid
it is of typeAUTO_INCREMENT
orSERIAL
you can omit it in theINSERT
.It is also important to note the following:
SELECT
as many columns in it as there are in theINSERT
INSERT
to create duplicate rowsINSERT
will not be performed if there is nothing in theSELECT
, that is, if the conditions of theWHERE
.They are things to take into account.
Note:
If the variable you pass in
LIKE
comes from an external source (form or other), your code is vulnerable to SQL Injection. It is strongly recommended to use prepared queries to avoid this.