Table of Contents
How to insert a record
How to update records in database from PHP script
How to delete a query from a PHP script
in conclusion
Home System Tutorial MAC How to connect PHP script to MySQL database

How to connect PHP script to MySQL database

Apr 11, 2025 am 09:46 AM

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Spotify on Apple Watch: How to use it in 2025 Spotify on Apple Watch: How to use it in 2025 Apr 04, 2025 am 09:55 AM

With the support of Apple devices' interconnected ecosystem, managing and synchronizing your Apple devices has become a breeze. Unlock Mac with Apple Watch? Simple! (If you haven't set this unlocking method yet, you should really try it, it's very time-saving). Can you pay with Apple Watch without using iPhone? Apple can handle it easily! Today we will focus on how to download the Spotify playlist to an Apple Watch and play without an iPhone. Spoiler: This is possible. How to use Spotify on Apple Watch: A quick overview Let's dive into the key issues and their solutions directly. If this form helps you, that would be great! If you

Fix your Mac running slow after update to Sequoia Fix your Mac running slow after update to Sequoia Apr 14, 2025 am 09:30 AM

After upgrading to the latest macOS, does the Mac run slower? Don't worry, you are not alone! This article will share my experience in solving slow Mac running problems after upgrading to macOS Sequoia. After the upgrade, I can’t wait to experience new features such as recording and transcription of voice notes and improved trail map planning capabilities. But after installation, my Mac started running slowly. Causes and solutions for slow Mac running after macOS update Here is my summary of my experience, I hope it can help you solve the problem of slow Mac running after macOS Sequoia update: Cause of the problem Solution Performance issues Using Novabe

How to get rid of 'Your screen is being observed' error How to get rid of 'Your screen is being observed' error Apr 05, 2025 am 10:19 AM

When you see the message "Your screen is being monitored", the first thing you think of is someone hacking into your computer. But that's not always the case. Let's try to find out if there are any issues that need you to worry about. Protect your Mac With Setapp, you don't need to worry about choosing a tool to protect your computer. You can quickly form your own suite of privacy and security software on Setapp. Free Trial Security Test What does "Your screen is being monitored" mean? There are many reasons why there is a Mac lock screen message that appears with “Your screen is being monitored”. You are sharing the screen with others You are recording the screen You are using AirPlay You are using some apps that try to access your screen Your computer is infected with evil

How to reduce WindowServer Mac CPU usage How to reduce WindowServer Mac CPU usage Apr 16, 2025 pm 12:07 PM

macOS WindowServer: Understanding High CPU Usage and Solutions Have you noticed WindowServer consuming significant CPU resources on your Mac? This process is crucial for your Mac's graphical interface, rendering everything you see on screen. High C

How to uninstall Honey from Mac How to uninstall Honey from Mac Apr 04, 2025 am 10:13 AM

How to make a video into a live photo on Mac and iPhone: Detailed steps How to make a video into a live photo on Mac and iPhone: Detailed steps Apr 11, 2025 am 10:59 AM

This guide explains how to convert between Live Photos, videos, and GIFs on iPhones and Macs. Modern iPhones excel at image processing, but managing different media formats can be tricky. This tutorial provides solutions for various conversions, al

Here's how to view, edit, and remove Exif metadata from photos Here's how to view, edit, and remove Exif metadata from photos Apr 04, 2025 am 10:22 AM

Understanding and Managing Exif Metadata on Your Mac Every photo you take contains more than just the image itself. Embedded within the file is Exif metadata, holding details like date, time, camera settings, GPS location, and copyright information.

Email is not syncing? How to refresh the Mail app on Mac Email is not syncing? How to refresh the Mail app on Mac Apr 04, 2025 am 09:45 AM

Mac mail synchronization failed? Quick solution! Many Mac users rely on the included Mail app because it is simple and convenient. But even reliable software can have problems. One of the most common problems is that Mail cannot be synced, resulting in recent emails not being displayed. This article will guide you through email synchronization issues and provide some practical tips to prevent such issues. How to refresh the Mail app on your Mac Operation steps Click the envelope icon Open the Mail app > View > Show Tab Bar > Click the Envelope icon to refresh. Use shortcut keys or menu options Press Shift Command N. Or open the Mail app

See all articles