使用 PHP 检查 SQL 行是否存在
问题描述:
我在 PHP 中使用 MySQL,我需要做这样的事情(伪代码):
I'm using MySQL with PHP and I need to do something like this (pseudocode):
if (sql row exists where username='bob')
{
// do this stuff
}
答
如果你使用的是mysql数据库,那么使用下面的-
If you are using mysql database, then use the following -
$query = "SELECT username from my_table where username='bob'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// row exists. do whatever you would like to do.
}
如果您想使用 PDO(PHP 数据对象)
,按照亚历克斯的建议,然后使用以下代码 -
If you would like to use PDO (PHP Data Object)
, as alex suggested, then use the following code -
$dbh = new PDO("mysql:host=your_host_name;dbname=your_db_name", $user, $pass);
$stmt = $dbh->prepare("SELECT username from my_table where username = ':name'");
$stmt->bindParam(":name", "bob");
$stmt->execute();
if($stmt->rowCount() > 0)
{
// row exists. do whatever you want to do.
}