$sql = 'SELECT * FROM tbluser, tblfile WHERE tbluser.Username = "'.$user.'"';
if ($result = mysql_query($sql)) {
if(mysql_num_rows($result)) {
echo'User already exists';
exit;
}
else
{
mysql_query('INSERT INTO tbluser
(`Username`, Password, BossID) VALUES ( "'.$user.'","'.$passwd.'","'.$boss.'")')or die(mysql_error());
$sqlq = 'SELECT * FROM tbluser, tblfile WHERE tbluser.Username = "'.$user.'"';
$res = mysql_query($sqlq);
while($row = mysql_fetch_array($res)){
mysql_query('INSERT INTO tbluser_file
(`FileID`, UserID) VALUES ( "'.$row['FileID'].'","'.$row['UserID'].'")')or die(mysql_error());
}
echo "Admin Added!";
}
}
我想检查用户是否已存在于我的数据库中。如果他存在我想退出,如果他不存在,我想执行上面的代码(在ELSE声明下)
提前致谢
答案 0 :(得分:1)
如果create a unique
index列为用户名,那么具有与用户名相同的值的插入作为表中已有的其他记录将导致特定的错误代码。您的脚本可以简单地尝试插入新记录并处理特定的错误代码,例如
define('ER_DUP_KEY', 1022);
// pre-condition: $user, $passwd, $boss have been prepared for usage within an sql statement
$query = sprintf("
INSERT INTO
tbluser
(`Username`, `Password`, `BossID`)
VALUES
('%s', '%s', '%s')
", $user, $passwd, $boss);
if ( !mysql_query($query) ) {
switch(mysql_errno()) {
case ER_DUP_KEY:
// handle duplicate user name
break;
default:
// handle other errors
}
}
如果您要使用两个查询(SELECT + INSERT),则必须处理race conditions,例如通过锁定表格。
编辑:我错过了隐式加入FROM tbluser, tblfile
在这种情况下,您可能会对INSERT ... ON DUPLICATE KEY UPDATE感兴趣,尤其是
如果表包含AUTO_INCREMENT列并且INSERT ... UPDATE插入行,则LAST_INSERT_ID()函数返回AUTO_INCREMENT值。如果语句更新了一行,则LAST_INSERT_ID()没有意义。但是,您可以使用LAST_INSERT_ID(expr)解决此问题。假设id是AUTO_INCREMENT列。要使LAST_INSERT_ID()对更新有意义,请按如下方式插入行:part。即:
INSERT INTO tbluser
查询答案 1 :(得分:0)
尝试以下:
确保查询返回行或没关系。
将if(mysql_num_rows($result))
更改为if(mysql_num_rows($result) > 0)
$sql = 'SELECT * FROM tbluser, tblfile WHERE tbluser.Username = "'.$user.'"';
if ($result = mysql_query($sql)) {
if(mysql_num_rows($result) > 0) {
echo'User already exists';
exit;
}
答案 2 :(得分:0)
$sql = 'SELECT COUNT(*) as COUNTUSER FROM tbluser, tblfile WHERE tbluser.Username = "'.$user.'"';
while ($myRow= mysql_fetch_array($sql)) {
$counterUser=$myRow[COUNTUSER];
}
if ($counterUser>0)
{
echo 'User already exists';
exit;
}