search
HomeSystem TutorialMACHow to connect PHP script to MySQL database

How to connect PHP script to MySQL database

In online form development, connecting PHP code with MySQL database is a common operation. User form data needs to be collected and added to the database. This article introduces two commonly used PHP and MySQL database connection methods.

PHP and MySQL database connection

To connect MySQL database to PHP, you need to install MySQL, database management tools and PHP on your computer. The two most commonly used connection methods are MySQLi and PDO.

First, we introduce the easier MySQLi to use.

First create a MySQL database, here we use TablePlus. TablePlus is a convenient database management tool that handles a variety of databases in a single interface. With its user-friendly interface, it takes only a few steps to create a database and add information. Open the application, click the database icon, and then click "New...", enter the database name and click "OK".

How to connect PHP script to MySQL database

Create a MySQL connection

Next, use mysqli_connect to connect to the database. You need a MySQL database password. To manage credentials safely and conveniently, we use Secrets to store credentials.

How to connect PHP script to MySQL database

Now we can connect to the MySQL database to PHP.

Open your commonly used PHP development tool and create a file named index.php. We use CodeRunner to write and edit code.

How to connect PHP script to MySQL database

Here is the code for extending the connection using MySQLi:

 <?php $conn = mysqli_connect(
    "<database location>",
    "<mysql> ",
    "<mysql> ",
    "Connect"
);
if (!$conn) {
    echo 'Connection Error:' . mysqli_connect_error();
}
?></mysql></mysql>

Click the Run button at the top of CodeRunner to run the code and view the results. If there is no error, the PHP script successfully establishes the MySQL database connection.

Before running the code, make sure the system has PHP installed. If not, enter "brew install php" in the terminal.

After establishing a connection, you can perform operations on the database.

Query the database, just connect to the database as before and request the required information:

 <?php $conn = mysqli_connect(
    "<database location>",
    "<mysql> ",
    "<mysql> ",
    "Connect"
);
if (!$conn) {
    echo 'Connection Error:' . mysqli_connect_error();
}
$sql = 'SELECT id FROM connect_table';
$result = mysqli_query($conn, $sql);
$connect = mysqli_fetch_all($result, MYSQLI_ASSOC);
print_r($connect);
?></mysql></mysql>

We use the SELECT statement to find the data for the desired column.

How to insert a record

Next, demonstrate a PHP to MySQL connection example that inserts information into the database.

Using INSERT INTO… VALUES syntax:

How to connect PHP script to MySQL database

The code snippet is as follows:

 <?php $conn = mysqli_connect(
    "<database location>",
    "<mysql> ",
    "<mysql> ",
    "Connect"
);
if (!$conn) {
    echo 'Connection Error:' . mysqli_connect_error();
}
$sql = 'INSERT INTO connect_table VALUES (5)';
if ($conn->query($sql) === TRUE) {
    echo "Record added!";
} else {
    echo "Error:" . $sql . "<br> " . $conn->error;
}
$conn->close();
?></mysql></mysql>

Add your own values ​​and run the code.

You can save the above code snippet for later use. We use the SnippetsLab application to save code snippets. It helps organize code snippets and avoids losing code examples.

How to connect PHP script to MySQL database

How to update records in database from PHP script

To use mysqli to connect to PHP to update records in a MySQL database, you need to use the UPDATE … SET … WHERE syntax.

Specify the columns and rows to update and the value, and then run the code:

How to connect PHP script to MySQL database

The code we use is as follows:

 <?php $conn = mysqli_connect(
    "<database location>",
    "<mysql> ",
    "<mysql> ",
    "Connect"
);
if (!$conn) {
    echo 'Connection Error:' . mysqli_connect_error();
}
$sql = 'UPDATE connect_table SET id = 66';
if ($conn->query($sql) === TRUE) {
    echo "Record updated!";
} else {
    echo "Error:" . $sql . "<br> " . $conn->error;
}
$conn->close();
?></mysql></mysql>

How to delete a query from a PHP script

Next, see how to quickly delete unwanted entries in the database.

The deletion syntax in MySQLi is DELETE FROM … WHERE …, let's try it in the code.

For example, if you want to remove the value 54 from the connect_table of the Connect MySQL database, you can use the following code:

How to connect PHP script to MySQL database

The output "value has been deleted!" means that the operation is successful. We can recheck it in the TablePlus database view:

How to connect PHP script to MySQL database

As you can see, the value 54 has been deleted from the id column.

Connect using PDO

Another common way to connect a PHP project to MySQL is PDO (PHP data object). This approach is more general because it can be used with multiple SQL databases, not just MySQL, which is different from MySQLi.

You can use the following code to establish a PDO MySQL connection:

How to connect PHP script to MySQL database

The code we use is as follows:

 <?php $servername = "localhost";
$username = "<your database username>";
$password = "<your database password>";
try {
    $conn = new PDO("mysql:host=$servername;dbname=<your database name>", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connect to the server successfully!";
} catch (PDOException $e) {
    echo $e->getMessage();
}
?></your></your>

Once connected to the database, you can add PDO operations to your code, such as inserting, deleting, selecting, or updating.

Create a simple PHP form and submit your values ​​through it to test it.

in conclusion

Now you have learned about the two most popular methods of PHP and MySQL connections – MySQLi and PDO connecting to SQL databases.

PHP-MySQL Connection is a versatile tool that helps you retrieve data from a database, update the database, and collect user data and add it to the database.

If you are just starting to connect PHP to MySQL, it is recommended to try MySQLi. Once you're more familiar with the process, you can add PDO as it can be used with other databases, not just MySQL.

When writing code, you can use the CodeRunner code editor to write and execute code, use SnippetsLab to save code snippetsLab for later use, and use TablePlus to manage the database. As for the database's login credentials, it can be securely stored in Secrets, an application for storing passwords, credit cards, and bank account information.

Another tool you can try to help you use PHP is Whisk, which previews your pages in real time – it allows you to create and adjust in real time. So if you need to create a PHP form for your project, you can use this application to complete the task.

All of these applications are available through Setapp subscription. Setapp is a productivity tool service for Mac and iOS, dedicated to clearing daily tasks from your schedule and making room for new and exciting efforts. You can experience these and more daily task tools with a free 7-day trial.

The above is the detailed content of How to connect PHP script to MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to partition hard drives on Mac | A complete guideHow to partition hard drives on Mac | A complete guideApr 15, 2025 am 11:20 AM

This guide helps you master Mac hard drive partitioning, whether for better file organization or dual-booting operating systems. Fear not data loss; we'll cover backups! Why Partition? Organizing files, installing Windows, or simply improving data

Best Cloud Storage for Mac: Which Online Storage Choose for Your MacBook?Best Cloud Storage for Mac: Which Online Storage Choose for Your MacBook?Apr 15, 2025 am 11:12 AM

Must-have cloud storage for Mac computers: space expansion and cross-device access Cloud storage services not only effectively free up space in Mac hard drives, but more importantly, it allows you to access files on almost any connected device. For example, you can create a file on your Mac and then access it on your iPhone. Recommended best cloud storage for Mac computers There are a wide range of cloud storage services on the market. Here are some of the ones we recommend: iCloud Google Drive Microsoft OneDrive Sync.com Dropbox Icedrive MEGA 1. iCloud For many Apple users, iCloud is a natural first choice. All modern

MacBook Microphone Not Working: How to Fix it on Mac Air/Pro?MacBook Microphone Not Working: How to Fix it on Mac Air/Pro?Apr 15, 2025 am 11:06 AM

Troubleshooting Your MacBook's Uncooperative Microphone: A Step-by-Step Guide Experiencing audio issues with your MacBook's microphone? Whether it's failing during a QuickTime recording, a FaceTime call, or a crucial Zoom meeting, this guide provide

An Error Occurred While Preparing the Installation: What Is It & How to Fix?An Error Occurred While Preparing the Installation: What Is It & How to Fix?Apr 15, 2025 am 11:02 AM

During the macOS installation process, you will sometimes encounter the prompt of "an error occurred while preparing for installation", which will cause installation delays. This article will introduce a variety of solutions. "An error occurred while preparing for installation" means that macOS update failed, which could be caused by unstable network connections, incorrect date and time settings, or Apple server issues. Causes that cause this error can include: date and time mismatch (especially if Apple is not selected as the date and time source), installation media corruption, or Mac hardware issues (e.g., the disk you choose to install macOS is empty). Here is a solution to this error: Check device compatibility: Make sure your Mac model is compatible with the version of macOS to be installed. Apple supports website columns

How to access your Mac remotely: Complete tutorialHow to access your Mac remotely: Complete tutorialApr 15, 2025 am 10:58 AM

Remotely Access Your Mac: A Comprehensive Guide Working remotely is now the standard, making remote Mac access more crucial than ever. Apple simplifies this process, and with helpful third-party apps, it's surprisingly easy. This guide covers vario

What is FileVault disk encryption and how to use itWhat is FileVault disk encryption and how to use itApr 15, 2025 am 10:56 AM

FileVault: Your Mac's Data Fortress – A Comprehensive Guide FileVault, as its name suggests, is macOS's built-in data vault, providing robust encryption for your entire startup disk. In today's digital landscape, data security is paramount, especia

How to fix 504 gateway timeout errors on MacHow to fix 504 gateway timeout errors on MacApr 15, 2025 am 10:42 AM

When visiting the website, all kinds of mysterious mistakes emerge one after another. The most famous one is the 404 error - the error encountered when accessing a web page that does not exist. The common error that ranks second is the 504 error gateway timeout. There are many other error codes in addition. When encountering such errors when loading a website, it is very frustrating for both visitors and brands. Visitors are unable to get the information they need, and brands reduce exposure and alienate their audience. The good news is that the 504 error is controllable to a certain extent. You can maintain your reputation by taking some precautions and learning how to quickly fix 504 gateway timeout issues. But first, let's clarify what exactly does the 504 error gateway timeout mean and why. What is 504 gateway timeout? Every visit

How to increase upload speedHow to increase upload speedApr 15, 2025 am 10:41 AM

This article explains how to improve upload speeds to enhance video conferencing, streaming, and overall online experience. Unlike download speeds, upload speeds are often overlooked, yet significantly impact network quality. Let's explore how to bo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.