[英]php mysql validate if table exist using pdo
我有以下代码来查看表(基于用户选择)是否存在,但它给了我以下错误:
[2019 年 3 月 21 日 11:34:11 UTC] PHP 致命错误:未捕获的 PDOException:SQLSTATE[42S02]:未找到基表或视图:1146 表“filecleaner.opened_2019-03-21”在 C 中不存在: \\inetpub\\wwwroot\\FileCleaner\\consultas.php:126 Stack trace: 0 C:\\inetpub\\wwwroot\\FileCleaner\\consultas.php(126): PDOStatement->execute(Array) 1 {main} throw in C:\\inetpub\\ wwwroot\\FileCleaner\\consultas.php 第 126 行
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM filecleaner.`Opened_". $DataDeConsulta ."`");
$stmt->execute([$DataDeConsulta]);
$count = $stmt->fetchColumn();
if ($count <= 0) {
$DataDeConsultaError = 'There is no information on that date!';
$valid = false;
}
if (isset($valid)) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM filecleaner.`Opened_". $DataDeConsulta ."`";
//session_start();
$_SESSION['DataDeConsulta'] = $DataDeConsulta;
$query_result=$pdo->query($sql);
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. htmlentities($row['Emails']) . '</td>';
echo ' ';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
}
您可以使用此选择查看 mysql/mariadb 中是否存在表:
SELECT * FROM information_schema.tables WHERE table_schema = 'you-database-name' AND table_name = 'your-table-name';
您是否尝试过使用这种 try-catch 语法?
/**
* Check if a table exists in the current database.
*
* @param PDO $pdo PDO instance connected to a database.
* @param string $table Table to search for.
* @return bool TRUE if table exists, FALSE if no table found.
*/
function tableExists($pdo, $table) {
// Try a select statement against the table
// Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
try {
$result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
} catch (Exception $e) {
// We got an exception == table not found
return FALSE;
}
// Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
return $result !== FALSE;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.