0

what am trying to do here is get data from mysql generated checkboxes. The check boxes data are in array . So for all the check boxes selected I want to use each as a parameter in a query to get more info from another databastablee.

Sample Code Below

if (isset($_POST['submitCourseCode'])) { 
     //GET ARRAY FROM DATABASE GENERATED CHECKBOXES                                         
     $aElective =  $_POST['electiveModules'];


    foreach($aElective  as $snode) {                                                    
        echo "$snode <br />";
    }
    //PASSING EACH DATA FROM ARRAY INTO QUERY   
    $Query = "SELECT ID,title,credits 
             FROM module 
             WHERE ID IN('" . implode("', '", $aElective) ."')";

    $Result = mysql_query($Query) 
    or die ("Query failed: " . mysql_error() . " Actual query: " . $Query);

    while ($Row = mysql_fetch_array($Result)) {

           $id = htmlentities($Row['ID']);
           $title = htmlentities($Row['title']);
           $credits = $Row['credits'];

    echo "<ul>" . $id . " " . $title .  " " . $credits . "</ul>";

    }  
}
var_dump($Query);   
var_dump($Result);  
var_dump($Row);     

Screenshot of my result enter image description here

Am guessing something is happening with my query probably because of the implode function but everything seems fine in my query.Any suggestions on what am doing wrong?

2 Answers 2

1

You need to trim array elements using array_map('trim', $aElective) as:

$Query = "SELECT ID,title,credits 
         FROM module 
         WHERE ID IN('" . implode("','", array_map('trim', $aElective)) ."')";
Sign up to request clarification or add additional context in comments.

4 Comments

+1, the problem is the extra space, but not quite as @Fluffeh thought. It is here in the $aElective variable.
@davidethell. I get error when I tried using trim.Warning: trim() expects parameter 1 to be string, array given in C:\wamp\www\xtra.php and then the query is empty.
Sorry, you're right. The values need to be trimmed, not the array itself. Do this before you implode: $aElective=array_map('trim',$aElective);
@davidethell.Thanks so much.My last five hours of trying to figure this out has come to an end.Thanks to U !! Have a great day sir !!
1

There is a problem with white spaces before your IDs in IN clause.

Try to add a str_replace() call

$Query = "SELECT ID,title,credits 
         FROM module 
         WHERE ID IN('" . str_replace(" ", "", implode("', '", $aElective)) ."')";

1 Comment

@wildnove.Thanks for the suggestion. It's working now.Have a great day sir !

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.