Bri
Bri

Reputation: 153

PDO UNION with ? not working

I am new to SQL and PDO and PHP so I know I am asking a lot of myself. Still nothing ventured... I want to combine the results of two queries and am using aliases to make the column names the same for the UNION query. I have tried all sorts of reducing till there is nothing left to reduce, there are many more in the actual result I need for my app. I have the following code by can't think why it is not working.

Both queries work on their own but I get nothing when I combine them with a UNION. Any suggestions would be most helpful.

include ("conn/dbCon_1.php");
$sql= "(SELECT  First_Name AS myResult FROM tbl_User WHERE First_Name LIKE ?)";
$sql.=" UNION ALL ";
$sql.= "(SELECT Course_Title AS myResult FROM tbl_Course  WHERE Course_Title LIKE ? )";
$c1 =  "%le%";
try {
    $qResults = $dbConn->prepare($sql); 
    $qResults->execute([$c1]); 
    $qResults->fetch(PDO::FETCH_ASSOC);
    return $qResults;
    //Close connection
    $dbConn = null;
} catch(PDOExcepetion $e) {
    echo $e->getMessage();
}

Many thanks in anticipation and thank you for your kind attention.

Bri

Upvotes: 1

Views: 750

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133400

You invoke the query with two parameters (like in the first Query and like in the second) even if they have the same value .. so you have to pass two parameters

$qResults->execute([$c1, $c1]);

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

As you have two placeholders - you should bind values twice:

$qResults->execute([$c1, $c1]);

Upvotes: 2

Related Questions