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...
$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
.
I want to input both #hello
and #world
into the database as a new row. Thanks in advance.
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();
}
}
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.