BarakaAka1Only
BarakaAka1Only

Reputation: 55

How to print multiple ID's from a $_GET variable using while() and array()

I'm here today because i'm under a minor issue that i can't seem to solve and it's why it brings be here. The issue is that i'm trying to get multiple ID's from a $_GET variable to print out. I tried to use array and great, it works but the thing is it makes separate arrays with [0] and i need it to be as one in the same array not array() array() which is what its doing.

So i'm using while() with mysql_fetch_array to get the results off the database and it depends on the $_GET from the url in-order to grab the correct id's. So in the URL i pass in api.php?do=remove&id=1,4,7 it will only print out the first id and not the others as a name. As i said i tried with array() and this is what came out :

Array
(
    [0] => BzlXO.jpg
)
Array
(
    [0] => cHZTk.jpg
)
Array
(
    [0] => 9yset.jpg
)
Array
(
    [0] => Ss04V.jpg
)

i don't understand why its doing that as i need it to be in one array as in

Array (

   [0] => BzlXO.jpg,
   [1] => cHZTk.jpg,
   [2] => 9yset.jpg,
   [3] => Ss04V.jpg
)

So that way when i implode them it will show as text as in: "You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg" with something like

        $iName[imagename] = array($iName[imagename]);
        $name = implode(",", $iName[imagename]);

Here is my code:

This is the URL "api.php?do=remove&id=1,4,7"

      $ID = $_GET['id'];
    $query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
    $result = mysql_query($query);

      while( $iName = mysql_fetch_array($result)){
          $querys = "DELETE FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
      $results = mysql_query($querys);

          if(!$results) {
       $api_message = 'Failed to get a Removal result';
       } else {

            $iName[imagename] = array($iName[imagename]);
            $name = implode(",", $iName[imagename]);

           $api_message = "You removed image(s) $name"; 

          }
}

The OUTPUT :

You removed image(s) BzlXO.jpg

but i need it to be:

The OUTPUT : You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"

Any help with this will be much appreciated, if any more information is needed please let me know and i'll include Thanks

Upvotes: 1

Views: 541

Answers (3)

Zuul
Zuul

Reputation: 16269

You should revise your code as to protect it against invalid values and reduce the possibility of failures.

As to your specific problem, there's no need to place values from one array inside another one, just to the goal of imploding it to a string. You can simply use string concatenation to keep adding the desired values.

This suggestion fixes you issue: code comments are to explain whats happening

// initialize the user message with the success string
$api_message = "You removed image(s): ";

// check if the URL variable exists and contains values
if (isset($_GET['id']) && $_GET['id']!='') {

    // clean the values a litle bit to prevent code injection
    $ID = strip_tags(trim($_GET['id']));

    // prepare the query (more compatible string concatenation)
    $query = "SELECT ID, imagename FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";

    // query the databse
    $result = mysql_query($query);

    // check for results
    if (is_resource($result) && mysql_num_rows($result)>=1) {

        // get total records
        $counter = mysql_num_rows($result);

        // run by each result found
        while($iName = mysql_fetch_array($result)) {

            // delete all from the database
            $querys = "DELETE FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
            $results = mysql_query($querys);

            // check if the returned result is false
            if (!$results) {

                // replace the user message with a fail information
                $api_message = 'Failed to get a Removal result';

            } else {

                // decrease the counter
                $counter--;

                // update the user message and add a "," if this is not the last name
                $api_message.= $iName['imagename'] . (($counter==0)?(''):(', '));

            }
        }

    } else {
        $api_message = 'ups... failed to talk with the database';
    }

} else {
    $api_message = 'ups... no ids collected';
}

Related reading:

  • PHP strip_tags

    strip_tags — Strip HTML and PHP tags from a string

  • PHP trim

    trim — Strip whitespace (or other characters) from the beginning and end of a string

  • PHP is_resource

    is_resource — Finds whether a variable is a resource

Upvotes: 1

Ken Keenan
Ken Keenan

Reputation: 10538

In addition to the solution posted by raina77ow, there is also a problem with the control flow in that you are executing the DELETE FROM uploads WHERE ID IN (...) statement for each iteration of the while loop. This will delete all the records on the first iteration. You need to change it to something like:

$ID = $_GET['id'];
$names = array();
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);

  while( $iName = mysql_fetch_array($result)){
      $querys = "DELETE FROM uploads WHERE ID = {$iName['ID']} AND username = '{$uploader}'";
      $results = mysql_query($querys);
      if(!$results) {
       $api_message = 'Failed to get a Removal result';
      } else {
        $names[] = $iName['imagename']);
      }
  }
  $name = implode(",", $names);
  $api_message = "You removed image(s) $name"; 

Upvotes: 2

raina77ow
raina77ow

Reputation: 106375

Perhaps you need to fill an array declared before the loop instead, like that:

$images = array();
while( $iName = mysql_fetch_array($result)) { 
  ...
  $images[] = $iName['imagename']; # pushing the deleted image into that array
}
...
$names = implode(', ', $images);

And I strongly suggest at least checking the possibility of using mysqli set of functions instead (or PDO, that's even better in my opinion, but might be a step too huge for your codebase). )

Upvotes: 2

Related Questions