I am currently making my products show their status "available" or "out of stock" create a new table called "status" in my database... In my products table add a new column called "status_id" where it is stored in What state is the product in?
Database:
condition:
products
Then when placing it so that it is shown in the list of my products in index.php, it appears that it is only the ID of the status table. For example, in the image below it says "1" and I need the status of the product to appear, to say if it is available or out of stock.
index.php
<div class="productos">
<a href="productos/producto.php?id=<?php echo $productos['id']?>">
<img src="<?php echo '/images/' . $productos['image']; ?>" class="img-test">
<p class="text-test"><?php echo $productos['title']?></p>
<p class="status"><?php echo $productos['tipo_id']; ?></p>
</a>
</div>
products.php
<?php
include($_SERVER['DOCUMENT_ROOT'].'/app/database/db.php');
include($_SERVER['DOCUMENT_ROOT'].'/app/helpers/validatePost.php');
$table = 'productos';
$categorias = selectAll('categorias');
$estado = selectAll('estado');
$errors = array();
$id = '';
$title = '';
$body = '';
$estadoid = '';
$topic_id = '';
$productos = selectAll($table);
if (isset($_POST['add-post'])) {
$_POST['topic_id']=serialize($_POST['topic_id']);
$errors = validatePost($_POST);
if (!empty($_FILES['image']['name'])) {
$image_name = time() . '_' . $_FILES['image']['name'];
$destination = "../../images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result){
$_POST['image'] = $image_name;
} else {
array_push($errors, "¡Algo fallo al subir la imagen!");
}
} else {
array_push($errors, "¡Necesitas subir una imagen!");
}
if (count($errors) === 0){
unset($_POST['add-post']);
$post_id = create($table, $_POST);
$_SESSION['message'] = '¡Post creado correctamente!';
$_SESSION['type'] = 'success';
header('location: ../../admin/posts/index.php');
exit();
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$topic = $_POST['topic_id'];
$estadoid = $_POST['estado_id'];
}
}
if (isset($_GET['id'])){
$id = $_GET['id'];
$post = selectOne($table, ['id' => $id]);
}
if (isset($_GET['del_id'])){
$id = $_GET['del_id'];
$count = delete($table, $id);
$_SESSION['message'] = '¡Post eliminado correctamente!';
$_SESSION['type'] = 'success';
header('location: ../../admin/posts/index.php');
exit();
}
if (isset($_POST['update-post'])){
$_POST['topic_id']=serialize(array_values($_POST['topic_id']));
$_POST['estado_id']=serialize($_POST['estado_id']);
$errors = validateEdit($_POST);
if (count($errors) === 0){
$id = $_POST['id'];
unset($_POST['update-post'], $_POST['id']);
$post_id = update($table, $id, $_POST);
$_SESSION['message'] = '¡Post actualizado correctamente!';
$_SESSION['type'] = 'success';
header('location: ../../admin/topics/index.php');
exit();
} else {
$id = $_POST['id'];
$title = $_POST['title'];
$body = $_POST['body'];
$topic = $_POST['topic_id'];
$estadoid = $_POST['estado_id'];
}
}
?>
db.php
<?php
session_start();
require('connect.php');
function dd($value)
{
echo "<pre>", print_r($value, true), "</pre>";
die();
}
function executeQuery($sql, $data)
{
global $conn;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare($sql);
$values = array_values($data);
$types = str_repeat('s', count($values));
$stmt->bind_param($types, ...$values);
$stmt->execute();
return $stmt;
}
function selectAll($table, $conditions = [])
{
global $conn;
$sql = "SELECT * FROM $table";
if (empty($conditions)) {
$sql = $sql . " ORDER BY id DESC";
$stmt = $conn->prepare($sql);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
} else {
// $sql = "SELECT * FROM $table WHERE username='ElVictox' AND admin=1";
$i = 0;
foreach ($conditions as $key => $value) {
if ($i === 0){
$sql = $sql . " WHERE $key=?";
} else {
$sql = $sql . " AND $key=?";
}
$i++;
}
$stmt = $conn->prepare($sql);
$values = array_values($conditions);
$types = str_repeat('s', count($values));
$stmt->bind_param($types, $values);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
}
}
function selectOne($table, $conditions)
{
global $conn;
$sql = "SELECT * FROM $table ";
$i = 0;
foreach ($conditions as $key => $value) {
if ($i === 0){
$sql = $sql . " WHERE $key=?";
} else {
$sql = $sql . " AND $key=?";
}
$i++;
}
$sql = $sql . " LIMIT 1";
$stmt = executeQuery($sql, $conditions);
$records = $stmt->get_result()->fetch_assoc();
return $records;
}
function create($table, $data)
{
global $conn;
$sql = "INSERT INTO $table SET ";
$i = 0;
foreach ($data as $key => $value) {
if ($i === 0){
$sql = $sql . " $key=?";
} else {
$sql = $sql . ", $key=?";
}
$i++;
}
$stmt = executeQuery($sql, $data);
$id = $stmt->insert_id;
return $id;
}
function update($table, $id, $data)
{
global $conn;
$sql = "UPDATE $table SET ";
$i = 0;
foreach ($data as $key => $value) {
if ($i === 0){
$sql = $sql . " $key=?";
} else {
$sql = $sql . ", $key=?";
}
$i++;
}
$sql = $sql . " WHERE id=?";
$data['id'] = $id;
$stmt = executeQuery($sql, $data);
return $stmt->affected_rows;
}
function delete($table, $id)
{
global $conn;
$sql = "DELETE FROM $table WHERE id=?";
$stmt = executeQuery($sql, ['id' => $id]);
return $stmt->affected_rows;
}
The problem is that you are displaying the numeric value, here:
To obtain the value of
DISPONIBLE
orAGOTADO
you would have to do an SQL query where you join usingJOIN
the tablesproductos
, andestado
. But in the current context this is hardly applicable, because you use a generic method for all queries. To do it throughJOIN
you would have to create another type of method, with logic that implementsJOIN
, something similar to what ORMs do.Since in this case it is only two values, you can use a ternary to assign
DISPONIBLE
orAGOTADO
according to the value, something like this:There, it will print
DISPONIBLE
when the value is equal to1
, otherwise it will printAGOTADO
.Note on strict coding
There is still one aspect to cover. What if it is neither
1
nor2
? You should make sure, where the data is generated, that this value comes with1
or with2
, or else that it isNULL
and evaluate here first of all the non-nullity of the data, assigning a default value and then do the evaluation with the ternary. I leave this note to invite you to write a strict code that controls the state of the data (if they are null, if they are empty, etc).