从PHP向SQL表发送可变长度的数据,有更好的方法吗?
我有一个JSON字符串从JS/AJAX进入PHP文件。条目的数量是动态的,从6到30不等 我填充一个数组,如下所示从PHP向SQL表发送可变长度的数据,有更好的方法吗?,php,mysql,Php,Mysql,我有一个JSON字符串从JS/AJAX进入PHP文件。条目的数量是动态的,从6到30不等 我填充一个数组,如下所示 $myarray = array(); $dataLength= count($decodedJSON['make'][0]['model'][0]['color']); for ($x = 0; $x < $dataLength*2; $x+=2) { $myarray[$x] = $decodedJSON['make'][0]['model'][0]['color
$myarray = array();
$dataLength= count($decodedJSON['make'][0]['model'][0]['color']);
for ($x = 0; $x < $dataLength*2; $x+=2) {
$myarray[$x] = $decodedJSON['make'][0]['model'][0]['color'][$x/2]['int'];
$myarray[$x+1] = $decodedJSON['make'][0]['model'][0]['color'][$x/2]['ext'];
}
for ($x = $dataLength*2; $x < 30; $x++) {
$myarray[$x] = 0;
}
但我在想一定有更好的办法
谢谢你的帮助,
HSC.为什么不在声明数组时用零填充它;然后可以保存最后一个循环:
$myarray =array_fill(0,30,0);
如果您使用PDO,您可以将事情简化如下:
try {
$pdo = new PDO('mysql:host=' . $host . ';dbname=' . $database, $user, $pass, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}catch(PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
exit;
}
$sql = 'INSERT INTO cars VALUES ('.implode(',',array_fill(0,30,'?')).')';
$values = array_fill(0,30, null);
/** populate array with data here ... **/
$stmt = $pdo->prepare($sql);
try {
$stmt->execute($values);
}catch(PDOException $e) {
die($e->getMessage());
}
这里有一个旁注,如果您可以确定需要哪些列来执行插入,那么就更好了,您可以更改JSON以使该列与值匹配。通过这种方式,您将避免“始终必须定义30列”的开销,您只需为该列指定一个默认值即可
try {
$pdo = new PDO('mysql:host=' . $host . ';dbname=' . $database, $user, $pass, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}catch(PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
exit;
}
$sql = 'INSERT INTO cars VALUES ('.implode(',',array_fill(0,30,'?')).')';
$values = array_fill(0,30, null);
/** populate array with data here ... **/
$stmt = $pdo->prepare($sql);
try {
$stmt->execute($values);
}catch(PDOException $e) {
die($e->getMessage());
}