Php Mysql 简明教程
PHP & MySQL - Select Records Example
您可以将相同的 SQL SELECT 命令用于 PHP 函数 mysql_query() 。此函数用于执行 SQL 命令,然后稍后可以使用另一个 PHP 函数 mysql_fetch_array() 来获取所有选定的数据。此函数将行作为关联数组、数字数组或两者返回。如果不再有行,则此函数将返回 FALSE。
You can use the same SQL SELECT command into a PHP function mysql_query(). This function is used to execute the SQL command and then later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns the row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows.
以下程序是一个简单的示例,它将展示如何从 tutorials_tbl 表中获取/显示记录。
The following program is a simple example which will show how to fetch / display records from the tutorials_tbl table.
Example
以下代码块将显示 tutorials_tbl 表中的所有记录。
The following code block will display all the records from the tutorials_tbl table.
将以下示例复制粘贴为 mysql_example.php:
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Selecting Records</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
echo 'Connected successfully<br />';
mysqli_select_db( $conn, 'TUTORIALS' );
$sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) {
echo "Tutorial ID :{$row['tutorial_id']} ".
"Title: {$row['tutorial_title']} ".
"Author: {$row['tutorial_author']} ".
"Submission Date : {$row['submission_date']} ".
"--------------------------------";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
?>
</body>
</html>
Output
访问部署在 apache Web 服务器上的 mysql_example.php,输入详细信息,并在提交表单时验证输出。
Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form.
Entered data successfully
在执行数据插入时,最好使用函数 get_magic_quotes_gpc() 来检查当前 magic quote 配置是否已设置。如果此函数返回 false,则使用函数 addslashes() 在引号前添加反斜杠。
While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes.
您可以进行许多验证,以检查输入的数据是否正确,并可以采取适当的操作。
You can put many validations around to check if the entered data is correct or not and can take the appropriate action.