在Mac OS下搭建PHP环境并操作MySQL,可以按照以下步骤进行:
安装Homebrew:在终端中运行以下命令安装Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
安装PHP:在终端中运行以下命令安装PHP:
brew install php
安装MySQL:在终端中运行以下命令安装MySQL:
brew install mysql
启动MySQL服务:在终端中运行以下命令启动MySQL服务:
brew services start mysql
设置MySQL根密码:在终端中运行以下命令设置MySQL根密码:
mysql_secure_installation
连接MySQL:在终端中运行以下命令连接MySQL:
mysql -u root -p
创建数据库:在MySQL命令行中运行以下命令创建数据库:
CREATE DATABASE mydatabase;
创建表:在MySQL命令行中运行以下命令创建表:
USE mydatabase;
CREATE TABLE mytable (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
);
PHP操作MySQL常用方法:
$servername = "localhost";
$username = "root";
$password = "your_password";
$dbname = "mydatabase";
$conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
- 插入数据:
```php
$sql = "INSERT INTO mytable (name, age) VALUES ('John Doe', 25)";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error inserting record: " . $conn->error;
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Age: " . $row["age"]. "
";
}
} else {
echo "No records found";
}
- 更新数据:
```php
$sql = "UPDATE mytable SET age = 30 WHERE name = 'John Doe'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "DELETE FROM mytable WHERE name = 'John Doe'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
这样就完成了在Mac OS下搭建PHP环境并操作MySQL的过程,并给出了PHP操作MySQL常用方法的小结。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站