downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

MySQL 関数> <
Last updated: Fri, 06 Nov 2009

view this page in

以下は、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 note add a note User Contributed Notes
MySQL 拡張モジュールに関する例
Sz.abi
19-Feb-2009 11:26
You might want to do something like this to output the column names as well:

<?php
echo "<table border=\"1\">\n";
$line = mysql_fetch_array($result, MYSQL_ASSOC);
    echo
"\t<tr>\n";
        echo
"\t\t<th>#</th>\n";
    foreach (
array_keys($line) as $col_value) {
        echo
"\t\t<th>$col_value</th>\n";
    }
    echo
"\t</tr>\n";
$i=0;
do  {
    echo
"\t<tr>\n";
   
$i++;
    echo
"\t\t<th>$i</th>\n";
    foreach (
$line as $col_value) {
        echo
"\t\t<td>$col_value</td>\n";
    }
    echo
"\t</tr>\n";
}while (
$line = mysql_fetch_array($result, MYSQL_ASSOC));
echo
"</table>\n";
?>

(Ok, here I also added line numbers; the main point of this post is using array_keys(...) to display the column names, and using a do {...} while (...); construct to read the first line only once).

MySQL 関数> <
Last updated: Fri, 06 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites