2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【PHP】PHPからmysqlにデーターを挿入する。(mysqliを用いて)

Last updated at Posted at 2020-11-07

phpから、mysqliメソッドを用いて、MySQLに接続する方法。

$link = mysqli_connect('ホスト名', 'ユーザー名', 'パスワード', 'データベース名')

切断するには

mysqli_close($link)

エラーを表示。

mysqli_connect関数は、接続に失敗した場合 false を返す。

if (!$link) {
  //mysqli_connect_error()関数でエラーログ を表示
  echo mysqli_connect_error();
}

データーを操作する。

# $queryはクエリ文が格納されているとする。
mysqli_query($link, $query);
# mysqli_queryも保存に失敗したら false を返す。

結果を取得する。

$result = mysqli_query($link, $query);
mysqli_fetch_assoc($result);

注:結果を1行づつ取り出す。全行が配列となっているわけではない。

よって、

foreach($result as $row){
  echo $row['name'];
}

のような記述はエラーとなる。

繰り返すなら、

  while ($review = mysqli_fetch_assoc($result)) {
}

の様な記述となる。(nullとなったらfalseが返りループ終了。

また、結果を配列に格納するなら

  while ($review = mysqli_fetch_assoc($result)) {
   $reviews[] = $revies;
}

のようにし、ループで1行ずつ配列に格納していく。

メモリを開放する。

mysqli_free_result($result)
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?