PHP :: MySQL连接
该代码段将连接到您的MySQL数据库:
$mysqli = mysqli_connect('localhost', 'DATABASE_USER', 'DATABASE_PASS', 'DATABASE_NAME');
检查连接错误:
if (mysqli_connect_errno()) { die('Failed to connect to MySQL: ' . mysqli_connect_error()); }
选择数据库表并显示所有结果:
$result = $mysqli->query('SELECT * FROM workers'); while ($row = $result->fetch_assoc()) { echo $row['name'] . '
'; }
检查行数:
$result->num_rows;
插入新记录:
$mysqli->query('INSERT INTO workers (name) VALUES ("John")');
检查受影响的行数:
$mysqli->affected_rows;
转义字符串中的特殊字符,如果不准备声明,则应使用此字符:
$mysqli->real_escape_string($user_input_text);
准备语句,防止SQL注入:
$name = 'John'; $limit = 1; $stmt = $mysqli->prepare('SELECT * FROM workers WHERE name = ? LIMIT ?'); $stmt->bind_param('si', $name, $limit); $stmt->execute(); //等等... $result = $stmt->get_result();
关闭查询并关闭数据库连接:
$stmt->close(); $mysqli->close();