这是我的阵列:
$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);
这是我得到的输出:
全名,肤色,粉刺,干性皮肤,油性皮肤,皱纹衰老,
敏感皮肤,黑锅,头发类型,尼泊金酯,硫酸盐,矿物油,
硅酮,放松,着色,变薄,生长,编织,滚筒,
wng、heat、假发、辫子、长发、指甲花、发色、发型
克里斯·鲁诺,2岁,不,是,不,是,是,不,直,不,不,不,不,不,
不,不,不,不,不,不,不,不,不,不,不,深褐色,经典
我还检查了MySQL表,一共有27列。
最佳答案
$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_u*函数,使用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));
关于php - 列数与第1行的值数不匹配-但是我有27列和27个值? PHP MySQL错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14948274/