简体   繁体   English

将 php 数组值插入数据库

[英]Insert php array value into database

I am working on this hashtag system.我正在研究这个标签系统。 am trying to get the hashtag words into the database in a new row.我正在尝试将主题标签词放入数据库中的新行。 for every hashtag word i need it to insert into a new row.对于每个主题标签词,我需要将其插入新行。 Below is my php line of code...下面是我的 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();
}

doing it this way it doesnt insert anything into the database but when i replace the $value to $value[0] , it input the first which is #hello .这样做它不会向数据库中插入任何内容,但是当我将$value替换为$value[0]时,它会输入第一个#hello

I want to input both #hello and #world into the database as a new row.我想将#hello#world作为新行输入到数据库中。 Thanks in advance.提前致谢。

Please change the foreach loop from:请从以下位置更改 foreach 循环:

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.因为, $matches是一个多维数组,我们正在尝试访问它的第 0 和第 1 个元素,它们又是 arrays 而不是字符串。

If we try to access first sub-array of $matches , it will work perfectly.如果我们尝试访问$matches的第一个子数组,它将完美运行。

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();
    }
}

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

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