PHP vol.25

MySQLへの接続

接続開始
データベースの切替
SQLを実行するために使う関数
結果の取得

1レコードをひとつの配列に入れて取得することができる
ポインタが取得毎に一個ずつ移動していく。

接続を切る

練習

DBの授業で使っていたデータベースからEmployeesの中身を表示する。

<html>
<head>
<title>DB接続練習</title>
</head>
<body>
<?php
$link = mysql_connect('localhost','MySQLユーザー名');
$db_selected = mysql_select_db("DB名");
$sql = "select * from employees";
$result = mysql_query($sql,$link);
?>
<table border="1">
<?php while($list = mysql_fetch_row($result)): ?>
  <tr>
    <?php foreach ($list as $value): ?>
    <td><?php echo $value; ?></td>
    <?php endforeach; ?>
  </tr>
<?php endwhile; ?>
</table>
<?php
mysql_close($link);
?>
</body>
</html>

選択と実行を同時に行う

<?php
$link = mysql_connect('localhost','MySQLユーザー名');
$sql = "select * from employees";
$result = mysql_db_query('DB名',$sql,$link);
?>
<html>
<head>
<title>DB接続練習</title>
</head>
<body>
<table border="1">
<?php while($list = mysql_fetch_row($result)): ?>
  <tr>
    <?php foreach ($list as $value): ?>
    <td><?php echo $value; ?></td>
    <?php endforeach; ?>
  </tr>
<?php endwhile; ?>
</table>
<?php
mysql_close($link);
?>
</body>
</html>

フォームからSQL文を入力して表示する。

<?php
if (isset($_POST['sql_command'])) {
    $link = mysql_connect('localhost','MySQLユーザー名');
    $sql = $_POST['sql_command'];
    $result = mysql_db_query('DB名',$sql,$link);
}
?>
<html>
<head>
<title>DB接続練習</title>
</head>
<body>
<form method="post" action="">
<h2>SQL文</h2>
    <textarea name="sql_command" /></textarea>
    <input type="submit" value="実行" />
</form>
<?php if(isset($_POST['sql_command'])): ?>
  <table border="1">
    <?php while($list = mysql_fetch_row($result)): ?>
      <tr>
        <?php foreach ($list as $value): ?>
          <td><?php echo $value; ?></td>
        <?php endforeach; ?>
      </tr>
    <?php endwhile; ?>
  </table>
<?php
mysql_close($link);
?>
<?php endif; ?>
</body>
</html>