如何知道某行是否存在MySQL


How to know a certain row exists MySQL

我想阻止用户评论已删除的线程。我设置了一个变量(我们称之为"tnum")来标识原始线程及其注释,因此我可以在同一网页中显示它们。当我删除一个话题时,原始话题和所有评论都会立即被删除(从 ~ 中删除,其中 tnum 是 ~)

所以我想我可以使用它来防止对已删除线程的评论提交。

我想在表中没有具有特定 tnum 值的行时发出错误消息。

if( 'some code' ) {
error("There is no data for the thread.");
}

有人可以帮助我吗?

谢谢。

您可以在 MySQL 中使用 COUNT() 来获取与您的条件匹配的行数。所以像这样的事情

$db = new PDO( /* connection details */ );
$sth = $db->prepare( 'SELECT COUNT(*) AS numRows FROM `table` WHERE tnum = :tnum' );
$sth->execute( array( 'tnum' => $tnum ) );
$result = $sth->fetchAll();
if( $result['numRows'] == 0 ) {
    error("There is no data for the thread.");
}

要知道表中是否存在列,您可以运行此查询:

SHOW COLUMNS FROM `table` LIKE 'fieldname';