Jump to: navigation, search

PHP MySQLi Fetch Records Use binding

From w3cyberlearnings

Contents

PHP MySQLi Fetch Records Using Binding with prepare and execute

Find a record using binding, prepare, execute, and variable bindings.

Syntax Binding

$query ="SELECT * FROM student WHERE age >=?";
$conn = $db->prepare($query) or die("Error");
$conn->bind_param("i", $age);//binding for the where clause
$conn->execute();
$conn->bind_result($id, $name, $age);
while ($conn->fetch()) {
     echo $id. '  '. $name .'  '. $age .'<br/>';
}

Example 1

<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);
// age to search
$age = 10;

if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$query =
	  "SELECT * FROM student WHERE age >=?";
$conn = $db->prepare($query) or die("Error");
$conn->bind_param("i", $age);
$conn->execute();
$conn->bind_result($id, $name, $age);

$my_table = '<table border="1">';
$my_table .='<tr><td>Id</td><td>Name</td><td>Age</td></tr>';

while ($conn->fetch()) {
$my_table .='<tr>';
$my_table .='<td>' . $id . '</td>';
$my_table .='<td>' . $name . '</td>';
$my_table .='<td>' . $age . '</td>';
$my_table .='<tr>';
}
$my_table .='</table>';

echo $my_table;

$conn->close();

$db->close();
?>

Output

Php mysqli fetch associative 1.png

<sidebar>

    • PHP MySQL mysqli|PHP MySQL mysqli
    • PHP MySQLi Connect|PHP MySQLi Connect
    • PHP MySQLi Create Table|PHP MySQLi Create Table
    • PHP MySQLi Insert Records Using Binding|PHP MySQLi Insert Records use Binding
    • PHP MySQLi Fetch Records as an associative array|PHP MySQLi Fetch Records as an associative array
    • PHP MySQLi Fetch All Records|PHP MySQLi Fetch All Records
    • PHP MySQLi Fetch Records And Bind to variables|PHP MySQLi Fetch Records And Bind to variables
    • PHP MySQLi Fetch as object|PHP MySQLi Fetch as object
    • PHP MySQLi Fetch Records Use binding|PHP MySQLi Fetch Records Use binding
    • PHP MySQLi Update Records and Return affected rows|PHP MySQLi Update Records and Return affected rows
    • PHP MySQLi Delete Records Use binding|PHP MySQLi Delete Records Use binding

</sidebar>

Navigation
Web
SQL
MISC
References