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;

导致此错误:

"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 字段是唯一的/主要的。

4

3 回答 3

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 注入问题。

于 2013-04-22T05:00:40.927 回答
0

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

见 mysqli_escape_string()

于 2013-04-22T05:01:46.237 回答
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';

于 2013-04-22T05:13:34.610 回答