Re: foreach
| From: | Matijn Woudt | Date: | Wed, 17 Oct 2012 15:17:41 +0000 |
| Subject: | Re: foreach | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-319499@lists.php.net to get a copy of this message | ||
On Wed, Oct 17, 2012 at 1:25 AM, Larry Garfield <larry@garfieldtech.com> wrote:
>
> For the love of god, please stop using ext/mysql (aka the mysql_*
> functions). It's insecure and slow and lacks features.
>
> Instead, use PDO, and bind your parameters. As a nice bonus, the result
> from a PDO-based query is not a raw resource but an iteratable object, which
> means you can foreach() it.
>
> http://php.net/manual/en/book.pdo.php
>
> $conn = new PDO(...);
> $result = $conn->query("SELECT * FROM items");
> foreach ($result as $record) {
> // Do something with each record here.
> }
>
> --Larry Garfield
>
Yes, the mysql extension is deprecated, but what's wrong with mysqli?
mysqli has the advantage that you don't need to keep a database handle
floating around, but you can just use mysqli_query everywhere.
When having multiple files and classes, it's terrible to pass $db to
each function/class, and I hate to use the global keyword.
just use while($record = $result->fetch_array()) instead of
foreach($result as $record)
And you mention ext/mysql is slow, well don't know about that, but PDO
is a bit slower than mysqli atleast.
I quote from [1]:
"For inserts, there was no significant difference between MySQLi and
PDO (prepared statements or not). For selects, MySQLi was about 2.5%
faster for non-prepared statements and about 6.7% faster for prepared
statements. "
- Matijn
[1] http://jnrbsn.com/2010/06/mysqli-vs-pdo-benchmarks