vistajess
vistajess

Reputation: 687

Searching for Id in MySql from an array using For Loop

I have an array of tag names which I passed via POST Method and I these tag names has its corresponding tag_id in the database. All I want is to search the id while iterating the array of tag names and I want the result of each query to be stored in an empty array. I think I just misunderstood something or what.

$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';

foreach ($tags_array as &$tag) {
    $sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
    $query = mysqli_query($conn, $sql);
    $result = mysqli_fetch_row($query);
    $tags_array_id[] = $result[0];
};

Please help guys, suggestions highly appreciated.

Upvotes: 0

Views: 266

Answers (3)

jjwdesign
jjwdesign

Reputation: 3322

Basically something like:

$sql = "SELECT * FROM `tbltag` WHERE tag_name IN('".implode("','", $tags_array)."')";

One last comment: You probably want to search for tag_id's instead of tag names, as you'll probably have those in your input ($_POST/$_GET). And as FuzzyTree has mentioned above, you'll want some type of ID validation and some kind of escaping of data going into the query to avoid SQL injection.

Upvotes: 2

Matt
Matt

Reputation: 1757

Question: Do you need the & in your foreach loop? You are not directly modifying the tags_array just using the information?

Trying adding the number to the array e.g add $x so you are adding in 1 record into 1 part of the array as you loop though.

$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
$x = 0;

foreach ($tags_array as &$tag) {
    $sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
    $query = mysqli_query($conn, $sql);
    $result = mysqli_fetch_row($query);
    $tags_array_id[$x] = $result[0];
    $x++;
};

Upvotes: 0

budirec
budirec

Reputation: 288

Use this instead

$tags_array = ['shoes','gadgets','fashion','food'];
$tags = implode("','", $tags_array);
$tags = "'".$tags."'";
$sql = "SELECT tag_id FROM tbltag WHERE tag_name IN ({$tags})";

Upvotes: 1

Related Questions