Perl、PHP、RubyからMySQLへの接続
MySQL(ユーザー名:hogehoge、パスワード:gehogeho、データベース名:aho)に接続した後、 SELECT文を実行してテーブルからデータを取得・表示する Perl、PHP、Rubyのそれぞれのサンプルプログラムを以下に紹介します。
■Perlのサンプル
#!/usr/bin/perl
use DBI;
$dbuser="hogehoge";
$dbpass="gehogeho";
$dbname="aho";
$sql="select no, name from ana";
$dsn = "DBI:mysql:$dbname";
$dsh = DBI -> connect ( $dsn, $dbuser, $dbpass , { RaiseError => 0 } );
$sth = $dsh->prepare($sql);
$sth->execute;
$num_rows = $sth->rows;
print "Content-type: text/html\n\n";
print <<HTML_HEAD;
HTML_HEAD
if ($dsh) {
print "データーベースに接続しました<br>\n";
} else {
print "データーベースへの接続が失敗しました<br>\n";
}
print "該当件数: $num_rows 件<br>\n";
for ($i=0; $i<$num_rows; $i++) {
@a = $sth->fetchrow_array;
print "no=$a[0], name=$a[1] <br>\n";
}
print <<HTML_TAIL;
HTML_TAIL
$sth->finish;
$dsh -> disconnect;
exit(0);
■PHPのサンプル
<html>
<body>
<?php
$db_user = "hogehoge";
$db_pass = "gehogeho";
$db_host = "localhost";
$db_name = "aho";
$db = mysqli_connect($db_host, $db_user, $db_pass);
mysqli_select_db($db, $db_name) or die ("データベースへの接続に失敗しました");
if ($db) {
print "データーベースに接続しました<br>\n";
}
$sql="select no, name from ana";
$rs = mysqli_query($db, $sql);
while( $a = mysqli_fetch_array($rs) ) {
print "no=$a[0], name=$a[1] <br>\n";
}
mysqli_close($db);
?>
</body>
</html>
■Rubyのサンプル
#!/usr/local/bin/ruby
require "cgi"
require "mysql"
cgi = CGI.new
no = cgi["no"].to_i
sql = "select no, name from ana where no = \"#{Mysql.quote(no)}\""
m = Mysql.new('localhost','hogehoge','gehogeho','aho')
res = m.query(sql)
i = 0
no_a = [0]
name_a = [0]
res.each do |a|
no_a[i] = a[0]
name_a[i] = a[1]
i += 1
end
print "Content-type: text/html\n\n"
print <<EOF
<html>
<body>
該当件数: #{res.num_rows} 件<br>
EOF
for count in 0..i-1
print "no=#{$no_a[count]}, name=#{$name_a[count]} <br>\n";
end
print <<EOF
</body>
</html>
EOF
m.close