简体   繁体   English

PHP如何将数组数据保存到数据库

[英]php how to save array data to database

Please check my code, I'm getting the following output: 请检查我的代码,我得到以下输出:

in wood that 1

in wood that 2 

in wood that 3 

in wood that 4 

From the code shown below, I'd like these four lines to be stored in my MySQL database. 从下面显示的代码中,我希望将这四行 存储在我的MySQL数据库中。

$string = "imperfection in wood that 1 can appear during the wood drying process.imperfection in   wood that 2 can appear during the wood drying process.imperfection in wood that 3 can appear during the wood drying process.imperfection in wood that 4 can appear during the wood drying process";
preg_match_all('/(imperfection)(.*?)(can)/', $string, $matches);   

foreach($matches[2] as $value) 
    echo  $value.'<br />'; 

$sql="INSERT INTO string_check(st_name)VALUES($value)";
$result=mysql_query($sql);

Thanks & Kind Regards, 谢谢与亲切的问候,

Iterate over the matches, escaping them (just in case) and wrapping them in quotes and parenthesis; 遍历匹配项,转义它们(以防万一),并用引号和括号括起来; then join all of them with commas, and use that string as your VALUES expression: 然后用逗号将它们全部连接起来,并使用该字符串作为VALUES表达式:

$foreach($matches[2] as $match) {
  $values[] = '("' . mysql_real_escape_string($match) . '")';
}
$value_statement = implode(', ', $values);
$sql="INSERT INTO string_check (st_name) VALUES $value_statement";

Are you going to store those four lines into different rows ? 您是否要将这四行存储在不同的行中? If that's the case then try this 如果是这种情况,请尝试

foreach($matches[2] as $value) {
    $sql="INSERT INTO string_check(st_name)VALUES($value)";
    $result=mysql_query($sql);
}

Here is the syntax if you want to store it into one row 如果要将其存储在一行中,请使用以下语法

$values = '';
foreach($matches[2] as $value) {
    $values .= $value;
}
$sql="INSERT INTO string_check(st_name)VALUES($values)";
$result=mysql_query($sql);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM