0

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.

1 Answer 1

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.