连接 MySQL 数据库

利用 mysqli 扩展连接 MySQL 数据库:

$host = "localhost";

$username = "username";

php5andmysql常见phpmysql操作年夜全 JavaScript

$password = "password";

$dbname = "database_name";

// 创建连接

$conn = mysqli_connect($host, $username, $password, $dbname);

// 检讨连接是否成功

if (!$conn) {

die("连接失落败: " . mysqli_connect_error());

}

echo "连接成功";

利用 PDO 扩展连接 MySQL 数据库:

$host = "localhost";

$username = "username";

$password = "password";

$dbname = "database_name";

// 创建连接

try {

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

// 设置 PDO 缺点模式为非常

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "连接成功";

} catch(PDOException $e) {

echo "连接失落败: " . $e->getMessage();

}

查询 MySQL 数据

利用 mysqli 扩展查询 MySQL 数据:

$sql = "SELECT id, name, email FROM users";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

// 输出每一行数据

while($row = mysqli_fetch_assoc($result)) {

echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";

}

} else {

echo "0 结果";

}

// 开释结果集

mysqli_free_result($result);

利用 PDO 扩展查询 MySQL 数据:

$sql = "SELECT id, name, email FROM users";

$stmt = $conn->query($sql);

// 设置结果集为关联数组

$stmt->setFetchMode(PDO::FETCH_ASSOC);

if ($stmt->rowCount() > 0) {

// 输出每一行数据

foreach($stmt as $row) {

echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";

}

} else {

echo "0 结果";

}

// 关闭游标,开释结果集

$stmt->closeCursor();

插入 MySQL 数据

利用 mysqli 扩展插入 MySQL 数据:

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {

echo "新记录插入成功";

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

}

利用 PDO 扩展插入 MySQL 数据:

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";

if ($conn->exec($sql)) {

echo "新记录插入成功";

} else {

echo "Error: " . $sql . "<br>" . $conn->errorInfo()[2];

}

更新 MySQL 数据

利用 mysqli 扩展更新 MySQL 数据:

$sql = "UPDATE users SET email='john.doe@example.com' WHERE name='John Doe'";

if (mysqli_query($conn, $sql)) {

echo "记录更新