MySQL PHP Connection and Usage
MySQL is an open-source relational database management system (RDBMS) that uses Structured Query Language (SQL) to manage and manipulate data.
PHP is a popular server-side scripting language, especially suited for web development.
When MySQL and PHP are used together, you can create dynamic, data-driven websites.
PHP provides multiple ways to connect to and operate MySQL databases, using the mysqli extension (MySQL Improved) or PDO (PHP Data Objects).
If you want to learn about the use of MySQL in PHP, you can visit our Introduction to Using MySQL in PHP。
Connect to MySQL database
Using the mysqli extension
mysqli ("Improved MySQL") is the recommended way to connect to MySQL in PHP. Here is a basic connection example:
Example
connect_error ) { die ( "Connection failed: " . $conn -> connect_error ) ; } echo "Connection successful" ; ?>Using PDO (PHP Data Objects)
PDO provides a data access abstraction layer that can work on different database systems:
Example
setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION ) ; echo "Connection successful" ; } catch ( PDOException $e ) { echo "Connection failed: " . $e -> getMessage ( ) ; } ?>Executes an SQL query
Query data
Query data using mysqli:
Example
$sql
=
"SELECT id, name, email FROM users"
;
$result
=
$conn
->
query
(
$sql
)
;
if
(
$result
->
num_rows
0
)
{
// Output each row of data
while
(
$row
=
$result
->
fetch_assoc
(
)
)
{
echo
"id: "
.
$row
[
"id"
]
.
" - Name: "
.
$row
[
"name"
]
.
" - Email: "
.
$row
[
"email"
]
.
"
"
;
}
}
else
{
echo
"0 results"
;
}
Query data using PDO:
Example
$stmt
=
$conn
->
prepare
(
"SELECT id, name, email FROM users"
)
;
$stmt
->
execute
(
)
;
// Set the result set as an associative array
$result
=
$stmt
->
setFetchMode
(
PDO
::
FETCH_ASSOC
)
;
foreach
(
$stmt
->
fetchAll
(
)
as
$row
)
{
echo
"id: "
.
$row
[
"id"
]
.
" - Name: "
.
$row
[
"name"
]
.
" - Email: "
.
$row
[
"email"
]
.
"
"
;
}
Insert data
mysqli insert data example:
Example
$sql
=
"INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')"
;
if
(
$conn
->
query
(
$sql
)
===
TRUE
)
{
echo
"New record inserted successfully"
;
}
else
{
echo
"Error: "
.
$sql
.
"
"
.
$conn
->
error
;
}
PDO insert data example (a more secure way):
Example
$stmt
=
$conn
->
prepare
(
"INSERT INTO users (name, email) VALUES (:name, :email)"
)
;
$stmt
->
bindParam
(
':name'
,
$name
)
;
$stmt
->
bindParam
(
':email'
,
)
;
// Insert a row
$name
=
"John Doe"
;
=
"john@example.com"
;
$stmt
->
execute
(
)
;
Security considerations
Preventing SQL Injection
SQL injection is a common security threat. To prevent SQL injection, you should:
- Use prepared statements (like the PDO example above)
- Validate and filter user input
- Do not directly concatenate user input into SQL queries
Other security practices
- Use the principle of least privilege: database users should only have necessary permissions
- Encrypt sensitive data
- Back up the database regularly
- Disable error display in production
Closing the Database Connection
After completing database operations, you should close the connection to release resources:
mysqli close connection:
Example
$conn
->
close
(
)
;
PDO close connection:
Example
$conn
=
null
;
Practical Application Examples
User registration system
Example
// Connect to the database
$conn
=
new
mysqli
(
"localhost"
,
"username"
,
"password"
,
"user_db"
)
;
// Check the connection
if
(
$conn
->
connect_error
)
{
die
(
"Connection failed: "
.
$conn
->
connect_error
)
;
}
// Handle form submission
if
(
$_SERVER
[
"REQUEST_METHOD"
]
==
"POST"
)
{
$username
=
$_POST
[
'username'
]
;
=
$_POST
[
'email'
]
;
$password
=
password_hash
(
$_POST
[
'password'
]
,
PASSWORD_DEFAULT
)
;
// Hash the password
// Prepared statements prevent SQL injection
$stmt
=
$conn
->
prepare
(
"INSERT INTO users (username, email, password) VALUES (?, ?, ?)"
)
;
$stmt
->
bind_param
(
"sss"
,
$username
,
,
$password
)
;
if
(
$stmt
->
execute
(
)
)
{
echo
"Registration successful!"
;
}
else
{
echo
"Error: "
.
$stmt
->
error
;
}
$stmt
->
close
(
)
;
}
$conn
->
close
(
)
;
User Login
Example
session_start
(
)
;
$conn
=
new
mysqli
(
"localhost"
,
"username"
,
"password"
,
"user_db"
)
;
if
(
$conn
->
connect_error
)
{
die
(
"Connection failed: "
.
$conn
->
connect_error
)
;
}
if
(
$_SERVER
[
"REQUEST_METHOD"
]
==
"POST"
)
{
$username
=
$_POST
[
'username'
]
;
$password
=
$_POST
[
'password'
]
;
$stmt
=
$conn
->
prepare
(
"SELECT id, username, password FROM users WHERE username = ?"
)
;
$stmt
->
bind_param
(
"s"
,
$username
)
;
$stmt
->
execute
(
)
;
$result
=
$stmt
->
get_result
(
)
;
if
(
$result
->
num_rows
==
1
)
{
$user
=
$result
->
fetch_assoc
(
)
;
if
(
password_verify
(
$password
,
$user
[
'password'
]
)
)
{
$_SESSION
[
'user_id'
]
=
$user
[
'id'
]
;
$_SESSION
[
'username'
]
=
$user
[
'username'
]
;
header
(
"Location: dashboard.php"
)
;
}
else
{
echo
"Invalid password"
;
}
}
else
{
echo
"User does not exist"
;
}
$stmt
->
close
(
)
;
}
$conn
->
close
(
)
;