开发者

Generating variables from db content?

开发者 https://www.devze.com 2023-03-11 19:36 出处:网络
I am querying a database to get 6 values in my params table suing this; $result = mysql_query(\"SELECT * FROM params\");

I am querying a database to get 6 values in my params table suing this;

$result = mysql_query("SELECT * FROM params");
    while($row = mysql_fetch_array($result))
  {

    $param = $row['value'] ;

 } 

is this right, if so is their away i can add one to the variable name each开发者_开发技巧 time round so i get $param1, $param2....

I dont want to have to send a query to the database for each param, is it possible to get them all like this?


The simpliest way is to use an array:

$result = mysql_query("SELECT * FROM params");

$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
    $param[$i] = $row['value'] ;

    $i++;
}

Than you get $param[0], $param[1], ...


You can create variable names like this:

      ${'var'.1}
      ${'var'.'1.cat'}
      ${'var'.$x}
      ${$y.$x}

and so on.


This seems like a design flaw. But what you can do is:

$count = 1;

$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
    $paramname = 'param' . $count++;
    $$paramname = $row['value'] ;
} 


You may find the list function useful - http://php.net/manual/en/function.list.php

list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);

Probably more use when using descriptive variables, just a thought.

0

精彩评论

暂无评论...
验证码 换一张
取 消