Establish a connection to the database server and select the database you’ll be working with
Construct a query to send the server
Send the query
Iterate over the returned result rows
Free the resources used by the result and possibly the database connection
<?php
// Step 1: Establish a connection
$db = mysql_connect("localhost", "testusr", "secretpass");
mysql_select_db("testdb", $db);
// Step 2: Construct a query
$query = "SELECT * FROM foo WHERE bar = '" . mysql_real_escape_string($zip) . "'";
// Step 3: Send the query
$result = mysql_query($query, $db);
// Step 4: Iterate over the results
while($row = myql_fetch_assoc($result)) {
print_r($row);
}
// Step 5: Free used resources
mysql_free_result($result);
mysql_close($db);
对于pdo,可以遵循相同的过程,如下所示:
<?php
// Step 1: Establish a connection
$db = new PDO("mysql:host=localhost;dbname=testdb", "testusr", "secretpass");
// Step 2: Construct a query
$query = "SELECT * FROM foo WHERE bar = " . $db->quote($zip);
// Step 3: Send the query
$result = $db->query($query);
// Step 4: Iterate over the results
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
// Step 5: Free used resources
$result->closeCursor();
$db = null;
1条答案
按热度按时间bkhjykvo1#
php中的mysql不安全,不再受支持。然而,有一个新的基于cass的系统称为pdo。以下是一些基本信息:来源(https://www.sitepoint.com/migrate-from-the-mysql-extension-to-pdo/)基本查询
使用mysql扩展的函数处理数据库的基本工作流可以看作是一个5步过程:
对于pdo,可以遵循相同的过程,如下所示: