使用 PHP 检查 SQL 行是否存在 [英] check if SQL row exists with PHP

查看:30
本文介绍了使用 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.
}

这篇关于使用 PHP 检查 SQL 行是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆