Maurice
Maurice

Reputation: 127

Convert MySQL result to an array strings

I am selecting names of my products from products table in MySQL then I want to present these names to something like
$names = array(name1, name2, ...)
Where name1, ... are the names of the products from MySQL. I have gone through suggested similar cases but none seems to solve my problem. I am a newbie and just trying to learn.

Upvotes: 3

Views: 11290

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157889

Dunno why everione sticked to one-liner but anyway it's always good idea to make your code less bloated

create a function

  function dbGgetCol($sql) {
    $ret = array(); 
    $res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql); 
    if ($res) {
      while ($row = mysql_fetch_row($result)) {
        $ret[] = $row[0]; 
      }
      mysql_free_result($res); 
    }
    return $ret;
  }

place it in some config file included into each script
and then get your array with this simple code

$names = dbGetCol("SELECT name FROM products");

Upvotes: -1

Naltharial
Naltharial

Reputation: 2152

Well, from an academic point of view, I suppose there's a "viable" alternative in doing something like

$names = explode('<|>', mysql_result(mysql_query(
    "SELECT GROUP_CONCAT(name separator '<|>') FROM products GROUP BY 'name'"
), 0));

All the power of loops and arrays in single line, for the low, low price of making baby Jesus cry. And yes, you should probably use a loop. Unless you have a phobia ever since a loop waited for you outside your school when you were little and beat you up, I guess.

Upvotes: -1

NeverPhased
NeverPhased

Reputation: 1566

$result = mysql_query("

SELECT `productname` FROM `products`

")or die($result."<br/><br/>".mysql_error());

    $numrows  = mysql_num_rows($result);  

    while ($row = mysql_fetch_assoc($result))
    {

    $productname[$i] = $row['productname'];

            // to print out use the following
             echo $productname[$i];
            $i++;

    }

Upvotes: -1

Eugen Rieck
Eugen Rieck

Reputation: 65284

$result = mysql_query("SELECT name FROM products");
$names=array();
while ($row = mysql_fetch_row($result)) $names[]=$row[0];
mysql_free_result($result);

You need the loop, as there is no way to directly get all rows of the complete result set.

Upvotes: 5

Related Questions