Is there a better way of doing this?

I found some sample code that basically uses SQL PDO and then outputs the data into a table. However, I’ve done this in the past (years ago, but don’t recall using this escape function.) I am having trouble finding what it is or its use on DuckDuckGo.

Is there a better way of doing this?

  $connection = new PDO($dsn, $username, $password, $options);

  $sql = "SELECT * FROM users";

  $statement = $connection->prepare($sql);
  $statement->execute();

  $result = $statement->fetchAll();


<?php foreach ($result as $row) : ?>
    <tr>
      <td><?php echo escape($row["id"]); ?></td>
      <td><?php echo escape($row["firstname"]); ?></td>
      <td><?php echo escape($row["lastname"]); ?></td>
      <td><?php echo escape($row["email"]); ?></td>
      <td><?php echo escape($row["age"]); ?></td>
      <td><?php echo escape($row["location"]); ?></td>
      <td><?php echo escape($row["date"]); ?> </td>
  </tr>

It works, don’t get me wrong, it’s just that I like to know what functions do so I can use them on my own without always having to rely on the tutorial code in the future.

I know from my experience with Java, and, to a lesser extent, C++. that there’s a structure called a map that has a key and a value. It almost looks like the escape function is being passed the key of “date”, “location”, etc, and echoing the value for that iteration.

Just have a look at Arrays

Only thing i am missing is that there is no limitation in the amount of results. Fetching one million records in one time and putting them in an array is not such a good idea… But properly you already know.

“escape” is not a native php function, if you’re using a proper IDE you should be able to ctrl-click the function name to go to its definition (which probably is somewhere in the tutorial code base). If not you should just search the tutorial folder for “function escape(” and find it yourself

I did find this code in a file.

function escape($html) {
return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, “UTF-8”);
}

Someone mentioned that there was a better way than doing arrays. What would that be if you did need to do a SELECT *?

It’s just a wrapper for another function, to shorten it I guess.

You don’t want to do a SELECT *, you want to specify what columns you want always.
It isn’t that there is a better way, but there are different ways. If you know java, then you are aware of objects? You can create a model of the data, then have pdo dump the results into the model.

Sponsor our Newsletter | Privacy Policy | Terms of Service