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

PHP MySQL Connect

किसी PHP script के MySQL database के against कोई query चलाने से पहले, इसे पहले एक connection establish करना ज़रूरी है -- MySQL को बताना कि किस server से बात करनी है, और एक username व password से authenticate करना। mysqli_connect() (या object-oriented new mysqli(...)) उस connection को खोलने का standard तरीका है।
Syntax
php
$conn = mysqli_connect($host, $username, $password, $database);

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

mysqli_close($conn);

एक Basic Connection Establish करना

mysqli_connect($host, $username, $password, $database) दिए गए credentials इस्तेमाल करके MySQL server से एक connection खोलता है और तुरंत named database select करता है, एक connection object return करते हुए जिसे आप बाद में हर query function को pass करेंगे।

उदाहरण: Establishing a Basic Connection

php
<?php
// mysqli_connect($host, $username, $password, $database) on a real server
$db = new SQLite3(':memory:');
echo "Connected and database selected";
?>

Connection Errors Check करना

mysqli_connect_error() यह describe करता है कि अगर सबसे हाल का connection attempt fail हुआ तो क्या गलत हुआ -- connect होने के तुरंत बाद इसे check करना आपको एक broken, unusable connection के साथ आगे बढ़ने के बजाय एक clear message के साथ fast fail करने देता है।

उदाहरण: Checking for Connection Errors

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

एक Database Connection बंद करना

mysqli_close($conn) (या OOP style में $conn->close()) ज़रूरत न रहने पर explicitly एक database connection बंद कर देता है, MySQL server पर resource free करते हुए -- हालाँकि script चलना खत्म होते ही PHP भी automatically कोई खुले connections बंद कर देता है।

उदाहरण: Closing a Database Connection

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
// Print "Connected" to the output
echo "Connected";
$db->close();
// Print " -- closed" to the output
echo " -- closed";
?>

Credentials को Securely Store करना

Database credentials को version control में committed किसी script में कभी directly hardcode नहीं किया जाना चाहिए -- उन्हें environment variables से, या .gitignore के through git से excluded एक अलग config file से load करना sensitive values को आपकी codebase की history से पूरी तरह बाहर रखता है।

उदाहरण: Storing Credentials Securely

php
<?php
// Declare `$host`, set to `getenv('DB_HOST') ?: 'localhost'`
$host = getenv('DB_HOST') ?: 'localhost';
// Declare `$password`, set to `getenv('DB_PASSWORD') ?: ''`
$password = getenv('DB_PASSWORD') ?: '';
// Print "Using credentials from environment, not hardcoded in the script" to the output
echo "Using credentials from environment, not hardcoded in the script";
?>

एक Custom Port या Options के साथ Connect करना

mysqli_connect() basic चार के अलावा optional port और socket parameters accept करता है, तब उपयोगी जब MySQL default port 3306 पर न चल रहा हो, जैसे कुछ Docker या shared-hosting setups में जहाँ एक non-standard port चाहिए।

उदाहरण: Connecting with a Custom Port or Options

php
<?php
// mysqli_connect($host, $user, $pass, $db, 3307) -- custom port example
echo "A non-default port can be passed as an extra argument";
?>
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. version control में committed किसी script में सीधे database credentials hardcode करना, बजाय उन्हें एक environment variable या repository से बाहर रखी एक config file से load करने के।
  2. इसके against queries चलाने से पहले यह check करना भूल जाना कि connection actually succeed हुआ, हर बाद की database call पर errors की एक confusing cascade की ओर ले जाते हुए।
  3. एक database connection को पूरी एक long-running script की अवधि तक खुला छोड़ना जब इसकी ज़रूरत सिर्फ शुरुआत में थोड़ी देर के लिए हो।
चैप्टर सारांश
  • mysqli_connect($host, $user, $password, $database) एक connection खोलता है और एक connection object return करता है, या failure पर false।
  • किसी भी queries चलाने से पहले, connection को attempt करने के तुरंत बाद हमेशा errors check करें।
  • Database credentials को main codebase के बाहर store किया जाना चाहिए (environment variables या एक gitignored config file), committed source में कभी hardcoded नहीं।

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.