PHP MySQL connecting script and function

Recommended MySQLi connection for current PHP

Enable strict MySQLi error reporting, create the connection, and set utf8mb4 so the connection handles the full Unicode range.

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$connection = new mysqli('localhost', 'db_user', 'db_password', 'database_name');
$connection->set_charset('utf8mb4');

// Use $connection for queries and prepared statements.
?>
Legacy section below: mysql_connect(), mysql_select_db() and mysql_error() belong to the removed PHP MySQL extension. Use MySQLi or PDO in maintained code.
Here is the PHP function to connect to MySQL server.
$link=mysql_connect("$servername","$dbuser","$dbpassword");
Here the variables $servername is equal to the name of the MySQL server host or ip address ( 'localhost' or '127.0.0.1'),

$dbuser stores the user id  and $dbpassword is the password assign to the user id to access the mysql_server.  If successful then it will return TRUE and we can check the variable $link to check the status of the command.
if(!$link){die("Could not connect to MySQL");}
The above command will display the error message if connection is not established.  Now once the MySQL connection established then we can select the database by using the command mysql_select_db. Here is the command.
mysql_select_db("$dbname",$link) or die ("could not open

db".mysql_error());
The above command will connect to database name stored in the variable $dbname. In case of any error the above line will print out it. Here is the total script below to connect from PHP to MySQL database using a function. At the top of the code we are assigning all values requried to connect to MySQL server.
<?Php

// hostname or ip of server
$servername='localhost';

// username and password to log onto db server
$dbusername='';
$dbpassword='';

// name of database
$dbname='mydb_name';

////////////// Do not  edit below/////////

connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect
("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open
db".mysql_error());
}?>
PHP MySQL Connection using PDO mysqli_connect(): Connection string for MYSQLI check mysql support in php by using phpinfo


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer