简体   繁体   中英

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.

$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:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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