首页 > 解决方案 > 将php数组值插入数据库

问题描述

我正在研究这个标签系统。我正在尝试将主题标签词放入数据库中的新行。对于每个主题标签词,我需要将其插入新行。下面是我的php代码行...

$string = filter_var("#hello #world", FILTER_SANITIZE_STRING);
preg_match_all('/(?<!\w)#\w+/', $string, $matches);

foreach ($matches as $key => $value) {
    $stmt = $mysqli->prepare("INSERT INTO hash_tag (tagged_word) VALUES (?)");
    $stmt->bind_param("s", $value);
    $stmt->execute();
}

这样做它不会向数据库中插入任何内容,但是当我替换$valueto时$value[0],它会输入第一个是#hello.

我想将两者都作为新行输入到数据库中#hello#world提前致谢。

标签: phpmysqli

解决方案


Please change the foreach loop from:

foreach ($matches as $key => $value) {

To

foreach ($matches[0] as $key => $value) {

Because, $matches is a multi-dimensional array and we are trying to access its 0th and 1st elements, which are again arrays not strings.

If we try to access first sub-array of $matches, it will work perfectly.

So, the final code is:

<?php
$string = filter_var("#hello #world", FILTER_SANITIZE_STRING);
preg_match_all('/(?<!\w)#\w+/', $string, $matches);

if (isset($matches[0]) && ! empty($matches[0])) {
    foreach ($matches[0] as $key => $value) {
        //echo '<pre>';print_r($key);echo '</pre>';
        //echo '<pre>';print_r($value);echo '</pre>';
        $stmt = $mysqli->prepare("INSERT INTO hash_tag (tagged_word) VALUES (?)");
    $stmt->bind_param("s", $value);
    $stmt->execute();
    }
}

推荐阅读