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 array 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.However, if you simply want variables to be created dynamically then extract() might do the trick.