1

I have problem with foreach loop and inner join on php. I have two tables: toners and printers. And code:

$toner = $this->_db->execute('SELECT TONERS.NAME, PRINTERS.NAME, TONERS.CONTRACTORS FROM TONERS INNER JOIN PRINTERS ON TONERS.ID_PRINTERS=PRINTERS.ID;')
foreach ($toner as $toners) {
            //here is the html table with results
} 

receives an error: Warning: Invalid argument supplied for foreach(). I'll add that on the query without 'Inner join' everything works fine ...

Anyone have an idea? Please...

k_turek
  • 191
  • 9

2 Answers2

3

foreach fails like this if $toner is null. The inner join is returning no rows. You need logic to handle this case. See this question for more info about this error.

Eric M. Johnson
  • 6,657
  • 2
  • 13
  • 23
0

At first, try to run this query on a server (like in PHPMyAdmin) and check that there are some records to fill your variable, which is used in foreach loop. This error shows you that your $toner var is empty.

Then try to fetch data from your query

$sql = "SELECT TONERS.NAME, PRINTERS.NAME, TONERS.CONTRACTORS FROM TONERS INNER JOIN PRINTERS ON TONERS.ID_PRINTERS=PRINTERS.ID;";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
     //do your magic
}