为什么我的INSERT INTO方法返回false?

时间:2014-11-12 22:26:23

标签: php mysql sql mysqli insert

我正在尝试将一些信息插入到我的一个数据库表中。这是我的代码:

function insertUser(){
    $con = db_connect();
    $response = array();

    if(empty($_REQUEST['firstname'])){
        $fnam = "";
    }else{
        $fnam = $_REQUEST['firstname'];
    }

    if(empty($_REQUEST['lastname'])){
        $lnam = "";
    }else{
        $lnam = $_REQUEST['lastname'];
    }

    if(empty($_REQUEST['age'])){
        $age = "";
    }else{
        $age = $_REQUEST['age'];
    }

    if(empty($_REQUEST['sex'])){
        $sex = "";
    }else{
        $sex = $_REQUEST['sex'];
    }

    if(empty($_REQUEST['location'])){
        $loc = "";
    }else{
        $loc = $_REQUEST['location'];
    }

    if(empty($_REQUEST['education'])){
        $edu = "";
    }else{
        $edu = $_REQUEST['education'];
    }

   //check if username forgot
    if(empty($_REQUEST['username'])){
        $response[] = "Please fill username box";
    }else{
        $uname = $_REQUEST['username'];
        //check if username is existed
        $isExisted = mysqli_query($con, "SELECT * FROM tbl_users WHERE username = '$uname'");
        if(mysqli_num_rows($isExisted) > 0){
            $response[] = "Username is Existed";
            }
         }

    //check if password forgot
    if(empty($_REQUEST['password'])){
        $response[] = "Please fill password box";
    } else{
        $pass = $_REQUEST['password'];
    }

    if(empty($response)){
        //$password = getHash($password);
        $res = mysqli_query($con, "INSERT INTO tbl_users (firstnam, lastname, age, sex, location, education, username, password, created_at) VALUES ('$fnam', '$lnam', '$age', '$sex', '$loc', '$edu', '$uname', '$pass', NOW())");
        // user stored successfully
        if ($res) {
            $response[] = "user stored successfully";
        }
    }

    echo json_encode($response);
    mysqli_close($con);
}

这是我的数据库的连接,我可以使用它来读取数据:

function db_connect(){
    $con = mysqli_connect("localhost", "root", "", "ketabha");
    mysqli_set_charset($con, 'utf8');
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    return $con;
}

表名和每个列名都正确但不起作用!当我echo json_encode($res);时,我的浏览器显示为false。你可以帮帮我吗?

1 个答案:

答案 0 :(得分:3)

要回答多条评论以便关闭问题并标记为已解决:

使用stripslashes()mysqli_real_escape_string()函数转义数据。

更好的是,使用prepared statementsPDO with prepared statements

在一段时间内交换的许多评论中,例如created_at列为DATETIME MySQL函数的NOW()

另一个是我认为是错误的列名,我怀疑是firstnam firstname

关于法语错误;这是因为SQL的.ini文件设置为lc-messages=fr_FR,需要更改为lc-messages=en_GB,因为您使用的是Wampserver,需要的是完成是为了获得英文信息。

Wamp的默认语言在MySQL中设置为法语,非常奇怪

您应该使用echo json_encode($res);来获取“真实”错误,而不是使用or die(mysqli_error($con))

一旦您有无错误的代码,您就可以使用echo json_encode($res);