php-and-mysql tutorials
Step-by-Step
PHP and MySQL Tutorials
Enhance your expertise as a website back-end developer with these PHP and MySQL tutorials. Explore the latest server-side development libraries to boost your skills in creating dynamic website elements. Stay ahead in the field and become a more proficient website coder with these in-depth tutorials.
PHP and MySQL Tutorials:
How to Connect to MySQL Database with Advanced Queries Using PHP Language Efficiently?
reading time
Reading Time:
00:08 Minutes
implement time
Implement Time:
00:25 Minutes

Introduction to PHP MySQL Database Connection

PHP is one of the most widely used languages for web development, and MySQL is a powerful open-source relational database management system (RDBMS). Establishing a secure and optimized connection between PHP and MySQL is crucial for developing dynamic and database-driven applications.

In this tutorial, we will cover:

  • Establishing a secure PHP-MySQL database connection
  • Writing advanced MySQL queries with PHP
  • Best practices to improve security and performance

Let’s dive into setting up a proper database connection before moving on to complex queries.

Step 1: Connecting to MySQL Database in PHP

To interact with a MySQL database using PHP, the recommended approach is using MySQLi (MySQL Improved Extension) or PDO (PHP Data Objects).

PHP Code to Connect MySQL Using MySQLi (Object-Oriented Method)
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test_db";

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";
?>
PHP Code to Connect MySQL Using PDO (Recommended for Security & Flexibility)
PHP
<?php
$dsn = "mysql:host=localhost;dbname=test_db;charset=utf8mb4";
$username = "root";
$password = "";

try {
	$conn = new PDO($dsn, $username, $password, [
		PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
		PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
	]);
	echo "Connected successfully";
} catch (PDOException $e) {
	die("Connection failed: " . $e->getMessage());
}
?>
Why use PDO?
  • Supports multiple database types (MySQL, PostgreSQL, SQLite, etc.)
  • Better error handling with exceptions
  • More secure (Prevents SQL injection)

Step 2: Advanced MySQL Queries with PHP

Now that we have successfully connected to the database, let’s explore 5 advanced MySQL queries that can help you retrieve and manipulate data efficiently.

1. Case-Sensitive and Case-Insensitive Searches in MySQL

By default, MySQL searches are case-insensitive because it uses the utf8_general_ci collation. However, you can perform a case-sensitive search by changing the collation or using the BINARY keyword.

Case-Insensitive Search (Default Behavior)
PHP
$sql = "SELECT * FROM users WHERE username = 'john_doe'";
$result = $conn->query($sql);

This will return both "John_Doe" and "john_doe".

Case-Sensitive Search Using BINARY
PHP
$sql = "SELECT * FROM users WHERE BINARY username = 'John_Doe'";
$result = $conn->query($sql);

This will only return records where the username is exactly "John_Doe" (case-sensitive).

2. Sorting Data Using ASC and DESC with LIMIT

Sorting data in ascending (ASC) or descending (DESC) order is useful for paginations and ranking systems.

Example: Fetch Top 5 Newest Users
PHP
$sql = "SELECT * FROM users ORDER BY created_at DESC LIMIT 5";
$result = $conn->query($sql);

Fetches the latest 5 users from the database.

Example: Fetch 3 Oldest Users
PHP
$sql = "SELECT * FROM users ORDER BY created_at ASC LIMIT 3";
$result = $conn->query($sql);

Fetches the oldest 3 users based on the created_at field.

3. Using LIKE Operator to Find Partial Matches

The LIKE operator is useful for searching specific patterns within a column.

Find Users Whose Name Starts With "Jo"
PHP
$sql = "SELECT * FROM users WHERE name LIKE 'Jo%'";
$result = $conn->query($sql);

Matches "John", "Joseph", "Jonah", etc.

Find Users Whose Name Ends With "son"
PHP
$sql = "SELECT * FROM users WHERE name LIKE '%son'";
$result = $conn->query($sql);

Matches "Jackson", "Emerson", "Davidson", etc.

Find Users With "mi" in the Middle
PHP
$sql = "SELECT * FROM users WHERE name LIKE '%mi%'";
$result = $conn->query($sql);

Matches "Emily", "Amir", "Tomis", etc.

4. Extract Values from Comma-Separated Strings in MySQL

A common problem is storing multiple values in a comma-separated format inside a column and retrieving them efficiently.

Find Users Having "PHP" in Their Skills List
PHP
$sql = "SELECT * FROM users WHERE FIND_IN_SET('PHP', skills)";
$result = $conn->query($sql);

If skills column contains values like "PHP,JavaScript,HTML", it will return users with PHP as one of their skills.

5. Selecting String Values as Integers

Sometimes, string values represent numeric data, and you may need to treat them as integers in queries.

Example: Sort a Column Containing Numeric Strings as Integers
PHP
$sql = "SELECT * FROM products ORDER BY CAST(price AS UNSIGNED) DESC";
$result = $conn->query($sql);

Ensures proper sorting of prices stored as strings (e.g., "100", "50", "200").

Step 3: Security & Performance Optimization Tips

To ensure a secure and high-performance PHP-MySQL application, follow these best practices:

Use Prepared Statements (Prevent SQL Injection)
PHP
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute(['user@example.com']);
$result = $stmt->fetchAll();
Validate & Sanitize User Input
PHP
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Use Indexing for Faster Query Execution

Index commonly searched columns to improve performance.

PHP
CREATE INDEX idx_email ON users(email);
Close Database Connection When Done
PHP
$conn->close();

Using close() ensures proper resource management and prevents memory leaks in long-running PHP scripts.

In PDO, the connection is automatically closed when the script ends. However, you can manually unset it:

PHP
$conn = null;

Final Thoughts: Master PHP-MySQL Like a Pro!

Building a robust PHP-MySQL application requires mastering database connections, writing optimized queries, and implementing security measures. By leveraging advanced queries like case-sensitive searches, sorting with limits, pattern matching, handling comma-separated values, and casting string values as integers, you can build high-performance web applications.

Now it’s your turn! Experiment with these queries in your PHP projects and optimize them further for better performance. Happy coding!

More Tutorials

Layer styles are the secret weapon of many professional designers, offering a quick and effective way to add depth, texture, and dimension to your artwork. Whether you’re

User interaction pseudo-classes in CSS allow developers to apply styles dynamically based on how users interact with elements. They enable changes when a user hovers, clicks,

Image zoom effects are widely used in modern web development to enhance user experience. They provide a detailed view of images without requiring users to open a separate

Photoshop’s “Select and Mask” tool is an incredibly powerful feature that allows users to achieve professional-level background removal. Whether you’re editing

Learn how to master the Rotate Tool in Adobe Illustrator to create stunning designs with ease. This detailed guide will cover the process of duplicating, transforming, and

The Pen Tool in Adobe Illustrator is one of the most powerful tools for creating custom shapes and paths. Mastering it can significantly enhance your design skills, allowing

In modern web design, CSS pseudo-classes play a vital role in enhancing the user experience by applying styles based on the position, interaction, or relationship of elements

Adobe Illustrator is a powerful vector graphics editor that offers a wide range of tools and features to help designers create precise and visually appealing artwork. In this

Development Tools
css beautifier tool

Our online CSS beautifier & minifier is the professional choice for clean code. It offers customizable options for formatting, beautification, and minification. Enhance your CSS for optimal results now!

html beautifier tool

Our online HTML beautifier is the professional choice for cleaning up code. Compress & format HTML for improved structure and readability, with just a few clicks. Start beautifying today!

css gradient generator tool

Design unique CSS gradients with our easy to use, professional generator. Choose colors and customize with advanced features. Lightweight for fast and optimized output!

sort words tool

Use our powerful sort words tool to arrange text by alphabetical order or character length. Many options available to format the output as desired. Clean up your lists now, quickly and easily!

encoder decoder tool

Professional-grade text encoding and decoding is here with our advanced tool. Sophisticated features and capabilities for all your complex data transformation needs. Start now!

css filter generator tool

Our lightweight CSS filter generator lets you create CSS filters using hex values with multiple advanced options. Get the perfect look for your elements with this powerful & efficient tool!

email extractor tool

Extract email IDs from messy text with a single click using our professional tool. Lightweight & efficient, streamlines the process for you, saving time. Try now for effortless email extraction!

lorem ipsum generator tool

Our online Lorem Ipsum generator provides the best solution for your demo content needs. It offers many options, allowing you to create perfect placeholder text with precision. Get started now!

Our Services
website development service

Our Website Development Service offers custom, responsive design, ensuring seamless user experience across devices. From concept to launch, we create dynamic, SEO-friendly sites to elevate your online presence and drive engagement.

website redesign service

Revamp your online presence with our Website Redesign Service! We specialize in creating modern, user-friendly designs that boost engagement and conversion rates. Transform your site today for a sleek, professional look that stands out.

psd to html5 service

Transform your PSD designs into pixel-perfect, responsive HTML5 code with our professional PSD to HTML5 conversion service. Enjoy clean, SEO-friendly, and cross-browser compatible code tailored to bring your vision to life seamlessly.

logo design service

Elevate your brand with our professional Logo Design Service. We create unique, memorable logos that capture your business's essence. Stand out in the market with a custom logo designed to leave a lasting impression.

seo search engine optimization service

Boost your site's search engine presence! We offer expert SEO solutions, including image and code enhancements, to achieve top positions on Google, Bing, and Yahoo. Let us drive qualified traffic to your business today!

social media marketing service

Boost your brand with our Social Media Marketing Service! We specialize in crafting engaging content, driving growth through targeted ads, and maximizing your online presence. Drive growth and connect with your audience effectively.

wordpress development service

Experience our WordPress development services, offering tailored solutions for custom themes, plugins, and seamless integrations. Enhance your online presence with our responsive, secure, and success-optimized WordPress solutions.

image enhancement service

Enhance your website's visual appeal: We sharpen icons/images, correct RAW files & repair damaged/distorted/overly bright photos. Expect natural-colored, high-resolution JPEGs, complete with photographic effects & upscaling.

Blog Post

Introduction In today's digital age, having a well-optimized website is crucial for businesses and individuals alike. A website that loads quickly, is easy to navigate, and provides a seamless user experience can greatly...

Introduction Graphic design is a dynamic and creative field that requires the right tools to bring your visions to life. While there are many high-end paid software options available, not everyone can afford...

HTML5 Semantic Elements have become an important factor in improving SEO rankings due to their ability to provide search engines with more meaningful information about the content of a webpage. These elements go...

JavaScript extended libraries offer a wide range of capabilities for creating interactive and dynamic elements on websites. With these libraries, you can easily incorporate features such as drop-down menus, popups, modals, banner sliders,...

Colors are an incredibly important factor in website design, because they can have a significant effect on user experience and engagement. Colors create visual stimulation, which can influence how users process information. Using...

If you want your website and graphic designs to capture attention, incorporating exceptional fonts is a must! Incorporating elegant typefaces has the capacity to bring your design up a notch, making it more...

In the ever-evolving landscape of digital marketing, Search Engine Optimization (SEO) remains an important strategy for increasing organic traffic and increasing a website's online visibility. However, as search engines continually refine their algorithms...

Adobe Photoshop is a prominent software in image editing and retouching, offers a variety of functionalities. However, it might not be the ideal choice for all users due to several drawbacks. Its interface,...