略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: MySQL 扩展概述范例

2024-12-21

MySQL 扩展概述范例

这个简单的范例展示了如何连接、执行一个查询,打印结果集后断开 MySQL 数据库的连接。

示例 #1 MySQL 扩展概述范例

<?php
// 连接、选择数据库
$link mysql_connect('mysql_host''mysql_user''mysql_password')
    or die(
'Could not connect: ' mysql_error());
echo 
'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');

// 执行 SQL 查询
$query 'SELECT * FROM my_table';
$result mysql_query($query) or die('Query failed: ' mysql_error());

// 以 HTML 打印查询结果
echo "<table>\n";
while (
$line mysql_fetch_array($resultMYSQL_ASSOC)) {
    echo 
"\t<tr>\n";
    foreach (
$line as $col_value) {
        echo 
"\t\t<td>$col_value</td>\n";
    }
    echo 
"\t</tr>\n";
}
echo 
"</table>\n";

// 释放结果集
mysql_free_result($result);

// 关闭连接
mysql_close($link);
?>
add a noteadd a note

User Contributed Notes 1 note

up
-13
zjrwjzzz at 163 dot com
7 years ago
Be aware that if you are trying to foreach the associative array returned by mysql_fetch_array() with MYSQL_ASSOC or mysql_fetch_assoc(), you have to ensure the return value that is used in foreach structure is exactly a array rather than a FALSE value.

Or you might encounter the warning below:
    Warning: Invalid argument supplied for foreach()

Here is an example (assume that $result have already stored the return value from mysql_query()):

If you have some block of code like:

<?php

// Printing results in HTML
echo "<table>\n";
while (
$line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo
"\t<tr>\n";
    foreach (
$line as $col_value) {
        echo
"\t\t<td>$col_value</td>\n";
    }
    echo
"\t</tr>\n";
}
echo
"</table>\n";

?>

If this is the case, you should use the code below instead:

<?php

// Check ahead, before using it
if (mysql_num_rows($result) > 0) {
   
// Printing results in HTML
   
echo "<table>\n";
    while (
$line = mysql_fetch_array($result, MYSQL_ASSOC)) {
        echo
"\t<tr>\n";
        foreach (
$line as $col_value) {
            echo
"\t\t<td>$col_value</td>\n";
        }
        echo
"\t</tr>\n";
    }
    echo
"</table>\n";
}

?>

官方地址:https://www.php.net/manual/en/mysql.examples-basic.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3