【问题标题】:Checking if data already is present in database [closed]检查数据库中是否已经存在数据[关闭]
【发布时间】:2014-12-10 13:00:44
【问题描述】:

我正在尝试检查数据库中是否已存在用户 ID。但由于某种原因,它不起作用。我尝试了不同的解决方案,但都失败了。

db_connect.php 工作正常,我仔细检查了!

create_user.php

<?php

$response = array();

if (isset($_POST['user_id'])){

        $id = $_POST['user_id'];
        $fullName = $_POST['user_fullName'];
        $firstName = $_POST['user_firstName'];
        $lastName = $_POST['user_lastName'];
        $birthday = $_POST['user_birthday'];
        $friends = $_POST['user_friends'];
        $totalFriends = $_POST['user_totalFriends'];
        $email = $_POST['user_email'];
        $gender = $_POST['user_gender'];
        $likes = $_POST['user_likes'];
        $events = $_POST['user_events'];
        $hometown = $_POST['user_hometown'];

    require_once __DIR__ . '/db_connect.php';

    $db = new DB_CONNECT();

    $query = mysql_query("SELECT * FROM 'userData' WHERE 'id' = '$id'");
    $user_data = mysql_num_rows($query);

    if(empty($user_data)) {         

        $result = mysql_query("INSERT INTO userData(id, fullName, firstName, lastName, birthday, friends, totalFriends, email, gender, likes, events, hometown) VALUES ('$id', '$fullName', '$firstName', '$lastName', '$birthday', '$friends', '$totalFriends', '$email', '$gender', '$likes', '$events', '$hometown')");

        if($result){
            $response["success"] = 1;
            $response["message"] = "User successfully created";

            echo json_encode($response);
        }

        else{
            $response["success"] = 0;
            $response["message"] = "Error occurred";

            echo json_encode($response);
        }
    }

    else {

        $response["success"] = 1;
        $response["message"] = "User already in database";

        echo json_encode($response);            

    }
}

else{
    $response["success"] = 0;
    $response["message"] = "Required userdata is missing";

    echo json_encode($response);
}   

?>

嗯。如果我在浏览器中运行此脚本,它会完美运行。当我在我的 android 应用程序中运行它时,它总是会创建一个新用户。

谢谢! T

【问题讨论】:

  • SELECT * FROM 'userData' WHERE 'id' 去掉表名和列名上的单引号。
  • 什么不起作用?是否有可以显示的错误或可以描述的行为?
  • 请阅读 SQL 注入。

标签: php mysql json database


【解决方案1】:

您在表名和字段周围添加了单引号。

将其更改为反引号。

$query = mysql_query("SELECT * FROM 'userData' WHERE 'id' = '$id'");

更新到:

$query = mysql_query("SELECT * FROM `userData` WHERE `id` = '$id'");

另外,请不要使用 mysql_* 函数,因为出于安全原因,它们已被弃用,并将在未来的版本中删除。

单引号用于用户输入。

关键字/数据库名称/表名称/字段名称可以用反引号括起来。

【讨论】:

  • 谢谢,我的蜱虫确实有问题。但是仍然不能解决我的问题。我编辑了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 2020-02-04
相关资源
最近更新 更多