开发者

A better way to set variables from a database query

I am using PHP5 and MySql, I wondered if there was a way of setting variables automatically instead of writing them all out?

I am currently using code such as this:

$sSQL = "SELECT * FROM myTable";
$result = mysqli_query($dbi,$SQL); 

if(mysqli_num_rows($result)==0){} 
else 
 {
   //loop and set array
   while ($row = mysqli_fetch_assoc($result)) {
     $field1 = $row['field1'];
     $field2 = $row['field2'];
     $field3 = $row['field3']; 
   }

  $newArray[] = (array(
        "field1" => "$field1",
        "field2" => "$field2",
        "field3" => "$field3"
      ));

Basically I am setting the variables to the same name as the SQL field names, and then setting an a开发者_如何学编程rray to the same. I was wondering if there was a quicker way of doing this that writing out all the names by hand? (I also know the select is bad, it's just there for illustration!)


One option is to use explicit field names in the SQL query and assign each result row directly. Besides, selecting columns with * reduces performance and makes the intent of your query less clear.

$sSQL = "SELECT field1, field2, field3 FROM myTable";

// other code

while ($row = mysqli_fetch_assoc($result)) {
    $newArray[] = $row;
}

However, if you simply want variables to be created dynamically then extract() might do the trick.


Why do you write "mysqli"? Why the i?

And about your question: The most usual way (and even the most simple way) is via mysql_fetch_object and then you describe a var like $var = $row->FIELD;

mysql_fetch_assoc is another possible feature, but the first one does work much better than assoc...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜