1

我正在尝试使用 php 执行准备好的语句,但它不起作用。我准备好的陈述是这样的:

SHOW TABLES LIKE "italy_turin_mathematics"

我这样做:

if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?_?_?")) {


    $stmt->bind_param('sss', "italy", "turin", "mathematics");

    $stmt->execute();

    $stmt->store_result();
    $stmt->bind_result($column1);

    while($stmt->fetch()) {
        echo "Table: ".$column1;
    }

}

我确定它必须返回一些东西,因为使用 PHPMyAdmin 它确实可以,但是使用 PHP 它总是跳过 while 循环,我认为准备好的语句查询有问题,也许它需要转义下划线字符?

我该怎么做?

4

3 回答 3

1

您的数据库体系结构完全错误

应该只有一张表包含所有地点和科学的所有数据。
而且您必须以通常的方式查询它,而SHOW TABLES根本不使用它。

所以,它必须是这样的

$sql = "SELECT * FROM t WHERE country=? AND city=? and science=?";
$stm = $pdo->prepare($sql);
$stm->execute(array("italy", "turin", "mathematics"));
$data = $stm->fetchAll();

上面的代码在 PDO 中,因为你必须使用它而不是 mysqli。

拆分表是一个非常糟糕的主意,违反了关系数据库的基本规则。如您所见,它会让您运行这样一个奇怪的查询,并使您的进一步代码变得更糟。

于 2013-04-04T15:26:09.413 回答
1
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?")) {

    $country = "italy";
    $city = "turin";
    $course = "mathematics";

    $stmt->bind_param('s', $country . "_" . $city . "_" . $course);

    $stmt->execute();

    $stmt->store_result();
    $stmt->bind_result($column1);

    while($stmt->fetch()) {
        echo "Table: ".$column1;
    }

}

据我所知,您拥有的代码会导致查询如下所示:

SHOW TABLES LIKE 'italy'_'turin'_'mathematics'
于 2013-04-04T15:29:31.430 回答
0

您不能在 mySQL 或我能想到的任何形式的 SQL 中进行这样的连接。

SHOW TABLES LIKE ?_?_?

应该:

SHOW TABLES LIKE CONCAT(?, '_', ?, '_', ?) --this gives an error, see below

我完全同意@your-common-sense 的评论,即这是一种糟糕的数据库设计方式,你会以更多的方式后悔,而不仅仅是这个搞砸的查询。

编辑:

MySQL 似乎不允许在SHOW TABLES语句中使用函数,因此您必须将表名连接到 PHP 中的单个字符串,或者您可以使用如下查询:

SELECT 
  TABLE_NAME
FROM    
  INFORMATION_SCHEMA.TABLES    
WHERE    
  table_schema = 'mydb' AND    
  table_name LIKE CONCAT(?, '_', ?, '_', ?);
于 2013-04-04T16:10:33.783 回答