Mac電腦上使用PHP訪問MySQL數(shù)據(jù)庫,需要進行以下幾個步驟:
1. 安裝MySQL
//使用Homebrew安裝 brew install mysql
2. 啟動MySQL
//使用命令行啟動 mysql.server start
3. 創(chuàng)建數(shù)據(jù)庫和表
//進入MySQL命令行 mysql -u root -p //創(chuàng)建一個名為test的數(shù)據(jù)庫 CREATE DATABASE test; //切換到test數(shù)據(jù)庫 USE test; //創(chuàng)建一個名為users的表 CREATE TABLE users( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );
4. 安裝PHP的MySQL擴展
//使用Homebrew安裝PHP brew install php //安裝MySQL擴展 brew install php-mysql
5. 編寫PHP代碼連接數(shù)據(jù)庫
//連接MySQL數(shù)據(jù)庫 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "test"; $conn = new mysqli($servername, $username, $password, $dbname); //檢測連接是否成功 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully";
通過上述步驟,Mac電腦上的PHP程序就可以訪問MySQL數(shù)據(jù)庫了。