我正在使用PHP和MySQL,我需要做类似于以下的事情(伪代码):
if (sql row exists where username='bob')
{
// do this stuff
}
我正在使用PHP和MySQL,我需要做类似于以下的事情(伪代码):
if (sql row exists where username='bob')
{
// do this stuff
}
如果您想使用PDO(PHP数据对象)
,请使用以下代码:
$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.
}
rowCount()
的说明:“如果与关联的 PDOStatement 执行的最后一个 SQL 语句是 SELECT 语句,则某些数据库可能会返回该语句返回的行数。但是,并非所有数据库都保证此行为,因此不应依赖于可移植应用程序。”。因此,请先检查您的数据库是否返回了正确的行数。 - PhoneixS$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
$user = "bob";
$user = mysql_real_escape_string($user);
$result = mysql_query("SELECT COUNT(*) AS num_rows FROM my_table WHERE username='{$user}' LIMIT 1;");
$row = mysql_fetch_array($result);
if($row["num_rows"] > 0){
//user exists
}