php - 将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();
}
这样做它不会向数据库中插入任何内容,但是当我替换$value
to时$value[0]
,它会输入第一个是#hello
.
我想将两者都作为新行输入到数据库中#hello
。#world
提前致谢。
解决方案
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();
}
}
推荐阅读
- flutter - 由于缺少 googleservicefile,flutter 风味构建失败
- discord.py - 添加特定用户以便能够使用 discord.py 查看文本频道
- json - 可序列化的泛型类型的 Kotlin 序列化
- td-engine - TDengine 报告“无效的表 ID”
- css - 视频背景顶部的顺风 css 模式
- r - 在同一张图中绘制两个数值变量
- r - 用于查找模式的 ifelse 语句,如果为真,则在另一个变量中编码一个值
- javascript - CSS snap 滚动属性捕捉网站的开始和结束
- sockets - HTTP CONNECT + GET 返回错误状态
- javascript - 如何在 Fullcalendar 中更改语言天数