[英]How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
我需要幫助檢查數據庫中是否存在一行。 就我而言,該行包含一個 email 地址。 我得到了結果:
email no longer exists publisher@example.com
這是我目前正在使用的代碼:
if (count($_POST)) {
$email = $dbl->real_escape_string(trim(strip_tags($_POST['email'])));
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($dbl, $query);
if (is_resource($result) && mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
} else {
echo "email no longer exists" . $email . "\n";
}
}
有沒有更好的方法來檢查 MySQL 數據庫中是否存在一行(在我的情況下,檢查 MySQL 中是否存在 email)?
以下是檢查行是否存在的經過嘗試、測試和驗證的方法。
(其中一些我自己用過,或者過去用過)。
編輯:我在我的語法中犯了一個錯誤,我使用了mysqli_query()
兩次。 請查閱修訂版。
IE:
if (!mysqli_query($con,$query))
應該簡單地讀為if (!$query)
。
旁注: '".$var."'
和'$var'
做同樣的事情。 您可以使用任何一個,兩者都是有效的語法。
這是兩個已編輯的查詢:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
在你的情況下:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
您還可以將mysqli_
與准備好的語句方法一起使用:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
注意:
在處理上面使用/概述的表單和 POST 數組時,請確保 POST 數組包含值,POST 方法用於表單並匹配輸入的命名屬性。
注意: <input type = "text" name = "var">
- $_POST['var']
匹配。 $_POST['Var']
不匹配。
咨詢:
錯誤檢查參考:
請注意 MySQL API 不會混合使用,以防您可能正在訪問此 Q&A 並且您正在使用mysql_
進行連接(和查詢)。
咨詢以下內容:
如果您正在使用mysql_
API 並且沒有選擇使用它,請參閱 Stack 上的以下問答:
mysql_*
函數已棄用,將從未來的 PHP 版本中刪除。
您還可以向 (a) 行添加 UNIQUE 約束。
參考:
您必須執行查詢並在查詢中向 $email 添加單引號,因為它是一個字符串,並刪除is_resource($query)
$query 是一個字符串,$result 將是資源
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
更新
根據您的編輯,只需更改:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
經過
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
你會沒事的
更新 2
更好的方法應該是有一個存儲過程,它執行以下 SQL,將電子郵件作為參數傳遞
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = @Email)
, 1, 0) as `Exist`
並檢索 php 中的值
偽代碼:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
有多種方法可以檢查數據庫中是否存在值。 讓我演示如何使用 PDO 和 mysqli 正確完成此操作。
PDO 是更簡單的選擇。 要找出數據庫中是否存在值,您可以使用准備好的語句和fetchColumn()
。 不需要獲取任何數據,因此如果值存在,我們只會獲取1
。
<?php
// Connection code.
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
有關更多示例,請參閱:如何檢查數據庫中是否存在電子郵件?
與往常一樣,mysqli 更麻煩,也更受限制,但我們可以使用准備好的語句遵循類似的方法。
<?php
// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');
// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
除了將結果行(甚至可能不存在)轉換為布爾值,您還可以獲取COUNT(1)
並使用fetch_row()[0]
從第一行讀取第一項
有關更多示例,請參閱:如何使用 mysqli 准備語句檢查數據庫中是否存在值
mysqli_num_rows()
,請不要聽他們的。 這是一種非常糟糕的方法,如果濫用可能會導致性能問題。real_escape_string()
。 這並不是用來防止 SQL 注入的。 如果您正確使用准備好的語句,則無需擔心任何轉義。在驗證之后和插入之前,使用 mysqli(procedural) 檢查用戶名是否已經存在。 這有效:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.