PHP mysqli fetch_object()関数
例-オブジェクト指向スタイル
結果セットの現在の行を返し、各フィールドの値を出力します。
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " .
$mysqli -> connect_error;
exit();
}
$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";
if ($result = $mysqli -> query($sql)) {
while ($obj = $result -> fetch_object()) {
printf("%s (%s)\n", $obj->Lastname, $obj->Age);
}
$result
-> free_result();
}
$mysqli -> close();
?>
下部にある手続き型の例を見てください。
定義と使用法
fetch_object()/ mysqli_fetch_object()関数は、結果セットの現在の行をオブジェクトとして返します。
注:この関数から返されるフィールド名では、大文字と小文字が区別されます。
構文
オブジェクト指向スタイル:
$mysqli_result -> fetch_object(classname, params)
手続き型:
mysqli_fetch_object(result, classname, params)
パラメータ値
Parameter | Description |
---|---|
result | Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result() |
classname | Optional. Specifies the name of the class to instantiate, set the properties of, and return |
params | Optional. Specifies an array of parameters to pass to the constructor for classname objects |
技術的な詳細
戻り値: | フェッチされた行の文字列プロパティを持つオブジェクトを返します。結果セットにこれ以上行がない場合はNULL |
---|---|
PHPバージョン: | 5歳以上 |
変更ログ: | 別のオブジェクトとして返す機能がPHP5.0.0で追加されました |
例-手続き型
結果セットの現在の行を返し、各フィールドの値を出力します。
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";
if ($result = mysqli_query($con, $sql)) {
while ($obj = mysqli_fetch_object($result)) {
printf("%s (%s)\n", $obj->Lastname, $obj->Age);
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
❮PHPMySQLiリファレンス