-1

I am trying to get some rows from a table that has columns row_ID,c_ID, e_ID, each e_ID can have different c_ID's. I use the mysql_fetch_array to get all c_ID's that are associated to a certain ID.

$result=mysql_query("SELECT c_ID from User_Competence WHERE e_ID=".$id);
            $test=mysql_fetch_array($result);
            print_r ($test['c_ID']);

But instead of getting several c_IDs for each e_ID, I get only one value in the array. Am I missing something in the query?

6
  • 1
    Is e_ID a unique field in User_Competence table? Commented Mar 11, 2013 at 13:14
  • 6
    You need to call it in a loop. There is an example on the PHP tag wiki stackoverflow.com/tags/php/info Commented Mar 11, 2013 at 13:14
  • 2
    You are using an obsolete database API and should use a modern replacement. We can't see where $id comes from but you may also be vulnerable to SQL injection attacks that a modern API would make it easier to defend yourself from. Commented Mar 11, 2013 at 13:14
  • 2
    FYI, PHP functions that start with mysql_ have been deprecated as of PHP 5.5.0. If you are in a position to do so, please consider updating your code to use the MySQLi or PDO extensions instead. Commented Mar 11, 2013 at 13:15
  • No it is not. only the row_ID is the primary key. Commented Mar 11, 2013 at 13:15

2 Answers 2

3

No, you do not have any errors. if e_ID is unique you will only get one result. You may want to try this if e_ID is not unique:

$result=mysql_query("SELECT c_ID from User_Competence WHERE e_ID=".$id);
while($test=mysql_fetch_array($result))
{
    print_r ($test['c_ID']);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why would I need a while if I want to print the whole array at once?
@auicsc - because each record is loaded as a separate array. If you switch to using PDO as your DB layer instead of the obsolete mysql_xxx() functions, then that does have the ability to load all records into a big array, using PDO::fetchall(), but as things stand, you need to use a loop; that's just the way it works.
@auicsc mysql_fetch_array is an array of the column values for a single row. You still have to call it separately for each row.
1

try this to get all ids

   $id = mysql_real_escape_string($id); // escape your variable here before u use it in the query

   $result=mysql_query("SELECT c_ID from User_Competence WHERE e_ID='".$id."' ");
        while ($test=mysql_fetch_array($result) ){
        echo $test['c_ID'].'<br />';
            }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.