How PHP Connect to Mysql

My computer develop environment

1
2
$ php -v
PHP 7.0.26
Features PHP mysql extension PHP mysqli extension PDO
PHP Support Version Before 3.0 5.0 5.0
Include In PHP5.x Yes Yes Yes
Development Status Maintenance Only Active Active in PHP5.3
Recommended Usage in New MySQL Projects Not Recommended Recommendations - Preferred Suggestions
API Character Set Support No Yes Yes
Prepare statement support in Server No Yes Yes
Prepare statement support in Client No No Yes
Stored Procedure Support No Yes Yes
Multi-State Execution Support No Yes Most
Does it support all MySQL 4.1+ features No Yes Most

PHP Mysql extension

  • Just MySQL database
  • Most primitive mysql database extension of PHP
  • Mysql 4.1.3-
  • Procedure Oriented
1
2
3
4
5
6
7
8
9
10
11
12
<?php
header('Content-Type: text/html; charset=utf-8');

$username = "liyuliang";
$password = "123456";
$database = "testDB";

$conn = @mysql_connect("localhost:3306",$username,$password) or die("connect mysql failed");

mysql_select_db($database,$conn);

echo "database connect success";

PHP mysqli extension

  • Just MySQL database
  • Mysql 4.1.3+
  • “i” means “Improvement” (Security Increased)
  • Pre-processing statements support (Prevent SQL injection)
  • Procedure Oriented + Object Oriented

It will open a new connection process each time when running PHP mysql extension but Mysqli extension will use the same connection. Because mysqli uses a persistent connection function and mysql is not

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
header('Content-Type: text/html; charset=utf-8');

$username = "liyuliang";
$password = "123456";
$database = "testDB";

$conn = mysqli_connect("localhost", $username, $password, $database, "3306");

if (!$conn) {

die("connect mysql failed" . mysqli_connect_error());
}else{

echo "database connect success";
}

PHP Data Object(PDO)

  • PDO can be used in 12 different database
  • Database abstract standard
  • Pre-processing statements support (Prevent SQL injection)
  • Object Oriented
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
header('Content-Type: text/html; charset=utf-8');

$username = "liyuliang";
$password = "123456";
$database = "testDB";

try {

$conn = new PDO("mysql:host={$username};dbname={$database}", $username, $password);

echo "database connect success";

} catch (PDOException $e) {
echo $e->getMessage();
}
Share