← Back to PHP Course | Chapter 11: Database | Lesson 2 of 21

PHP MySQLi Connection

एक MySQLi connection database तक पहुँचने के लिए एक phone number dial करने जैसा है। आप PHP को address, name, और password देते हैं, और यह एक line खोल देता है ताकि आप questions पूछ सकें।
Syntax
php
$conn = mysqli_connect($host, $user, $password, $database);   // procedural
$conn = new mysqli($host, $user, $password, $database);        // object-oriented

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

mysqli_close($conn);

MySQLi क्या है?

mysqli_connect($host, $user, $password, $database) mysqli extension की procedural style इस्तेमाल करके MySQL server से एक connection खोलता है, एक connection object return करते हुए जिसे आप बाद के query functions को pass करेंगे।

उदाहरण: What is MySQLi?

php
<?php
// SQLite3 stands in for mysqli_connect() here -- on your own server:
// $conn = mysqli_connect("localhost", "root", "", "my_app");
$conn = new SQLite3(':memory:');
echo "Connection established";
?>

Connection बंद करना

object-oriented style इसके बजाय एक new mysqli($host, $user, $password, $database) instance बनाती है, और ज़्यादातर modern PHP code इस style को prefer करता है क्योंकि यह दूसरे object-oriented database code के साथ ज़्यादा naturally पढ़ता है।

उदाहरण: Closing the Connection

php
<?php
// Object-oriented style: $conn = new mysqli($host, $user, $password, $database);
$conn = new SQLite3(':memory:');
echo get_class($conn);
?>

Connection Errors Handle करना

connect होने के तुरंत बाद हमेशा connection में errors check करें, mysqli_connect_error() या object की ->connect_error property इस्तेमाल करके, ताकि एक गलत password या unreachable host बाद के confusing errors की एक cascade के बजाय एक clear message के साथ fail हो।

उदाहरण: Handling Connection Errors

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$conn`
$conn = new SQLite3(':memory:');
// Check whether `!$conn`
if (!$conn) {
    // Print "Connection failed" to the output
    echo "Connection failed";
// Otherwise, run this branch
} else {
    // Print "Connected successfully" to the output
    echo "Connected successfully";
}
?>

एक Database Select करना

Connection credentials (host, username, password) को version control में committed किसी script में कभी directly hardcode नहीं किया जाना चाहिए — उन्हें environment variables या एक gitignored config file में store करना secrets को आपके repository से बाहर रखता है।

उदाहरण: Selecting a Database

php
<?php
// Declare `$host`, set to `getenv('DB_HOST') ?: 'localhost'`
$host = getenv('DB_HOST') ?: 'localhost';
// Declare `$user`, set to `getenv('DB_USER') ?: 'root'`
$user = getenv('DB_USER') ?: 'root';
// Print "Connecting to $host as $user (credentials from environment, not hardcoded)" to the output
echo "Connecting to $host as $user (credentials from environment, not hardcoded)";
?>

एक Simple Query Execute करना

mysqli_close() या ->close() से explicitly एक connection close करना अच्छा practice है, हालाँकि PHP script के execution के अंत में automatically भी कोई खुले connections बंद कर देगा।

उदाहरण: Executing a Simple Query

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$conn`
$conn = new SQLite3(':memory:');
$conn->exec("CREATE TABLE test (id INTEGER)");
// Print "Query executed" to the output
echo "Query executed";
$conn->close();
// Print " -- connection closed" to the output
echo " -- connection closed";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. connect होने के बाद $mysqli->connect_error check न करना, ताकि एक failed connection ignore हो जाए और बाद की queries confusing errors के साथ fail हो जाएँ।
  2. पुराने mysql_* functions इस्तेमाल करना, जो PHP 7 में हटा दिए गए थे और अब exist नहीं करते।
  3. publicly served script में database credentials hard-code करना बजाय उन्हें एक protected config file में रखने के।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.