通过php输出时MySQL-PHP语法错误(似乎没有)

时间:2014-08-18 05:54:18

标签: php mysql syntax

由于某些原因,我的这段代码不会通过,我敢肯定这个的语法是正确的,但它只是赢了。请帮忙!

insert into users(username, name, password, type, accounts_prefix, comments, 0, 1, status) values('testuser', 'Testuser', 'abc2', 'RSLR', 'tes', 'testuseremailcom', 'username_owner', null, 'A')

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便使用“' 0,1,status”值附近(' testuser',' Testuser',' ; abc2',' RSLR' tes' tes',' testuserema' at line 1

编辑:插入功能:

    function db_insert( $table, $values )
{
    if( count($values) == 0 ) return FALSE;

    $sql = "insert into $table(";
    foreach( $values as $name => $value )
    {
        $sql .= $name.", ";
    }

    $sql = substr($sql, 0, strlen($sql) - 2).") values(";
    foreach( $values as $name => $value )
    {
        if( gettype( $value ) == "string" )
        {
            if( $value == "[null]" )
                $sql .= "null, ";
            else
                $sql .= "'".$value."', ";
        }
        else
            $sql .= $value.", ";
    }
    $sql = substr($sql, 0, strlen($sql) - 2).")";

    echo $sql."|";
    $result = mysql_query($sql);
    echo mysql_error()."|";
    return $result;
}

插入命令

if( !db_insert("users", array(
        "username" => $_REQUEST["r_username"],
        "name" => $_REQUEST["r_name"],
        "password" => $_REQUEST["r_password"],
        "type" => "RSLR",
        "accounts_prefix" => $_REQUEST["r_prefix"],
        "comments" => $_REQUEST["r_comments"],
        "username_owner", $_REQUEST["r_username_owner"],
        "status" => "A")
    ) )
    {
        echo("NOT OK Failed to add"); }

2 个答案:

答案 0 :(得分:0)

很可能因为0和1不应该是列名

答案 1 :(得分:0)

使用反引号来转义特殊关键字(在这种情况下为' 0'和' 1'),如下所示:

insert into users(username, name, password, type, accounts_prefix, comments, `0`, `1`, status)
values('testuser', 'Testuser', 'abc2', 'RSLR', 'tes', 'testuseremailcom', 'username_owner', null, 'A')

事实上,始终使用反引号作为列名称是最佳做法。