PHP 选择脚本
在 PHP 函数中使用相同的 SELECT 语句来执行操作。您将再次使用mysql_query()函数。查看下面给出的示例 -
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT product_id, product_name,product_manufacturer, ship_date FROM products_tbl';
mysql_select_db('PRODUCTS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Product ID :{$row['product_id']} <br> ".
"Name: {$row['product_name']} <br> ".
"Manufacturer: {$row['product_manufacturer']} <br> ".
"Ship Date : {$row['ship_date']} <br>".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
成功检索数据后,您将看到以下输出 -
Product ID: 12345
Nomenclature: Orbitron 4000
Manufacturer: XYZ Corp
Ship Date: 01/01/17
----------------------------------------------
Product ID: 12346
Nomenclature: Orbitron 3000
Manufacturer: XYZ Corp
Ship Date: 01/02/17
----------------------------------------------
mysql> Fetched data successfully
最佳实践建议在每个 SELECT 语句之后释放游标内存。PHP为此提供了mysql_free_result()函数。如下所示查看其使用 -
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT product_id, product_name, product_manufacturer, ship_date FROM products_tbl';
mysql_select_db('PRODUCTS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM)) {
echo "Product ID :{$row[0]} <br> ".
"Name: {$row[1]} <br> ".
"Manufacturer: {$row[2]} <br> ".
"Ship Date : {$row[3]} <br> ".
"--------------------------------<br>";
}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>