2013-01-14 40 views
2

我正在嘗試編寫一個PHP函數來檢查給定的值是否在數據庫的列中。該函數採用參數$userName$link,其中$userName將在數據庫$linkuserid列中檢查。這是我到目前爲止:查詢結果來自PHP提出的查詢

<?php 
/*This function checks to see if the username is already in use 
INPUT: the userName to check for and a link to the database 
OUTPUT: true if there are no other users registered with userName 
*/ 
function isUnique($userName, $link) 
{ 
    $result = !!mysqli_fetch_row(mysqli_query($link, 'SELECT `userid` 
    FROM `login` 
    WHERE `userid` = \''.$userName.'\'')); 
    return $result; 
} 


echo '<html><head><title>testing</title><body>'; 
$uName = $_POST['us']; 
$pass = $_POST['pa']; 

//database work 
$link = mysqli_connect("localhost:3306", "root", ""); 
if(!$link) 
    die('Could not connect to MySQL: '.mysql_error()); 
$db_selected = mysqli_select_db($link, 'Accounts'); 
if(!$db_selected) 
    die('Can\'t use Accounts: '.mysql_error()); 
echo '<br />Using Accounts database<br />'; 
if(isUnique($uName, $link)) 
{ 
    echo 'username is unique!<br />'; 
} 
else 
{ 
    echo 'username is not unique!<br />'; 
} 
mysqli_close($link); 

echo '</body></html>'; 
?> 

該網頁總是說,給定的用戶名不是唯一的。

+0

複製[**請不要在新代碼'mysql_ *'功能**](http://bit.ly/phpmsql)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 –

+3

@ROYFinley:如果你仔細觀察,你會發現他正在使用mysqli :) –

+0

是的,對不起,我習慣以對象風格來看它。應該看起來更接近。 –

回答

0
function isUnique($userName, $link) 
{ 
       $result = mysqli_query($link, 'SELECT `userid` 
         FROM `login` 
         WHERE `userid` = \''.$userName.'\'')); 
       return mysqli_num_rows($result) == 0; 
} 

phpfreaks

1

試試這個:

function isUnique($userName, $link) { 
    return !!mysqli_fetch_row(mysqli_query($link, "select `userid` from `login` where `userid`='".$userName."'")); 
} 

由於mysqli_fetch_row返回null如果沒有行,一個數組,如果有一個,轉換爲Boolean會告訴你,如果有一個行或不行。

+1

請務必對此發表評論,以免在6個月後感到困惑! –

+0

不能說它的作品。現在返回值總是一無所獲(即'''')。 – Celeritas

+0

如果它是一個布爾值,返回值怎麼可能是什麼?你確定查詢是正確的嗎?有沒有錯誤? –

0
$userName = mysqli_escape_string($userName); // Or such 

"SELECT COUNT(*) FROM login WHERE userid='$userName'" 

BTW IMO最好是INSERT,然後檢查是否有插入的行和錯誤代碼/味精的數量。 如果這是0和「...重複...」,那麼你知道它正在使用,並可以正確處理。