0

I have a php function that interogates a table and gets all the fields in a column if a condition is fulfield. So the function returns a collection of elements. The problem is that i want this function to return an array that i can parse and display. The code below:

function get_approved_pictures(){
    $con = mysql_connect("localhost","valentinesapp","fBsKAd8RXrfQvBcn");
    if (!$con)
    { 
      echo 'eroare de conexiune';
      die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("mynameisbrand_valentineapp", $con);

    $all = (mysql_query("SELECT picture FROM users WHERE approved = 1")); 

    $row=mysql_fetch_assoc($all);
     //  mysql_close($con);

    return $row['picture']; 
  }

Where am I wrong?

2
  • the mysql_ extension is deprecated. Use mysqli_ or PDO Commented Feb 9, 2013 at 9:00
  • do not connect inside of every function. connect only once at the beginning of your code, and then just use the established connection all the way through Commented Feb 9, 2013 at 9:58

4 Answers 4

3

You need to use the loop for traversing all the data fetched by the query:

$pictures=array();
while($row=mysql_fetch_assoc($all))
{
    $pictures[]=$row['picture']; 
}
return $pictures;
Sign up to request clarification or add additional context in comments.

Comments

0

Do it like this

$all = mysql_query("SELECT picture FROM users WHERE approved = 1"); 
$arr = array(); // Array to hold the datas
while($row = mysql_fetch_array($all)) {
  $data = $row['picture'];
  array_push($arr,$data);
}
return $arr;

You can now insert it into a function and return the values.

Note : mysql_* functions are being depreciated. Try to avoid them.

Comments

-1

For the sake of diversity and to give you some sense of how to use PDO instead of deprecated mysql_*, this is how your function might look like:

function get_approved_pictures(){
    $db = new PDO('mysql:host=localhost;dbname=mynameisbrand_valentineapp;charset=UTF-8',
                  'valentinesapp', 'password');
    $query = $db->prepare("SELECT picture FROM users WHERE approved = 1");
    $query->execute();
    $pictures = $query->fetchAll(PDO::FETCH_ASSOC);
    $db = null;
    return $pictures;
}

Disclaimer: all error handling intentionally omitted for brevity

Comments

-1

For the sake of diversity and to give you some sense of how the things have to be instead of inconvenient and wordy PDO, this is how your function might look like:

function get_approved_pictures(){
    global $db;
    return $db->getCol("SELECT picture FROM users WHERE approved = 1");
}

Disclaimer: all error handling is up and running but intentionally encapsulated into private methods for invisibility.

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.