Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从PHP向SQL表发送可变长度的数据,有更好的方法吗?_Php_Mysql - Fatal编程技术网

从PHP向SQL表发送可变长度的数据,有更好的方法吗?

从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

我有一个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'][$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());
}