2008-11-09 91 views
1

采用标准方式(为简单起见,检查删除错误)一般来说,我连接和检索数据:如何使用PHP中的对象从MYSQL数据库连接/检索数据?

$db = mysql_select_db("dbname", mysql_connect("host","username","passord")); 
$items = mysql_query("SELECT * FROM $db"); 

while($item = mysql_fetch_array($items)) { 
    my_function($item[rowname]); 
} 

在哪里创建my_function做一些有益的事情witht该特定行。

什么是使用对象的等效代码?

回答

3

自从5.1版本,PHP是随PDO驱动程序,它给出了准备语句的类。

$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database 
//each :keyword represents a parameter or value to be bound later 
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass'); 

# Variables are set here. 
$query->bindParam(':id', $id); // this is a pass by reference 
$query->bindValue(':pass', $pass); // this is a pass by value 

$query->execute(); // query is run 

// to get all the data at once 
$res = $query->fetchall(); 
print_r($res); 

看到PDO driver at php.net

注意,当您使用binbParam或bindValue这种方式(预处理语句)将自动逃避一切必要而且是执行mysql的查询,最安全的方法之一,只要。

还有mysqli扩展名执行类似任务,但我个人发现PDO更清洁。

整个过程如何,并且使用所有这些步骤给您提供的解决方案可能比任何其他PHP解决方案都要好。

然后,您可以使用$query->fetchobject作为对象检索您的数据。