请告诉我如何在MySQL中的表中插入索引数组?在此代码片段中,我需要将数组项插入data
$data = [5555,22,102858,12,.554,88888,99999999,12,1.5];
$temtbl = "CREATE TEMPORARY TABLE IF NOT EXISTS `dataTable` (
`data` decimal(14,2) DEFAULT 100
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;";
$conn->query($temtbl);
$insertTotbl= "INSERT INTO `dataTable`(`data`);
$conn->query($insertTotbl);
更新
$row =[];
$query5 = "SELECT * FROM `dataTable`" ;
$results = $conn->query($query5);
if ($results) {
$row = $results->fetch_array(MYSQLI_NUM);
$row = array_map('floatval', $row);
}
$conn->close();
echo json_encode($row);
答案 0 :(得分:2)
一种简单的方法:
$data = [5555,22,102858,12,.554,88888,99999999,12,1.5];
$temtbl = "CREATE TEMPORARY TABLE IF NOT EXISTS `dataTable` (
`data` decimal(14,2) DEFAULT 100
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;";
$conn->query($temtbl);
$insertTotbl= "INSERT INTO `dataTable`(`data`) VALUES (" . implode('),(', $data) . ")";
$conn->query($insertTotbl);
更新
第二部分:
$nums = [];
$query5 = "SELECT * FROM `dataTable`" ;
$results = $conn->query($query5);
while ($row = $results->fetch_array()) {
$nums[] = floatval($row[0]);
}
$conn->close();
echo json_encode(nums);
答案 1 :(得分:0)
您可以在存储之前serialize:
<?php
$data = [5555,22,102858,12,.554,88888,99999999,12,1.5];
$foo = serialize($data);
var_dump($foo); // Outputs: a:9:{i:0;i:5555;i:1;i:22;i:2;i:102858;i:3;i:12;i:4;d:0.5540000000000000479616346638067625463008880615234375;i:5;i:88888;i:6;i:99999999;i:7;i:12;i:8;d:1.5;}
此时,您可以将$foo
存储为数据库中的字符串。当您查询数据时,您可以unserialize获取数据:
$bar = unserialize($foo);
var_dump($bar); //Outputs the array.
?>
答案 2 :(得分:0)
试试这个:
foreach($data as $val)
{
$insertTotbl= "INSERT INTO `dataTable`(`data`) VALUES ('".$val."') ";
$conn->query($insertTotbl);
}