php foreach button issue

Viewed 44

What I exactly need:

inside the foreach for every element I create a button. Then connect to postgresql db, select data from the table by condition.

If there is a matching entry in the database then I display <span class="fa fa-heart"> </span>. If no entries then display <span class="far fa-heart"></span>. I need this output exactly inside <button> </button> tag.

<form method="POST">
<?php foreach ($rows as $data): ?>
<button class="btn btn-outline-danger mx-1" name=fav-click style="font-size: 11px;">
 <?php
  $linkk = pg_connect("host=localhost dbname=webportal user=postgres password=1234567");
   $favor=(int)$data['obj_id'];
   $id_usr=(int)$id;
   $query = "select obj_id, usr_id from favorites where usr_id='$id_usr' and obj_id='$favor'";
   $re = pg_query($linkk, $query);
   $row1=pg_fetch_all($re);
   if(pg_num_rows($re)==0)
    {
     echo '<span class="far fa-heart"></span>';
   }
   if(pg_num_rows($re)>0)
    {
      echo '<span class="fa fa-heart"> </span>';
    }
    ?>
      
    </button>

inside the form there also are

<input type=hidden name=obj_id value=<?= $data['obj_id'];?>>
<input type=hidden name=id_usr value=<?= $id; ?>>

in which I store the values ​​I need.

Outside the foreach I have:

<?php 
 if(isset($_POST['fav-click']) && isset($_POST['obj_id']) && isset($_POST['id_usr'])) {
 $oo = $_POST['obj_id'];
 $uu=$_POST['id_usr'];
  if(pg_num_rows($re)==0)
              {
             $zapr="insert into favorites(obj_id, usr_id) values($oo, $uu)";
              $done = pg_query($linkk, $zapr);
              }
                if(pg_num_rows($re)>0)
                  {
                   $zapr="delete from favorites where obj_id='$oo' and usr_id='$uu'";
                     $done = pg_query($linkk, $zapr);
                      }
                    } 
                    ?>

But it works not correctly because it always displays and does queries in the db for the last element of foreach. Doesn't matter if I click a button for another one.

How can I fix it?

0 Answers
Related