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, particularly well-suited for web development.
When MySQL and PHP are used together, they can create dynamic, data-driven websites.
PHP provides multiple ways to connect to and operate MySQL databases. You can use the mysqli extension (MySQL Improved) or PDO (PHP Data Objects).
If you want to learn about using MySQL within PHP, you can visit our (#).
* * *
## Connecting to a MySQL Database
### Using the mysqli Extension
mysqli ("MySQL Improved") 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"Connected successfully";
?>
### Using PDO (PHP Data Objects)
PDO provides a data-access abstraction layer that can work with different database systems:
## Example
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo"Connected successfully";
}
catch(PDOException $e){
echo"Connection failed: ".$e->getMessage();
}
?>
* * *
## Executing SQL Queries
### Querying Data
Using mysqli to query data:
## Example
$sql="SELECT id, name, email FROM users";
$result=$conn->query($sql);
if($result->num_rows>0){
// Output data of each row
while($row=$result->fetch_assoc()){
echo"id: ".$row." - Name: ".$row." - Email: ".$row."
";
}
}else{
echo"0 results";
}
Using PDO to query data:
## Example
$stmt=$conn->prepare("SELECT id, name, email FROM users");
$stmt->execute();
// Set the result set to an associative array
$result=$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll()as$row){
echo"id: ".$row." - Name: ".$row." - Email: ".$row."
";
}
### Inserting Data
mysqli data insertion 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 data insertion example (a more secure method):
## Example
$stmt=$conn->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name',$name);
$stmt->bindParam(':email',$email);
// Insert one row
$name="John Doe";
$email="john@example.com";
$stmt->execute();
* * *
## Security Considerations
### Preventing SQL Injection
SQL injection is a common security threat. To prevent SQL injection, you should:
1. Use prepared statements (as shown in the PDO example above)
2. Validate and filter user input
3. Never directly concatenate user input into SQL queries
### Other Security Practices
* Use the principle of least privilege: Database users should only have the necessary permissions.
* Encrypt sensitive data.
* Back up the database regularly.
* Disable error display in production environments.
* * *
## Closing the Database Connection
After completing database operations, you should close the connection to release resources:
mysqli closing connection:
## Example
$conn->close();
PDO closing connection:
## Example
$conn=null;
* * *
## Practical Application Examples
### User Registration System
## Example
// Connect to the database
$conn=new mysqli("localhost","username","password","user_db");
// Check connection
if($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
}
// Handle form submission
if($_SERVER=="POST"){
$username=$_POST['username'];
$email=$_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_DEFAULT);// Hash the password
// Prepared statement to prevent SQL injection
$stmt=$conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss",$username,$email,$password);
if($stmt->execute()){
echo"Registration successful!";
}else{
echo"Error: ".$stmt->error;
}
$stmt->close();
}
$conn->close();
### User Login System
## Example
session_start();
$conn=new mysqli("localhost","username","password","user_db");
if($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
}
if($_SERVER=="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();
π Categories
- β‘ JavaScript (1589)
- π PHP (872)
- π Python3 (810)
- π HTML (691)
- βοΈ C# (650)
- π Python (594)
- β Java (552)
- βοΈ PyTorch (534)
- π§ Linux (472)
- βοΈ C (432)
- π¦ jQuery (406)
- π¨ CSS (377)
- π XML (259)
- π¦ jQuery UI (231)
- π― Bootstrap (220)
- βοΈ C++ (215)
- π °οΈ Angular (205)
- π HTML DOM (201)
- π΄ Redis (188)
- π Web Building (142)
- π Vue.js (141)
- π R (131)
- πΌ Pandas (124)
- ποΈ SQL (105)
- βοΈ Docker (86)
- βοΈ TypeScript (73)
- βοΈ Highcharts (70)
- π AI Agent (70)
- βοΈ React (68)
- π Node.js (65)
- βοΈ Machine Learning (60)
- π Git (59)
- π΅ Go (58)
- π Markdown (58)
- π’ NumPy (55)
- π§ͺ Flask (54)
- βοΈ Scala (53)
- ποΈ SQLite (52)
- π JSTL (52)
- βοΈ VS Code (51)
- π MongoDB (49)
- π Perl (48)
- π Ruby (47)
- π Matplotlib (47)
- βοΈ Uncategorized (46)
- π Swift (46)
- ποΈ PostgreSQL (46)
- βοΈ Data Structures (46)
- π Playwright (46)
- π iOS (45)
- ποΈ MySQL (44)
- βοΈ LangChain (43)
- π FastAPI (40)
- βοΈ Ionic (38)
- π Design Patterns (37)
- βοΈ Eclipse (37)
- π¨ CSS3 (34)
- π Lua (34)
- βοΈ Codex (34)
- πΈ Django (32)
- βοΈ OpenCV (32)
- π Rust (31)
- π JSP (31)
- βοΈ Claude Code (31)
- π Pillow (30)
- βοΈ OpenCode (28)
- π AI Skills (27)
- π Flutter (26)
- π Maven (26)
- π¨ Tailwind CSS (25)
- π§ TensorFlow (25)
- π Servlet (24)
- π Dart (23)
- π Assembly (23)
- βοΈ Memcached (22)
- βοΈ SVG (22)
- βοΈ Electron (22)
- π NLP (22)
- π Regex (21)
- π Android (20)
- π£ Kotlin (19)
- π Julia (19)
- π SOAP (17)
- π Selenium (17)
- π PowerShell (17)
- π Sass (16)
- π HTTP (16)
- π Zig (15)
- π AI (15)
- π AJAX (14)
- π Swagger (14)
- βοΈ Scikit-learn (13)
- βοΈ ECharts (13)
- βοΈ Chart.js (13)
- βοΈ Cursor (13)
- βοΈ SciPy (12)
- π RDF (12)
- π Ollama (12)
- π Next.js (12)
- π Plotly Dash (12)
- π JSON (11)
- π RESTful API (11)
- π WSDL (9)
- βοΈ CMake (8)
- π Firebug (7)
- π Nginx (6)
- βΈοΈ Kubernetes (6)
- π Jupyter (6)
- π LaTeX (4)
- π UniApp (4)
- ποΈ SQL Server (1)
YouTip