检查是否使用php在mySql数据库中插入新行并返回新插入的行

时间:2015-06-15 08:56:38

标签: php mysql

我有一个PHP代码,可以从我的Android应用程序注册新用户。我已将用户名字段声明为唯一,因此如果输入重复的用户名,则会在插入时生成错误。如何检查插入是否成功执行以及如何继续将新添加的行返回到应用程序。这是我的代码,我应该在if()语句中写什么?

$con = mysqli_connect("", "", "", "");

$username = $_POST["username"];
$password = $_POST["password"];
$imagelink = $_POST["imagelink"];
$name = $_POST["name"];
$dob = $_POST["dob"];
$mobile = $_POST["mobile"];
$email = $_POST["email"];
$currency = $_POST["currency"];
$location = $_POST["location"];


$statement = mysqli_prepare($con, "INSERT INTO a8768135_testdb.Uzer (username, password, imagelink, name, dob, mobile, email, currency, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssssssss", $username, $password, $imagelink, $name, $dob, $mobile, $email, $currency, $location);
mysqli_stmt_execute($statement);


if() {
    $statemente = mysqli_prepare($con, "SELECT * FROM a8768135_testdb.Uzer WHERE username = ? AND password = ?");
    mysqli_stmt_bind_param($statemente, "ss", $username, $password);
    mysqli_stmt_execute($statemente);

    mysqli_stmt_store_result($statemente);
    mysqli_stmt_bind_result($statemente, $userID, $username, $password, $imagelink, $name, $dob, $mobile, $email, $currency, $location);

    $user = array();

    while (mysqli_stmt_fetch($statemente)) {
        $user["username"] = $username;
        $user["password"] = $password;
        $user["imagelink"] = $imagelink;
        $user["name"] = $name;
        $user["dob"] = $dob;
        $user["mobile"] = $mobile;
        $user["email"] = $email;
        $user["currency"] = $currency;
        $user["location"] = $location;
    }

    echo json_encode($user);
}


mysqli_close($con);

1 个答案:

答案 0 :(得分:0)

使用mysqli_insert_id

mysqli_insert_id($con);

结果将是刚刚创建的记录的最后一个id(自动增量值),返回零值意味着没有添加/插入新记录

您的代码应如下所示:

$statement = mysqli_prepare($con, "INSERT INTO a8768135_testdb.Uzer (username, password, imagelink, name, dob, mobile, email, currency, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssssssss", $username, $password, $imagelink, $name, $dob, $mobile, $email, $currency, $location);
mysqli_stmt_execute($statement);

if(mysqli_insert_id($con) > 0) {
......
}