LoginSignup
28
30

More than 5 years have passed since last update.

mysqlからmysqliへの書き換え方法

Last updated at Posted at 2016-04-30

概要

PHP7系以降のバージョンでは、mysql関数が使用出来ない為、mysqliクラスまたはPDOクラスの関数等で書き換える必要がある。現在多くの主要レンタルサーバ等では、標準でPHP5系が採用されており、セキュリティ等のサポート切れの問題で、PHP7系に切り替わる日がやってくることが予想されるが、今からmysql関数で記述されている部分を書き換えておけば安心である。今回はmysql関数をmysqliクラスの関数等で書き換える方法についてまとめておく。

mysqliとは

mysqlの機能拡張版である。
mysqli = mysql + improved

オブジェクト指向型で書き換える

手続き型(クラスを利用していない)ではなく、オブジェクト指向型(mysqliクラスをオブジェクト化して使用)での書き換えが推奨されているので、それに従い書き換える方法を示す。

mysql関数(手続き型)

//データベースに接続
$con = mysql_connect($host, $username, $password);
if (!$con) {
    error_log(mysql_error());
    exit;
}

//データベースの選択
$res = mysql_select_db($dbname, $con);
if (!$res) {
    error_log(mysql_error());
    exit;
}

//SQLを実行
$res = mysql_query($sql, $con);
if (!$res) {
    error_log(mysql_error());
    exit;
}

//結果の出力
while($row = mysql_fetch_assoc($res)){
    error_log(mysql_real_escape_string($row['name']));
}

//接続のクローズ
mysql_close($con);

mysqli関数(オブジェクト指向型)

//データベースの接続と選択
$mysqli = new mysqli($host, $username, $password, $dbname);
if ($mysqli->connect_error) {
    error_log($mysqli->connect_error);
    exit;
}

//SQLを実行
$res = $mysqli->query($sql);
if (!$res) {
    error_log($mysqli->error);
    exit;
}

//結果の出力
while ($row = $res->fetch_assoc()){
    error_log($mysqli->real_escape_string($row['name']));
}

//接続のクローズ
$mysqli->close();

mysql_connect()関数&mysql_select_db()関数を書き換える

newしてmysqliオブジェクトを作成する。4番目の引数データベース名を指定することで、DBの接続と選択処理が一行で書ける。

$mysqli = new mysqli($host, $username, $password, $dbname)

mysql:http://php.net/manual/ja/function.mysql-connect.php
mysqli:http://php.net/manual/ja/function.mysqli-connect.php

mysql_query()関数を書き換える

 $mysqli->query($sql)

mysql:http://php.net/manual/ja/function.mysql-query.php
mysqli:http://php.net/manual/ja/mysqli.query.php

mysql_fetch_assoc()関数を書き換える

$result = $mysqli->query($sql)
$result->fetch_assoc()

mysql:http://php.net/manual/ja/function.mysql-fetch-assoc.php
mysqli:http://php.net/manual/ja/mysqli-result.fetch-assoc.php

mysql_error()関数を書き換える

$mysqli->error

mysql:http://php.net/manual/ja/function.mysql-error.php
mysqli:http://php.net/manual/ja/mysqli.error.php

mysql_real_escape_string()関数を書き換える

$mysqli->real_escape_string($string)

mysql:http://php.net/manual/ja/function.mysql-real-escape-string.php
mysqli:http://php.net/manual/ja/mysqli.real-escape-string.php

28
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
30