Jump to content

Store Selected ID Numbers Inside an Array with MySQL


glassfish
 Share

Go to solution Solved by Barand,

Recommended Posts

The Script:

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <input type="text" name="hashtags" />
    <input type="submit" name="submit" />

</form>
<?php

include("connect.php");

?>
<?php

if(isset($_POST['submit'])){

    $hashtags = explode(", ", $_POST['hashtags']);

    for($i= 0; $i < count($hashtags); $i++){

        $tqs = "SELECT `id` FROM `hashtags_two` WHERE `hashtags` = '" . $hashtags[$i] . "'";
        $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));

    }

    $fetch_array = array();
    while($row = mysqli_fetch_array($tqr)){
        $fetch_array[] = $row['id'];
    }

}

Hey, sorry for these fundamental array questions lately, I am not going to ask much more when it comes to this.

 

The hashtags come from the submit form (separated by commas) and get stored inside an array with the "explode()" function. The script should select the ID numbers of the hashtags from the table.

 

With the script above only the last row gets inserted into $fetch_array inside the while loop.

 

When the $fetch_array variable is printed on screen then only one ID number can be seen inside the array:

Array ( [0] => 24 ) 

How can I have the other ID numbers too?

Link to comment
Share on other sites

  • Solution

You run several queries inside a loop, then, when the loop exits, you process the results of the last query.

 

What you should do is fetch all the data in a single query then process the results.

$hashtags = explode(", ", $_POST['hashtags']);

$hashlist = join ("','", array_map(array($dbc,'real_escape_string'),$hashtags));

$tqs = "SELECT `id` 
        FROM `hashtags_two` 
        WHERE `hashtags` IN ('$hashlist')";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));

$fetch_array = array();
while($row = mysqli_fetch_array($tqr)){
    $fetch_array[] = $row['id'];
}
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.