然后选择Insert PHP query

时间:2018-03-23 08:29:44

标签: php mysql

如果用户存在,我可以先检查数据库,如果不存在,则使用insert语句。代码目前只执行select语句。

<?php
    include_once('includes/dbconn.php');

    if (isset($_POST['submitted'])) {
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $user = $_POST['user'];
        $pass = $_POST['pass'];

        $query_check_user = "SELECT username FROM Users WHERE username = '$user'";
        $query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";

        if (mysqli_query($dbconn, $query_check_user)) {
            echo "user already exists";
            mysqli_close($dbconn);
        }else{
            mysqli_query($dbconn, $query);
        }
    }
?>

3 个答案:

答案 0 :(得分:0)

<?
    include_once('includes/dbconn.php');

    if (isset($_POST['submitted'])) {
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $user = $_POST['user'];
        $pass = $_POST['pass'];

        //Query for count
        $query_check_user = "SELECT count(*) as total FROM Users WHERE username = '$user'";
        $query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
        //Execute query for count
        $result = mysqli_query($dbconn, $query_check_user);
        //Fetch result
        $data = mysqli_fetch_assoc($result);
        //Check if count >0
        if ($data['total']>0) {
            echo "user already exists";
            mysqli_close($dbconn);
        }else{
            mysqli_query($dbconn, $query);
        }
    }
?>

答案 1 :(得分:-2)

你可以使用mysqli_num_rows();检查数字是否大于0,然后用户存在,否则插入用户数据。

我的例子:

include_once('includes/dbconn.php');

    if (isset($_POST['submitted'])) {
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $user = $_POST['user'];
        $pass = $_POST['pass'];

        $query_check_user = "SELECT username FROM Users WHERE username = '$user'";
        $query_result = mysqli_query($query_check_user);
        $query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";

        if (mysqli_num_rows($query_result) > 0) {
            echo "user already exists";
            mysqli_close($dbconn);
        }else{
            mysqli_query($dbconn, $query);
        }
    }

答案 2 :(得分:-3)

我从你的问题中得到的是,如果用户不存在,你想插入用户,对吗?

$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$b = mysqli_query($dbconn,$query_check_user);
$a = mysqli_num_rows($b);
if($a<0):
   mysqli_query(dbconn, "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')");
endif;