Home > Software engineering >  Parse error: syntax error, unexpected 'UNION' (T_STRING)
Parse error: syntax error, unexpected 'UNION' (T_STRING)

Time:04-07

I'm trying to display a table with all records including NULL values and I've tried everything I can think of including the UNION operator. This is my code:

<?php

include "dbconfig.php";

$con = mysqli_connect($host, $username, $password, $dbname)
or die ("<br>Cannot connect to DB\n");

$sql = ("SELECT * FROM TECH3740.EMPLOYEE") UNION ("SELECT * FROM TECH3740.EMPLOYEE WHERE 
salary IS NULL");
$result = mysqli_query($con, $sql);

?>

<!DOCTYPE HTML>
<HTML>
<HEAD>

</HEAD>

<BODY>

<?php

if(mysqli_num_rows($result) > 0) {
?>

<TABLE border ="1" cellspacing = "0" cellpadding ="5">
<tr>
    <TH>ID</TH>
    <TH>Login</TH>
    <TH>Password</TH>
    <TH>Name</TH>
    <TH>Role</TH>
    <TH>Gender</TH>
    <TH>Salary</TH>
    <TH>Address</TH>

</tr>

<?php
$i = 0;
while($row = mysqli_fetch_array($result)) {
    ?>

    <tr>
        <TD><?php echo $row["employee_id"]; ?></TD>
        <TD><?php echo $row["login"]; ?></TD>
        <TD><?php echo $row["password"]; ?></TD>
        <TD><?php echo $row["name"]; ?></TD>
        <TD><?php echo $row["role"]; ?></TD>
        <TD><?php echo $row["gender"]; ?></TD>
        <TD><?php echo $row["salary"]; ?></TD>
        <TD><?php echo $row["Address"]; ?></TD>
    </tr>
<?php
    $i  ;
}
?>

</TABLE>

<?php
}
else{
    echo "No result found";
}
?>

</BODY>
</HTML>

It's throwing a Parse error: syntax error, unexpected 'UNION' (T_STRING) on line 8. I'm not sure what else to try. Any advice?

CodePudding user response:

You have the quotes in the wrong place, they should be around the entire SQL query. UNION is SQL syntax, not PHP.

$sql = "SELECT * 
        FROM TECH3740.EMPLOYEE 
        UNION 
        SELECT * 
        FROM TECH3740.EMPLOYEE 
        WHERE salary IS NULL";

CodePudding user response:

You don't really need to use a UNION just quote your query in this way

$sql = "SELECT * FROM TECH3740.EMPLOYEE";

This will pick up ALL the rows including the NULLs

  • Related