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:

1

2

3

4

5

6

7

8

9

10

<?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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?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:

1

2

3

4

5

6

7

8

9

10

11

<?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
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
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 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

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 type hashtag on Mac How to type hashtag on Mac Apr 13, 2025 am 09:43 AM

You can’t really use the internet nowadays without encountering the hashtag symbol that looks like this — #. Popularized on a global scale by Twitter as a way to define common tweet themes and later adopted by Instagram and other apps to c

Mac Disk Utility: How to Repair Disk with First Aid? How to Recover It? Mac Disk Utility: How to Repair Disk with First Aid? How to Recover It? Apr 13, 2025 am 11:49 AM

You might need to repair your Mac disk if your computer won’t start up, apps keep freezing, you can’t open certain documents, or the performance has slowed to a halt. Luckily, Apple includes a handy tool you can use to

How to delete files on Mac How to delete files on Mac Apr 15, 2025 am 10:22 AM

Managing Mac storage: A comprehensive guide to deleting files Daily Mac usage involves installing apps, creating files, and downloading data. However, even high-end Macs have limited storage. This guide provides various methods for deleting unneces

Is Google Chrome Not Working on Mac? Why Are Websites Not Loading? Is Google Chrome Not Working on Mac? Why Are Websites Not Loading? Apr 12, 2025 am 11:36 AM

With a market share of over 65.7%, Google Chrome is the biggest web browser in the world. You can use it if you use other operating systems like Windows and Android, but many Mac users also prefer Chrome over Safari. Mo

How to connect bluetooth headphones to Mac? How to connect bluetooth headphones to Mac? Apr 12, 2025 pm 12:38 PM

From the dawn of time to just about a few years ago, all of us sported a pair of wired headphones and were convinced that this is simply how it will be done forever. After all, they are the easiest technology around: just plug them in, put them

See all articles