I am using the fetch() API to implement a query to a table and in this query I would like to know how many rows (tuples) it is returning in order to make a conditional to record and display the data obtained within a container.
JavaScript code:
function cargarSimilares() {
let cod = localStorage.getItem("codPROD");
let cat = localStorage.getItem("categoria");
let subcat = localStorage.getItem("subcategoria").replaceAll(" ","_");
let data = new FormData();
data.append('codigo',cod);
data.append('categoria',cat);
data.append('subcategoria',subcat);
fetch('prdSimilares.php',{
method: 'POST',
body: data
})
.then(res => res.json())
.then(dataS => {
console.log(dataS);
});
}
This is what I have in prdSimilares.php:
$codigo = $_POST['codigo'] ?? null;
$categoria = $_POST['categoria'] ?? null;
$subcategoria = $_POST['subcategoria'] ?? null;
public function obtener_productos_similares($codigo, $categoria, $subcategoria) {
$db = new Connection();
$query = "SELECT prod.id_producto, prod.descripcion_producto, cat.descripcion_categoria, suc.descripcion_subcategoria
FROM producto AS prod
INNER JOIN categoria AS cat
ON prod.id_categoria = cat.id_categoria
INNER JOIN subcategoria AS suc
ON prod.id_subcategoria = suc.id_subcategoria
WHERE prod.disponible = '1' AND prod.id_producto <> '$codigo' AND cat.descripcion_categoria = '$categoria' AND suc.descripcion_subcategoria = '$subcategoria'
ORDER BY prod.precio ASC";
$resultado = $db->query($query);
$datos = [];
if ($resultado->num_rows > 1) {
while ($row = $resultado->fetch_assoc()) {
$datos[] = [
'codigo' => $row['id_producto'],
'nombre' => $row['descripcion_producto'],
'id_cat' => $row['id_categoria'],
'categoria' => $row['descripcion_categoria'],
'subcategoria' => $row['descripcion_subcategoria']
];
}
}
return $datos;
}
Several items are being recorded in the table and I give each of these a category and a subcategory; At the beginning, all the items that exist in this table are being shown in a container, each item also has the option to show more information about it and apart from that I have a container intended to show the items of the category to which the item belongs selected; Now, the problem is that there may be one or more items that are from that same category and my problem is that I am not sure of the number of items that are going to be in the table related to said category and subcategory, I must make the query save the data depending on the number of rows (tuples) returned.
As you can see, my idea is to use the if($resultado->num_rows>=1) {...}
and followed by this by putting the reserved word else{}
(when the condition is not met) to record in the array the data that the $resultado
. I tried in the following way:
else {
$datos = $resultado;
}
return $datos;
And in the console it showed me empty but in the table as at the moment I am controlling it I know that there are three items of a category / subcategory so it should show me two tuples since in the query it is specified that it be different from the code of the item selected (AND prod.id_producto <> '$codigo')
.
Does anyone have a notion of what is failing and / or missing to correct it and be able to achieve the objective?
ABSTRACT
I want to know how many rows or tuples I have in the query made to save the data and then display it in a container.
what I have:
function cargarSimilares() {
let cod = localStorage.getItem("codPROD");
let cat = localStorage.getItem("categoria");
let subcat = localStorage.getItem("subcategoria").replaceAll(" ","_");
let data = new FormData();
data.append('codigo',cod);
data.append('categoria',cat);
data.append('subcategoria',subcat);
fetch('prdSimilares.php',{
method: 'POST',
body: data
})
.then(res => res.json())
.then(dataS => {
console.log(dataS);
});
}
$codigo = $_POST['codigo'] ?? null;
$categoria = $_POST['categoria'] ?? null;
$subcategoria = $_POST['subcategoria'] ?? null;
public function obtener_productos_similares($codigo, $categoria, $subcategoria) {
$db = new Connection();
$query = "SELECT prod.id_producto, prod.descripcion_producto, cat.descripcion_categoria, suc.descripcion_subcategoria
FROM producto AS prod
INNER JOIN categoria AS cat
ON prod.id_categoria = cat.id_categoria
INNER JOIN subcategoria AS suc
ON prod.id_subcategoria = suc.id_subcategoria
WHERE prod.disponible = '1' AND prod.id_producto <> '$codigo' AND cat.descripcion_categoria = '$categoria' AND suc.descripcion_subcategoria = '$subcategoria'
ORDER BY prod.precio ASC";
$resultado = $db->query($query);
$datos = [];
if ($resultado->num_rows > 1) {
while ($row = $resultado->fetch_assoc()) {
$datos[] = [
'codigo' => $row['id_producto'],
'nombre' => $row['descripcion_producto'],
'id_cat' => $row['id_categoria'],
'categoria' => $row['descripcion_categoria'],
'subcategoria' => $row['descripcion_subcategoria']
];
}
}
return $datos;
}
after the if(){}
try putting an else {}``:
else {
// cuando solo es una fila
$datos[] = $resultado -> fetch_assoc();
}
no data was shown in the console (I put it to do the tests)
Well, it seems that you only need to call the function that you have created in php and display the data with
json_encode()
. Something like that:Try and confirm
I already found a solution and it was changing in the call to the function and in the conditional I added the
isset()
to each variable. The code in prdSimilares would be as follows:The change is basically in the arguments that I pass to the function.