Re: foreach

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Oct 17, 2012 at 1:25 AM, Larry Garfield <larry@xxxxxxxxxxxxxxxx> 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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux