猿问

当我尝试绘制查询表时,我的 php 代码出错

由于我如何在表格中获取信息,我需要建立一个联合来显示交叉引用。


Tablebrand1 是表的名称。2 和 3


Tablebrand1


CODE    CROSSREFERENCE

A15     SAMSUNG A10

A16     SAMSUNG A20

A63     SAMSUNG A30


Tablebrand2


CODE    CROSSREFERENCE

X63     SAMSUNG A10

X64     SAMSUNG A20

X65     SAMSUNG A30


Tablebrand3


CODE    CROSSREFERENCE

TOP99   SAMSUNG A10

TOP98   SAMSUNG A20

TOP97   SAMSUNG A30

SQL查询


(SELECT "Tablebrand1" AS `brand`, CROSSREFERENCE as `code`

    FROM Tablebrand1 WHERE CROSSREFERENCE = 'SAMSUNG A10')

UNION 

(SELECT "Tablebrand2" AS `brand`, CROSSREFERENCE as `code`

    FROM Tablebrand2 WHERE CROSSREFERENCE = 'SAMSUNG A10')

UNION

(SELECT "Tablebrand3" AS `brand`, CROSSREFERENCE as `code`

    FROM Tablebrand3 WHERE CROSSREFERENCE = 'SAMSUNG A10');

查询正确地显示了它,但是当尝试在 php 中显示它时,我收到一个来自查询的错误,因为如果我修改它以进行更简单的查询,它会正确地显示数据。


<?php

echo "<table style='border: solid 1px black;'>";

echo "<tr><th>brand</th><th>code</th></tr>";


class TableRows extends RecursiveIteratorIterator {

  function __construct($it) {

    parent::__construct($it, self::LEAVES_ONLY);

  }


  function current() {

    return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";

  }


  function beginChildren() {

    echo "<tr>";

  }


  function endChildren() {

    echo "</tr>" . "\n";

  }

}


$servername = "localhost";

$username = "user";

$password = "pass";

$dbname = "dbname";


try {

  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $conn->prepare("((SELECT "Tablebrand1" AS `brand`, CROSSREFERENCE as `code`

    FROM Tablebrand1 WHERE CROSSREFERENCE = 'SAMSUNG A10')

UNION 

(SELECT "Tablebrand2" AS `brand`, CROSSREFERENCE as `code`

    FROM Tablebrand2 WHERE CROSSREFERENCE = 'SAMSUNG A10')

UNION


我的代码如下,我对 php 和 union 的了解很少。


炎炎设计
浏览 134回答 1
1回答

白板的微信

您没有说明错误消息是什么,但一个明显的错误是您使用的引号没有被转义。(另外,在查询开始时您有太多的引号( "((SELECT...) 因此您需要像这样转义查询中的引号$stmt = $conn->prepare("&nbsp; (SELECT \"Tablebrand1\" AS `brand`, CROSSREFERENCE as `code`&nbsp; &nbsp;FROM Tablebrand1 WHERE CROSSREFERENCE = 'SAMSUNG A10')&nbsp; UNION&nbsp;&nbsp; (SELECT \"Tablebrand2\" AS `brand`, CROSSREFERENCE as `code`&nbsp; &nbsp;FROM Tablebrand2 WHERE CROSSREFERENCE = 'SAMSUNG A10')&nbsp; UNION&nbsp; (SELECT \"Tablebrand3\" AS `brand`, CROSSREFERENCE as `code`&nbsp; &nbsp;FROM Tablebrand3 WHERE CROSSREFERENCE = 'SAMSUNG A10');");或者,您可以在查询中使用单引号,而不是像这样的双引号$stmt = $conn->prepare("&nbsp; (SELECT 'Tablebrand1' AS `brand`, CROSSREFERENCE as `code`&nbsp; &nbsp;FROM Tablebrand1 WHERE CROSSREFERENCE = 'SAMSUNG A10')&nbsp; UNION&nbsp;&nbsp; (SELECT 'Tablebrand2' AS `brand`, CROSSREFERENCE as `code`&nbsp; &nbsp;FROM Tablebrand2 WHERE CROSSREFERENCE = 'SAMSUNG A10')&nbsp; UNION&nbsp; (SELECT 'Tablebrand3' AS `brand`, CROSSREFERENCE as `code`&nbsp; &nbsp;FROM Tablebrand3 WHERE CROSSREFERENCE = 'SAMSUNG A10');");
随时随地看视频慕课网APP
我要回答