I want to fetch all the values of a row in a table having the same photograph id

<?php
  $message = "";
  if(empty($_GET['id'])) {
    $session->message("<div class='btn sm-warning'>please select an image.</div>");
    redirect_to('list_properties.php');
  } 
  $id  = $_GET['id'];
  $sql = "SELECT * FROM pictures GROUP BY photograph_id HAVING '$id';";
  $property       = $database->query($sql);
  $photos         = $database->fetch_array($property);
 echo $photos;
?>

This is my sql table below... i want to select all images having the same photograph_id using an id number.

id  photograph_id   image            title                location    price        type
    1   etsq1mro6n  building-1.jpg  5 Bedroom           Lekki   90,000,000  Sale
    2   etsq1mro6n  building-2.jpg  5 Bedroom           Lekki   90,000,000  Sale
    3   etsq1mro6n  building-3.jpg  5 Bedroom           Lekki   90,000,000  Sale
    4   etsq1mro6n  building-4.jpg  5 Bedroom           Lekki   90,000,000  Sale
    5   etsq1mro6n  building-5.jpg  5 Bedroom           Lekki   90,000,000  Sale
    6   etsq1mro6n  building-6.jpg  5 Bedroom           Lekki   90,000,000  Sale

2 Answers

0
scaisEdge On Best Solutions

could be you are looking for a filter based on where

"SELECT * FROM pictures 
WHERE  photograph_id = '$id';";

eg

"SELECT * FROM pictures 
WHERE  photograph_id = 'etsq1mro6n';";

anyway you should not use php var in sql you are at risk for sqlinjection .. you should take a look at prepared statements and bindig param ..

1
Someguywhocodes On

Adding onto what @scaisEdge said, you're currently using HAVING which is typically used when aggregating data - which you're not doing. This is an example of HAVING to find duplicate records, used in conjunction with COUNT():

SELECT
    name, email, COUNT(*)
FROM
    users
GROUP BY
    name, email
HAVING 
    COUNT(*) > 1

As pointed out, you need to use a WHERE instead of HAVING:

<?php
  $message = "";
  if(empty($_GET['id'])) {
    $session->message("<div class='btn sm-warning'>please select an image.</div>");
    redirect_to('list_properties.php');
  } 
  $id  = $_GET['id'];
  $sql = "SELECT * FROM pictures WHERE photograph_id = '$id';";
  $property       = $database->query($sql);
  $photos         = $database->fetch_array($property);
 echo $photos;
?>

As a best practice, you should also use prepared statements - https://www.php.net/manual/en/pdo.prepared-statements.php.