为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
炎炎设计 2023-11-03 21:33:52
由于我如何在表格中获取信息,我需要建立一个联合来显示交叉引用。Tablebrand1 是表的名称。2 和 3Tablebrand1CODE    CROSSREFERENCEA15     SAMSUNG A10A16     SAMSUNG A20A63     SAMSUNG A30Tablebrand2CODE    CROSSREFERENCEX63     SAMSUNG A10X64     SAMSUNG A20X65     SAMSUNG A30Tablebrand3CODE    CROSSREFERENCETOP99   SAMSUNG A10TOP98   SAMSUNG A20TOP97   SAMSUNG A30SQL查询(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 中显示它时,我收到一个来自查询的错误,因为如果我修改它以进行更简单的查询,它会正确地显示数据。<?phpecho "<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 的了解很少。
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

您没有说明错误消息是什么,但一个明显的错误是您使用的引号没有被转义。(另外,在查询开始时您有太多的引号( "((SELECT...) 因此您需要像这样转义查询中的引号


$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

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

   FROM Tablebrand3 WHERE CROSSREFERENCE = 'SAMSUNG A10');"

);

或者,您可以在查询中使用单引号,而不是像这样的双引号


$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

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

   FROM Tablebrand3 WHERE CROSSREFERENCE = 'SAMSUNG A10');"

);


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 130 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信