本文目錄一覽:
php怎麼連接mysql
連接到一個 MySQL 資料庫
在您能夠訪問並處理資料庫中的數據之前,您必須創建到達資料庫的連接。
在 PHP 中,這個任務通過 mysql_connect() 函數完成。
語法
mysql_connect(servername,username,password);
參數
描述
servername 可選。規定要連接的伺服器。默認是 “localhost:3306″。
username 可選。規定登錄所使用的用戶名。默認值是擁有伺服器進程的用戶的名稱。
password 可選。規定登錄所用的密碼。默認是 “”。
php連接mysql
public function getInfo(){
$this-userName=$this-userInfo[“name”];
$this-userPSW=$this-userInfo[“password”];
$this-userAge=$this-userInfo[“age”];
$this-userGrade=$this-userInfo[“grade”];
}
你這裡不對吧,應該是
$this-userName=$this-userInfo[0][“name”];
$this-userPSW=$this-userInfo[0][“password”];
$this-userAge=$this-userInfo[0][“age”];
$this-userGrade=$this-userInfo[0][“grade”];
就算你只取一條數據,也還是一個數組,所以要加下標0
php如何連接mysql
用mysql的函數庫
第一步 連接資料庫
mysql_connect(‘localhost’,’username’,’password’)
第二步 設置字符集
mysql_set_charset(‘utf8’);
第三步 選擇資料庫
mysql_select_db(‘DB_name’);
第四步 準備SQL語句
$sql = ‘select * from table_name’;
第五步 執行SQL語句
$result = mysql_query($sql);
第六步 解析數據
$data = mysql_fetch_array($result);
最後一步 關閉資料庫連接
mysql_close();
以上是資料庫最基本操作 不過mysql這套函數庫將要被淘汰 建議改用mysqli 或則 pdo
如何在PHP中連接MySQL資料庫
php鏈接mysql必備條件:
已安裝mysql資料庫;
檢查php環境是否已開啟mysql擴展(一般情況下是開啟的);
檢查方法:a.使用phpinfo();函數,看有沒有mysql項;b.打開php.ini文件,檢查php_mysql.dll前分號是否已取掉。
php鏈接代碼如下:
?php
//設置編碼格式
header(“Content-type:text/html;charset=utf-8”);
//定義資料庫主機地址
$host=”localhost”;
//定義mysql資料庫登錄用戶名
$user=”root”;
//定義mysql資料庫登錄密碼
$pwd=””;
//鏈接資料庫
$conn = mysql_connect($host,$user,$pwd);
//對連接進行判斷
if(!$conn){
die(“資料庫連接失敗!”.mysql_errno());
}else{
echo “資料庫連接成功!”;
}
?
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257212.html