Jump to content

Store Selected ID Numbers Inside an Array with MySQL


glassfish

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?

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'];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.