1

这是我的数组:

$person = array(
    "fullname" => $fn,
    "skin_shade" => $_POST['skin_shade'],
    "acne" => $_POST['acne'],
    "dry_skin" => $_POST['dry_skin'],
    "oily_skin" => $_POST['oily_skin'],
    "wrinkles_aging" => $_POST['wrinkles_aging'],
    "sensative_skin" => $_POST['sensative_skin'],
    "darkspots" => $_POST['darkspots'],
    "hair_type" => $_POST['hair_type'],
    "parabens" => $_POST['parabens'],
    "sulfates" => $_POST['sulfates'],
    "mineral_oil" => $_POST['mineral_oil'],
    "silicones" => $_POST['silicones'],
    "relaxed" => $_POST['relaxed'],
    "colortreated" => $_POST['colortreated'],
    "thinning" => $_POST['thinning'],
    "growth" => $_POST['growth'],
    "braidout" => $_POST['braidout'],
    "roller" => $_POST['roller'],
    "wng" => $_POST['wng'],
    "heat" => $_POST['heat'],
    "wig" => $_POST['wig'],
    "braid" => $_POST['braid'],
    "dreadlocks" => $_POST['dreadlocks'],
    "henna" => $_POST['henna'],
    "hair_color" => $_POST['hair_color'],
    "hair_style" => $_POST['hair_style'],
);

这是我尝试插入它并得到错误的地方:

$columns = implode(", ",array_keys($person));
$escaped_values = array_map('mysql_real_escape_string', array_values($person));
$values = implode(", ", $escaped_values);
$sql = "INSERT INTO people ($columns) VALUES ('$values')";
mysql_query($sql) or die (mysql_error());

我还在列和值上使用了 print_r 以确保它们的大小相同:

print_r($columns); echo"</br></br>";
print_r($values);

这是我得到的输出:

全名,skin_shade,粉刺,干性皮肤,油性皮肤,皱纹_老化,敏感皮肤,黑斑,头发类型,对羟基苯甲酸酯,硫酸盐,矿物油,有机硅,放松,颜色处理,变薄,生长,辫子,滚筒,wng,热,假发,辫子,长发绺,指甲花,头发颜色,头发样式

克里斯·鲁诺,2,不,是,不,是,是,不,直,不,不,不,不,不,不,不,是,不,不,不,不,不,不,不,不,深棕色,经典

我还检查了我的 MySQL 表,有 27 列。

4

2 回答 2

5
$sql = "INSERT INTO people ($columns) VALUES ('$values')";

这将把一个字符串文字放入 VALUES 子句中,一个包含逗号分隔值列表的单引号字符串:

INSERT INTO people (...columns...) VALUES ('Chris Runo, 2, No, Yes, No, Yes, Yes, No, Straight, No, No, No, No, No, No, No, Yes, No, No, No, No, No, No, No, No, dark_brown, classic')

为了解决这个问题,您可以编写自己的引用/转义函数并在 array_map() 中使用它:

function myquote($val)
{
  return "'" . mysql_real_escape_string($val) . "'";
}

$escaped_values = array_map('myquote', array_values($person));

$values = implode(", ", $escaped_values);
$sql = "INSERT INTO people ($columns) VALUES ($values)";

否则,您可以放弃已弃用的 mysql_* 函数,并使用 PDO,这样可以更轻松地编写不受 SQL 注入影响的查询:

$columns = implode(", ",array_keys($person));
$params = implode(",", array_fill(0, count($person), "?"));

$sql = "INSERT INTO people ($columns) VALUES ($params)";
$stmt = $pdo->prepare($sql) or die(print_r($pdo->errorInfo(), true));
$stmt->execute(array_values($people)) or die(print_r($stmt->errorInfo(), true));
于 2013-02-19T01:25:38.650 回答
0

您需要将您的值与''. 因此,将您的内爆更改为:

$values = implode("', '", $escaped_values);
于 2013-02-19T01:27:53.140 回答