检查mySQL数据库中是否已存在记录

时间:2011-04-16 09:55:43

标签: php mysql

  

可能重复:
  insert contacts into database but does not want to duplicate already existing contact

我打算做的是,检查用户的帐户是否已存储在我的数据库中,重定向到另一个URL,否则将其数据存储在数据库中。以下是我写的查询。它不起作用请告诉我哪里出错了。 thaks。

$result = mysql_query("SELECT * FROM centraluser where id = '$id'");
$row = mysql_fetch_row($result);
if($row) {
    mysql_query("UPDATE central SET time = '$time' WHERE id = '$id'");
    $url = "http://www.somesite.com";
    echo '<script type="text/javascript"> alert("Sorry! you can't register twice.");</script>';
    echo '<script type="text/javascript">top.location.href = "'.$url.'";</script>';die;exit;

}
else  {
    mysql_query("INSERT INTO centraluser VALUES ('$id','$name','$email','0','5000','0','0','$birthday','$time')");
    echo('welcome new user');

2 个答案:

答案 0 :(得分:1)

首先,您遇到此代码的错误

转义字符串并使用下面的代码。

并定义代码的哪些部分仍无效。

echo '<script type="text/javascript"> alert("Sorry! you can\'t register twice.");</script>';
echo '<script type="text/javascript">top.location.href = "'.$url.'";</script>';die;exit;

答案 1 :(得分:0)

希望这有效

$result = mysql_query("SELECT * FROM centraluser WHERE id = '$id'");
$user_data = mysql_fetch_row($result);
if(empty($user_data)) {
    $qry = "INSERT INTO centraluser VALUES    ('$id','$name','$email','0','5000','0','0','$birthday','$time')";
    mysql_query($qry);
    $_SESSION['msg'] = 'welcome new user';
    header("Location:dashboard.php"); // write your main page after login
    exit();
}
else {
     $qry="UPDATE central SET time = '$time' WHERE id = '$id'";
     mysql_query($qry);
     $url = "http://www.somesite.com";
     echo '<script type="text/javascript"> alert("Sorry! you can\'t register twice.");</script>';
     echo '<script type="text/javascript">top.location.href ="'.$url.'";</script>';
    exit();
}