[英]PHP “SHOW TABLES” MySQLi query not working
我正在嘗試使用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循環,我認為准備好的語句查詢有問題,也許它需要轉義下划線char?
我該怎么做?
您的數據庫體系結構完全錯誤 。
對於所有地點和科學,應該只有一個表包含所有數據。
而且您必須以常規方式查詢它,而根本不使用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。
拆分表是一個非常糟糕的主意,違反了關系數據庫的基本規則。 如您所見,它使您運行這樣一個奇怪的查詢,並使您的進一步代碼變得更糟。
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'
您無法在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(?, '_', ?, '_', ?);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.