Skip to content

mysqli_connect: Connect PHP to MySQL in 7 Steps

mysqli_connect: Connect PHP to MySQL in 7 Steps

Let's start with PHP and MySQL. The first thing to do is connect to the database MySQL, and try to get information on database tables on the page. The function to connect to MySQL is called mysqli_connect ().

To connect PHP to MySQL and work with returned data, treat the process as a sequence: establish a connection, execute a query, verify what came back, then render the rows safely. A connection alone does not prove that a later query succeeded, and a query that returns no records is not necessarily an error. Keeping those cases separate makes database-backed pages easier to debug.

Start with a checked MySQLi connection

Keep connection settings outside the page

Use the host, account name, password, and database name provided for the environment. Store real credentials outside public source files, and use an account with only the privileges the application requires. Sample strings such as a made-up username are placeholders, not connection details to copy into production.

After creating the connection, check the returned handle before attempting a query. If it failed, stop the work that depends on the database and use a controlled error path. Development logs can contain useful diagnostics; public responses should not reveal credentials, server details, or raw database errors.

Set the connection character set

Configure the connection's character set explicitly so PHP and MySQL handle text consistently. Use the character set expected by the application and database, and keep output escaping in place when rendering text into HTML. Character encoding and HTML escaping solve different problems: one makes text interpretation consistent, while the other prevents data from being treated as markup.

This function returns a connection to pop for the database MySQL connection, that's called a database handling.

There are few important MySQL functions for the PHP MySQL commands:

  • 1. mysqli_connect
  • 2. mysqli_query
  • 3. mysqli_num_rows
  • 4. mysqli_fetch_array
  • 5. mysqli_close

Now Let's start with first function of PHP for creating a connection:

mysqli_connect :

<?php
$username = "yourName";
$password = "yourPassword";
$database = "databaseName";
$hostname = "localhost"; 
//connection to the database
$dbcon = mysqli_connect($hostname, $username, $password, $database) or die("Unable to connect to MySQL");
echo "Connected to MySQL Database";
?>

After connection successfully created need to hit a query where data is stored with table:

Run the query and verify its result

Use the right query for the task

A SELECT statement retrieves data; INSERT, UPDATE, and DELETE statements change data. For a demonstration that reads a table, select only the columns the page needs instead of relying on a wildcard. Explicit column names make it clear what the page expects and reduce accidental changes if the table later gains another field.

For values that come from a form, URL, or other external input, use a prepared statement and bind the values. Do not assemble a SQL statement by concatenating untrusted text. Placeholders protect data values; they do not stand in for table names, column names, or sort directions. If a user can choose a sort field, map that choice to a short allow-list of known SQL identifiers.

Programmer working through a database query on a laptop
A developer works through application code for a database-backed page. · Photo: Christina Morillo / Openverse (CC0)

Store and check the returned value

Assign the result of the query to a clearly named variable, then check it before passing it to a row-count or fetch function. A common bug in older examples is to execute a query without assigning its return value and later try to read an unrelated or undefined result variable. Keep the connection, statement, and result variables distinct so you can see which operation each value represents.

Handle a failed query separately from a successful query with zero rows. The former needs an error path; the latter is an ordinary outcome that the page can describe or use to show an empty state. Never display a success message or start a fetch loop until the query outcome supports it.

Count rows and fetch data deliberately

Choose a row-fetching method

For many pages, mysqli_fetch_assoc is a readable option because each fetched row is an associative array keyed by the selected column names. A while loop can continue until no more row is returned. If code uses mysqli_fetch_array, be aware that it can return both numeric and associative keys unless a specific mode is requested; choose the format intentionally rather than relying on accidental duplicate values.

PHP MySQLi query workflow from connection to safe output
PHP Query to Safe Results

Row counting is useful when the result is buffered and the application needs a count, but it is not always necessary just to know whether a row exists. If the page will fetch every row anyway, process the loop and track what you need. For very large results, avoid loading or counting more data than the page actually needs; add appropriate limits or pagination.

Make empty results useful

An empty result should be handled in the user interface, not treated as a database crash. A search page can say that no matching records were found; a report can display its headings and a clear empty state. Test this case deliberately, since it often exposes code that assumes a first row always exists.

Also consider the result cursor: fetching a row advances it. If a routine has already consumed the rows, a later loop will not automatically start from the beginning. Arrange the order of operations so the result is read once, or obtain another result when a separate pass is genuinely required.

Render results without exposing the application

Escape database values for HTML

Data retrieved from the database may contain text entered by users or imported from another system. Escape values for the HTML context before inserting them into a page; use the appropriate escaping function and character encoding. Do the same for generated headings if they can be influenced by aliases or other dynamic content.

SQL parameter binding and HTML escaping are complementary safeguards. Prepared statements protect the query when external values are used as data; HTML escaping protects the output when retrieved values are displayed. Neither one replaces access control, validation, or careful handling of errors.

Use predictable cleanup

Close statements and release result resources when they are no longer needed, particularly in jobs that handle many queries or run for a long time. A normal request usually releases its non-persistent connection when the script ends, but explicit cleanup can make the intended lifecycle clear. Avoid helper functions that depend on a connection variable hidden in another scope; pass the handle to a helper if one is used.

Debug common PHP and MySQLi problems

Trace the operation that failed

  • Confirm that the connection succeeded before running a query.
  • Check the SQL syntax and the actual table and column names.
  • Verify that the result variable receives the query return value.
  • Distinguish a query error from a valid result containing no rows.
  • Check that the database account can perform the requested operation.
  • Review protected logs rather than exposing raw errors to visitors.

When a query works in a database client but fails in the PHP application, compare the exact SQL, connection database, account permissions, and runtime environment. A typo or a different selected database can make the same table name refer to something unexpected. Logging the operation context without sensitive values can make diagnosis faster.

Test the full flow

Test a normal result with several rows, an empty result, a query failure, and values containing characters such as apostrophes and angle brackets. Test the same data path that the application uses, including any bound input values. Then verify that the displayed page shows readable values without interpreting database content as HTML.

A dependable database page is not just a successful connection snippet. It clearly handles each stage, reports failures safely, and gives users a sensible outcome when there is nothing to show. Once those habits are in place, the same pattern can be reused across reports and other database-backed pages.

For reusable connection configuration, see the PHP MySQLi connection setup guide. For a dynamic table driven by result-column metadata, read the article on getting column names with MySQLi.

Top 50 MySQL Interview Questions and Answers

mysqli_query :

<?php
$query = "SELECT * FROM table_name";
mysqli_query($dbcon, $query) or die('Error in querying database');
?>

When the query is executed we need to how mutch data received on page :

mysqli_num_rows :

<?php
if($row = mysqli_num_rows($result_query)) {
 echo 'Total '. $row . ' record found.';
}
else{
 echo 'No record found';
}
?>

Now we just need to go through all the rows of that query which we need mysqli_fetch_array which stores the rows in an array, we can get the data of this array usning while loop :

mysqli_fetch_array :

<?php
while ($row_data = mysqli_fetch_array($result_query)) {
 echo $row_data['firstName'] . ' ' . $row_data['lastName'] . ': ' . $row_data['emailId'] .'<br />';
}
?>

Finally we need to close the database connection using mysqli_close :

mysqli_colse :

<?php
mysqli_close($dbcon);
?>

Result

<?php
$username = "yourName";
$password = "yourPassword";
$database = "databaseName";
$hostname = "localhost"; 
//connection to the database
$dbcon = mysqli_connect($hostname, $username, $password, $database) or die("Unable to connect to MySQL");
echo "Connected to MySQL Database";
$query = "SELECT * FROM table_name";
mysqli_query($dbcon, $query) or die('Error in querying database');
if($row = mysqli_num_rows($result_query)) {
 echo 'Total '. $row . ' record found.';
 while ($row_data = mysqli_fetch_array($result_query)) {
  echo $row_data['firstName'] . ' ' . $row_data['lastName'] . ': ' . $row_data['emailId'] .'<br />';
 }
}
else{
 echo 'No record found';
}
mysqli_close($dbcon);
?>

Write a comment