使用php将数组保存到mysql

时间:2017-07-18 13:34:30

标签: php mysql

我有像这样的swift数组

["002012295915", "00971595502", "8885555512", "5555648583", "4085555270", "0562825196", "01147220964"]

使用php代码保存到mysql数据库的最佳方法是什么

1 个答案:

答案 0 :(得分:0)

如果您计划将所有数组保存为数据库中的一个字符串,则可以使用mysqli_querymysqli_real_escape_string

将所有数组保存为一个字符串:

$arr = ["002012295915", "00971595502", "8885555512", "5555648583", "4085555270", "0562825196", "01147220964"];
$con = mysqli_connect("localhost","root","pass","db");
mysqli_query($con,"insert into TABLE values('".mysqli_real_escape_string($con,$arr)."')");

如果您想稍后打印,只需使用select from TABLE where

自己保存每个值(没有正则表达式知识):

    //LET'S MAKE THE ARRAY MORE BEAUTIFUL FOR THE LOOP WITHOUT REGEX.

    $arr = str_replace('[','',$arr); 
    $arr = str_replace(']','',$arr);
    $arr = str_replace('"','',$arr);

//NOW THE ARRAY LOOKS LIKE THAT: 002012295915, 00971595502, 8885555512, 5555648583, 4085555270, 0562825196, 01147220964
//WE JUST NEED TO SPLIT IT NOW


$new_Array = explode(',',$arr); //DEVIDE ARRAY ELEMENT BY ','

//OK NOW WE JUST NEED TO PUT EACH ONE AS A SINGULAR VALUE IN THE DATABASE.

 $con = mysqli_connect("localhost","root","pass","db");

foreach($new_Array as $data)
{
   mysqli_query($con,"INSERT INTO TABLE VALUES('$data')");

}