I have a problem when extracting a data in mysql through PHP.
I have a database with two tables related to each other, the users table is related to its "Id" with another table called content in the "creator" section. What I am looking for is to extract from the users table another piece of data called "user", which would be the name in relation to the id, but I can only extract the id, that is, the identification number and not the name.
Here I leave my code.
<?php
include("apartadosPhp/conexion_bd.php");
$query = "SELECT * FROM contenido ORDER BY fecha DESC";
$resultado = $conexion -> query($query);
while ($row = $resultado->fetch_assoc()){
?>
<div>
<div class="img">
<img class="imgEntrada" src="img/entradas/<?php echo $row ['Img']?>" alt="imgEntrada">
</div>
<div class="detalles">
<h3><?php echo $row['Titulo'] ?></h3>
<h4 class="creador"> <?php echo $row['creador'] ?> </h4>
</div>
</div>
<?php
}
?>
At the time of putting, $row['creador']
it prints the ID of the user who registered the input, but I want to extract the name, not the id.
Perhaps a query like this can return the data you need:
As a general rule, it is not convenient to use the
*
and also it is not useful when you are going to use several related tables and extract data from them.This is how it should be,
creador
it is the numeric column that is used to relate the rows of your tablecontenido
with your tableusuarios
. The fact that there is a relationship between tables does not mean that when you consult that table alone it will bring you data from the related tables, but rather that in the SQL statement you must indicate the relationships usingJOIN
, then you will be able to obtain the data from all the tables that you have put in the SQL statement.For example, you can define your variable like this
$query
:He
INNER JOIN
will bring you data fromusuarios
and fromcontenido
. Instead of$row['creador']
use now$row['nombre']
, which will be the username.Suppose you are also interested in the position, because you can continue relating:
There you will also have the column
descripcion
of the table at handcargo
. By the way, the columnperfil int(50)
inusuarios
is not the same size as the columnid int(11)
incargo
, in a correct primary/foreign key definition environment to automatically manage referential integrity you will get an error.