Example 1 — Set a Connect Timeout
Init, set timeout, then real_connect. Sample reports success.
<?php
$mysqli = mysqli_init();
mysqli_options($mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$ok = mysqli_real_connect(
$mysqli,
"localhost",
"demo_user",
"demo_pass",
"app_db"
);
echo $ok ? "Connected with timeout option." : "Failed.", PHP_EOL;
mysqli_close($mysqli); How It Works
- mysqli_init() creates the empty handle.
- mysqli_options() sets MYSQLI_OPT_CONNECT_TIMEOUT to 5 seconds.
- mysqli_real_connect() opens the server using that setting.
- Close when finished.

