PDO UNION用? 不工作

问题描述:

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

我是SQL和PDO以及PHP的新手,所以我知道自己很多。 仍然没有冒险... 我想结合两个查询的结果,并使用别名使UNION查询的列名相同。 我尝试了各种减少,直到没有任何东西可以减少,有 在我的应用程序所需的实际结果中还有更多。 我有以下代码,不能想为什么它不起作用。 p>

两个查询都是自己工作但是当我将它们与UNION组合时我什么也得不到。 任何建议都是最有帮助的。 p>

  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->执行([$ c1]);  
 $ qResults-> fetch(PDO :: FETCH_ASSOC); 
返回$ qResults; 
 //关闭连接
 $ dbConn = null; 
} catch(PDOExcepetion $ e){
 echo $ e-  > getMessage(); 
} 
  code>  pre> 
 
 

非常感谢您的期待并感谢您的关注。 p>

Bri p> div>

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]);

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

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