Check if record exists in the table and return in mysqli

Asked

Viewed 5,049 times

-1

Hello I have a table called logs

id | usuario_id | produto_id
1  |     10     |   20
2  |     10     |   30
3  |     20     |   30
4  |     20     |   20

They are logs stating that the user with id 10 has already seen the product with id 20, and the same user with id 10 has seen product 30.

I’ve done an action that when it clicks on the preview button inserts in the logs table the user id and product id.

I wanted to make the following situation. In the product list where has the id | nome | preço It is bold, if the user has not viewed, and if already viewed is normal.

<tr style="
<?php
$user = $_SESSION['usuarioId']; //pega a sessão do usuário logado
$sql = "SELECT * FROM logs WHERE usuario_id = '{$user}'"; //monto a query
$row = $sql->fetch_row();
if ($row[0] > 0) {//se retornar algum resultado
echo 'font-weight: 700;';
} else {
echo 'font-weight: 300;';
}
?>">

The idea is if the user of the session is not in the table of that product, it gets font 700, if it is gets font 300.

Could someone help me?

2 answers

1


To check whether the row there is just do this:

$sql = "SELECT * FROM logs WHERE usuario_id = '{$user}'";
$result = mysql_query($sql);

if(mysql_num_rows($result) > 0) {
    echo 'font-weight: 300;';
} else {
    echo 'font-weight: 700;';
}
  • did not work. It is always returning the first IF.

  • So it’s because Row exists

  • Solved like this:<?php &#xA; $userid = $row_usuario["id"];&#xA; $result = $conn->query("SELECT * FROM logs WHERE usuario_id = '{$userid}'");&#xA; $row = $result->fetch_row();&#xA; if ($row[0] > 0){&#xA; echo "font-weight:300;";&#xA; }&#xA; else { &#xA; echo "font-weight:700;";<br>&#xA; }&#xA; ?>

-4

I just did:

if($rows["product_id"]){
     echo '**EXISTE**';
}else{
     echo '**NÃO EXISTE**';
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.