开发者

Am I missing something? Reading from database in PHP seems long-winded

So, if I want to pull some data from my database (PHP, MySql), whether I'm writing for a class or hard-coded, I've been doing something along the lines of:

$x = "SELECT <column(s)> FROM <table> WHERE <conditions>";开发者_运维问答
$y = mysql_query($x);
while($result = mysql_fetch_assoc($y))
{
echo $result['column']; // etc
}

Obviously I use a function or class (depending on design pattern) so pulling data like this is done in one line, I just wondered if I was doing 'too much work' and if there was a quicker way of doing this.

Thanks.


You can get tighter code by using a more up-to-date PHP module to access your database.

The mysql_xxx() functions that you're using have been superseded by the mysqli_xxx() functions. This uses similar code, but provide more features and security than the older library:

$query = 'SELECT <column(s)> FROM <table> WHERE <conditions>';
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        print $row['column'];
    }
}

You can find out more about MySQLi (including how it differs from the old MySQL library) here: http://php.net/manual/en/book.mysqli.php

But for really concise code, you might consider looking into the PDO library. Your query could be expressed with PDO like this:

$sql = 'SELECT <column(s)> FROM <table> WHERE <conditions>';
foreach ($conn->query($sql) as $row) {
    print $row['column'];
}

...and if you really wanted to, the first two lines of that code could be combined as well.

Find out more about PDO at the PHP manual site: http://www.php.net/manual/en/book.pdo.php


Looks good. you maybe can merge the first tow lines into "$y = mysql_query('SELECT FROM WHERE ');"

And notice that in PHP its faster (from compile time) to use single quotes (') rather that double quotes (").

It depends on the further work, but you might wanna consider loading the info into XML dom format. (If you want to do more sophisticated things that just representing the data)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜