Connect PHP and MySQL (Object Oriented )

Share

Connecting PHP and MySQL in the object-oriented method is pretty much similar to a procedural method. The only difference is we create an object instead of a calling function. We have mysqli class in PHP which takes a certain parameter to create a connection. This class has predefined methods and properties which helps PHP to interact and carry out the provided function.

Conneting MySQL Database using mysqli Class

<?php
$server = "localhost";
$username = "username";
$password = "password";
$database = "my_database";

// Create a connection
$connection = new mysqli($server, $username, $password, $database);

// Check connection
if ($connection->connect_error) {
  die("Connection Error: " . $connection->connect_error);
}
echo "Connection successfull";
?>

The way how object-oriented methods work is similar to a procedural method. In the object-oriented method, all the methods are encapsulated in the mysqli class. Let’s explore some more methods and properties that we use pretty much during creating connections and operation over databases.

  • mysqli::query() and mysqli::fetch_assoc()
<?php

$server = "localhost";
$username = "username";
$password = "password";
$database = "my_database";

$connection = new mysqli($server, $username, $password, $database);

if ($connection->connect_error) {
  die("Connection Error: " . $connection->connect_error);
}

$myquery = $connection->query("SELECT * FROM User LIMIT 10");

while ($row = $myquery->fetch_assoc()){
printf("Username:".$row['username']);
}
?>
  • Prepare Statement and executing


<?php

$server = "localhost";
$username = "username";
$password = "password";
$database = "my_database";

$connection = new mysqli($server, $username, $password, $database);

if ($connection->connect_error) {
  die("Connection Error: " . $connection->connect_error);
}
$username = "CodewithSudeep";

/* create a prepared statement */
$myquery = $connection->prepare("SELECT id FROM User WHERE Username=?");

/* bind parameters for markers */
$myquery->bind_param("s", $username);

/* execute query */
$myquery->execute();

/* bind result variables */
$myquery->bind_result($id);

/* fetch value */
$myquery->fetch();

printf("%s has id %s\n", $username, $id);
?>

For more methods and properties refer to the official documentation.

Share
Sudeep Mishra

Sudeep Mishra

Healing

Leave a Reply

Your email address will not be published.

%d bloggers like this: