似乎无法找到SQL语句错误的位置

时间:2013-04-22 04:58:05

标签: php mysql

我可能只是太累了,我想错过的东西真的很简单,但我无法弄明白。

尝试执行以下查询:

INSERT INTO chars (charName,charClass,charLevel,charLife,charES,charInt,charStr,charDex)
VALUES (mlkauschwitz,ranger,81,4500,50,50,300,250)
ON DUPLICATE KEY UPDATE charClass=ranger,charLevel=81,charLife=4500,charES=50,charInt=50,charStr=300,charDex=250;

导致此错误:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'mlkauschwitz' in 'field list'"

为什么认为某个值是一个字段?

使用以下PHP:

include "db.php";
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$char = array(
    'charClass'=>'ranger',
    'charDex'=>'250',
    'charES'=>'50',
    'charInt'=>'50',
    'charLevel'=>'81',
    'charLife'=>'4500',
    'charName'=>'mlkauschwitz',
    'charStr'=>'300',
);
$sql = 'INSERT INTO chars (charName,charClass,charLevel,charLife,charES,charInt,charStr,charDex) VALUES ('.$char["charName"].','.$char["charClass"].','.$char["charLevel"].','.$char["charLife"].','.$char["charES"].','.$char["charInt"].','.$char["charStr"].','.$char["charDex"].') ON DUPLICATE KEY UPDATE charClass='.$char["charClass"].',charLevel='.$char["charLevel"].',charLife='.$char["charLife"].',charES='.$char["charES"].',charInt='.$char["charInt"].',charStr='.$char["charStr"].',charDex='.$char["charDex"].';';
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($stmt) {
    try {
        $stmt->execute();
    }
    catch (PDOException $e) {
        var_dump($e);
    }
}

charName字段是唯一/主要的。

3 个答案:

答案 0 :(得分:4)

需要引用结果SQL中的值。 使用pdo,你应该这样做:

$sql = 'INSERT INTO chars (charName,charClass,charLevel,charLife,charES,charInt,charStr,charDex) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE charClass='.$char["charClass"].',charLevel='.$char["charLevel"].',charLife='.$char["charLife"].',charES='.$char["charES"].',charInt='.$char["charInt"].',charStr='.$char["charStr"].',charDex='.$char["charDex"].';';
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($stmt) {
    try {
        $stmt->execute(array($char["charName"],$char["charClass"],$char["charLevel"],$char["charLife"],$char["charES"],$char["charInt"],$char["charStr"],$char["charDex"]));
    }
    catch (PDOException $e) {
        var_dump($e);
    }
}

不确定确切的语法,但您可以在手册中查找。这可以确保PDO正确引用所有值,并避免mysql注入问题。

答案 1 :(得分:0)

如果mlkauschwitz不是列而是值,则引用它

请参阅mysqli_escape_string()

答案 2 :(得分:0)

将您的查询更改为INSERT INTO chars (charName,charClass,charLevel,charLife,charES,charInt,charStr,charDex) VALUES ('mlkauschwitz','ranger','81','4500','50','50','300','250') ON DUPLICATE KEY UPDATE charClass='ranger',charLevel='81',charLife='4500',charES='50',charInt='50',charStr='300',charDex='250';