Skip to content
Advertisement

SQL query fetching data from multiple tables and displaying in html table

I am working on a system that fetches data from three tables. My query takes input from a form stored in variables named $departure and $destination. However the query is not working when i use these variables but if i enter result in sql query then it fetches data from sql. I echoed $departure and $destination to check if they have right values stored in them and the values are right still not giving result when use in query. Here is the code that didn’t work:

$q = "SELECT route.departure, route.destination,buses.busid, buses.busno,  dates.Date 
      FROM buses , route , dates
      WHERE  buses.route = route.rid && buses.date = dates.id && route.departure= '$departure' && 
              route.destination='$destination' && dates.Date = '$date'";;

$query = mysqli_query($conn,$q);

while($res = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
     ?>
     <tr class="text-center">
     <td> <?php echo $res['departure'];  ?> </td>
     <td> <?php echo $res['destination'];  ?> </td>
     <td> <?php echo $res['busid'];  ?> </td>
     <td> <?php echo $res['busno'];  ?> </td>
     <td> <?php echo $res['Date'];  ?> </td>
     <td> <button class="btn-danger btn" name="book"> <a href="selectseats.php?busID=<?php echo $res['ID']; ?>" class="text-white"> Book </a>  </button> </td>
     </tr>

<?php 
}
}
?>

But when I replace $departure from ‘Lahore’ and $destination from ‘Islamabad’(which are exact values stored in my sql database) in the query $q, then it shows result. Kindly help me out as I am totally stuck on that. Thanks in Advance!

Advertisement

Answer

can be an incorrect use of quotes, try concatenating values as next:

From:

"SELECT route.departure, route.destination,buses.busid, buses.busno,  dates.Date 
 FROM buses , route , dates
WHERE  buses.route = route.rid && buses.date = dates.id && route.departure= '$departure' && 
          route.destination='$destination' && dates.Date = '$date'";

To:

"SELECT route.departure, route.destination,buses.busid, buses.busno,  dates.Date 
 FROM buses , route , dates
WHERE  buses.route = route.rid && buses.date = dates.id && route.departure= '".$departure."' && 
          route.destination='".$destination."' && dates.Date = '".$date."'";

Also try to use the native SQL placeholders to scape parameters and kept secure your database.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement