Home » PHP » Fungsi mysqli prepare() PHP

Fungsi mysqli prepare() PHP

by Hanifah Nurbaeti
by Hanifah Nurbaeti

Section Artikel

Definisi dan Penggunaan

Fungsi prepare() / mysqli_prepare() digunakan untuk menyiapkan pernyataan SQL untuk dieksekusi.

Syntax

Object oriented style:

$mysqli -> prepare(query)

Procedural style:

mysqli_prepare(connection, query)

Nilai Parameter

ParameterDeskripsi
connectionRequired. Menentukan koneksi MySQL yang akan digunakan
queryRequired. Menentukan kueri SQL.
Catatan: Jangan menambahkan titik koma di akhir kueri!

Detail Teknis

Return Value:Mengembalikan objek pernyataan jika sukses. FALSE jika gagal
PHP Version:5+

Contoh – Object oriented style
Siapkan pernyataan SQL untuk eksekusi:

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

// Periksa Koneksi
if ($mysqli -> connect_errno) {
  echo "Gagal Menghubungkan ke MySQL: " . $mysqli -> connect_error;
  exit();
}

// Mempersiapkan dan ikat
$stmt = $mysqli -> prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt -> bind_param("sss", $firstname, $lastname, $email);

// atur parameters and eksekusi
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt -> execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt -> execute();

echo "New records created successfully";

$stmt -> close();
$mysqli -> close();
?>

You may also like