0

Is there a quick way to filter a mysql_query result to get a list containing only values of a specific column?

$query = mysql_query("SELECT * FROM users");
$list_of_user_names = get_values($query,"names");

What is the name of the function to be used in place of get_values?

1
  • 1
    SELECT names FROM users and then fetch the first column. Commented Feb 15, 2013 at 4:43

3 Answers 3

1

Assuming your field name in databse is "names"

$query = mysql_query("SELECT names FROM users");

while($row = mysql_fetch_assoc($query)){
    echo $row['names'];
    echo "<br>";
}

NOTE : mysql_* functions are deprecated in new version of php, use mysqli_* or PDO

Sign up to request clarification or add additional context in comments.

Comments

0

Use below function.

  function get_values($q,$c)
  {
       $arr = array();
       while($row = mysql_fetch_array($q))
       {
            $arr[] = $row[$c];
       }
       return $arr; // return all names value.
  }

2 Comments

No, I mean... thank you, this does answer the question, but I'm looking for an official implementation (or something that could be used on it's place, such as a filter function).
@Dokkat You have to iterate the mysql result to obtain the result. :)
0

Try this:

$query = mysql_query("SELECT names FROM users");

if (!$query) {
    echo "Could not successfully run query from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($query) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $names

while ($row = mysql_fetch_assoc($query)) {
    echo $row["names"];

}

Comments

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.