Fungsi PHP mysqli fetch_assoc()
Contoh - Gaya Berorientasi Objek
Ambil baris hasil sebagai larik asosiatif:
<?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";
$result = $mysqli -> query($sql);
// Associative array
$row = $result
-> fetch_assoc();
printf ("%s (%s)\n", $row["Lastname"], $row["Age"]);
// Free result set
$result
-> free_result();
$mysqli -> close();
?>
Lihat contoh gaya prosedural di bawah.
Definisi dan Penggunaan
Fungsi fetch_assoc() / mysqli_fetch_assoc() mengambil baris hasil sebagai larik asosiatif.
Catatan: Nama bidang yang dikembalikan dari fungsi ini peka huruf besar-kecil.
Sintaksis
Gaya berorientasi objek:
$mysqli_result -> fetch_assoc()
Gaya prosedural:
mysqli_fetch_assoc(result)
Nilai Parameter
Parameter | Description |
---|---|
result | Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result() |
Detail Teknis
Nilai Kembali: | Mengembalikan array asosiatif string yang mewakili baris yang diambil. NULL jika tidak ada lagi baris di hasil-set |
---|---|
Versi PHP: | 5+ |
Contoh - Gaya prosedural
Ambil baris hasil sebagai larik asosiatif:
<?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";
$result = mysqli_query($con, $sql);
// Associative array
$row = mysqli_fetch_assoc($result);
printf ("%s (%s)\n", $row["Lastname"], $row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
Referensi PHP MySQLi