Luda
Luda

Reputation: 7068

Printing result of mySQL query with INNER JOIN

I have a working SQL statement that returned correct results when I checked it on MAMP.

SELECT `questions`.`questionID` AS question, `questions`.`questionText`, 
       `questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
       `answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`

But I can't figure out how to print the output with php. Please help. This is the code:

<html>
<body>

<?php
    header('Content-Type: text/html; charset=utf-8');
    $con=mysqli_connect("localhost","root","root","Theory");
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions`   .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
                                 FROM `questions`,`answers`
                                 WHERE `questions`.`questionID` = `answers`.`questionID`");

    if (!$result)
    {
        die('Error: ' . mysqli_error($con));
    }
   while($row = mysqli_fetch_array($result))
   {
       echo "{";
       echo "{" . $row['questions'.'questionID'] . "}";   //this is not the full print
       echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
       echo "}";
   }

    mysqli_close($con);
    ?>

</body>
</head>

I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.

Upvotes: 3

Views: 2172

Answers (2)

STT LCU
STT LCU

Reputation: 4330

You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!

replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.

EDIT to answer the question's comments:

when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.

Try this:

while($row = mysqli_fetch_array($result))
{
   echo "{";
   echo "{" . $row['questionID'] . "}";   //this is not the full print
   echo "{" . $row['questionText'] . "}"; //just for checking
   echo "}";
}

Upvotes: 7

Francisco Presencia
Francisco Presencia

Reputation: 8851

$sql is aparently not set. You can do:

$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions`   .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
                             FROM `questions`,`answers`
                             WHERE `questions`.`questionID` = `answers`.`questionID`");

if (!$result)
{
    die('Error: ' . mysqli_error($con));
}

Upvotes: 5

Related Questions