简体   繁体   中英

PHP: How do you avoid the use of extract() in a specific case

I'm very new to PHP and have been reading everywhere that the use of the extract function is not recommended. I'm fetching data from a mysql table to populate a section of a website. Therefore I don't know how many rows the table could have.

So I'm using the extract function which gives me an array of arrays for each row. In order to create some variables that would facilitate the 'echoing' of each field I'm using this code:

$query = "SELECT * FROM example";
$result = mysqli_query($link,$query);
$num = mysqli_num_rows($result);
$gharray = mysqli_fetch_all($result,MYSQLI_ASSOC);
$arrayrows = array_keys($gharray);
foreach ($arrayrows as $arrayrow) {
   $i = $arrayrow;
};
foreach ($gharray[$i] as $ghimg) {
   extract ($gharray[$i], EXTR_PREFIX_ALL, "img"."$i");
};

It gets the job done and creates variables such as: $img1_title, $img1_description, $img2_title , etc. (This will be mentioned in a comment so these variables have an explanation when backtracking.

But I'm wondering if this is a correct use or if there's a simpler, cleaner solution to achieve the same results. Or if there's a set limit of rows (ie six) would you do it differently?

We sanitize all the content posted to the database so there should be no trouble. (Plus the admin is the only one who can post info there). Anyway help would be appreciated.

You could use list () but you'll need an enumerated array. Check PHP Documentation:

$row = [];
$row[0] = 123;
$row[1] = 'data';
 list($id, $data) = $row; 

http://php.net/manual/en/function.list.php

Basically list($id, $data) = $row; does:

$id = $row[0];
$data = $row[1];

Which is way shorter with more variables.

Counting variables:

To count variables (which seems to be the intention of your first loop?), you can use:

    $number_of_rows_in_your_array = count($arrayrows);

Cleaner solution:

You weren't very specific on HOW you want to populate the site. Assuming that you want to populate a simply table with identical row structures, then you don't need x variables. Insteady, You could replace both of your loops with something like this:

    echo '
    <table>
      <tr>
        <td>
          Header row
        </td>
      </tr>';
      for($x=0;$x=count($arrayrows);$x++){
        echo '
        <tr>
          <td>
             '.$arrayrows[$x].'
          </td>
        </tr>';
      }
    echo '
    </table>';

Here, I'm using the array and I'm displaying the $ith element with each iteration. Thus, there's no need for x variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM