同一个表mysql上的多个查询

时间:2014-12-13 17:07:29

标签: php mysql database mysqli

我有一张这样的表:

users_info:
userID | title     | content
1      | Firstname | Tester
1      | Lastname  | Wester
2      | Firstname | LKks

我想检查带有PHP函数的数据库中是否已存在firstname和lastname。 如何运行简单查询以检查是否有任何结果? firstname的变量是:$ firstname和$ lastname为lastname。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我认为最好的方法是子查询。

SELECT userID from users_info where title = 'Firstname' and content = '$firstname' AND
userID IN (SELECT userID from users_info where title = 'Lastname' and content = '$lastname')

如果你得到任何结果。你有这个firstname和lastname具有相同id的行。

答案 1 :(得分:0)

function tableValidate($firstname, $lastname)
{
$query = $dbConnect->prepare("SELECT * FROM users_info WHERE title = ? AND content = ?");
$query->bindValue(1, 'Firstname');
$query->bindValue(2, $firstname);
$query->execute();
try
{
    $result = $query->rowCount();
} 
catch(PDOException $e)
{
    die($e->getMessage());
}

$queryOne = $dbConnect->prepare("SELECT * FROM users_info WHERE title = ? AND content = ?");
$queryOne->bindValue(1, 'Lastname');
$queryOne->bindValue(2, $lastname);
$queryOne->execute();
try
{
    $resultOne = $queryOne->rowCount();
} 
catch(PDOException $e)
{
    die($e->getMessage());
}

if($result > 0 && $resultOne > 0)
{
    echo "Firstname and Lastname Exists";
}
else if ($result > 0)
{
    echo "Firstname Exists";
}
else if ($resultOne > 0)
{
    echo "Lastname Exists";
}
else
{
    echo "Success";
}
}