通過php簡單操作mysql

來源:互聯網
上載者:User

標籤:取值   ace   into   簡單   each   order   style   white   終端   

除了在終端操作mysql外,還可以在php檔案也可以操作mysql,步驟如下:

1.連結資料庫:mysqli_connect(host,user[,password]);

<1>host一般寫localhost或者127.0.0.1

<2>user是root

<3>有密碼就寫,沒密碼就不寫

$connect = mysqli_connect("127.0.0.1","root","chencuixin644152");
tip:一般在末尾加上 or die("資料庫沒串連成功");
$connect = mysqli_connect("127.0.0.1","root","chencuixin644152") or die("資料庫沒串連成功") ;

2.選擇資料庫:mysqli_connect(link,dbname);

<1>link是指串連的資料庫;

<2>dbname是指你要操作的表格名;

mysqli_select_db($connect,"class") or die(mysqli_error($connect));
tip:一般在末尾加上 or die(mysqli_error($connect)),將在mysql上顯示的錯誤資訊顯示在php頁面上;

3.設定編碼:mysqli_select_db() 或者mysqli_query();

mysqli_set_charset($connect,"utf8") or die(mysqli_error($connect));

或者可以寫成如下寫法:
mysqli_query($connect,"set names utf8") or die(mysqli_error($connect));

4.要在資料庫執行的語句

$insertSql = "insert into staff (id,name,sex,age,post,salary,position) values(8,‘小剛‘,‘男‘,7,‘人事部‘,3000,‘人事部門‘)";

tip:$insertSql是字串類型;

5.將語句插入資料庫:mysqli_query();

$result = mysqli_query($coon,$insertSql)  or die(mysqli_error($connect));
針對非SELECT、SHOW、DESCRIBE 或 EXPLAIN 查詢成功的查詢,將返回 TRUE。如果失敗,則返回 FALSE。
if($result == true){
    echo "資料插入成功";
}else{
echo "資料插入失敗";
}
針對成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查詢,將返回一個 mysqli_result 對象。
$resultSet = mysqli_query($connect,$selectSql);//返回一個對象

6.從資料庫取值到php中:mysqli_fetch_assoc()或者mysqli_fetch_object()或者mysqli_fetch_row();

<1>mysqli_fetch_assoc():返回一個索引數組;

<2>mysqli_fetch_obeject():返回一個對象;

<3>mysqli_fetch_row():返回一個索引數組。

echo "<table border=‘1‘ cellpadding=‘10‘>";
while($result=mysqli_fetch_assoc($resultSet)){
echo "<tr>";
echo "<td>{$result[‘id‘]}</td><td>{$result[‘name‘]}</td><td>{$result[‘sex‘]}</td><td>{$result[‘age‘]}</td><td>{$result[‘post‘]}</td><td>{$result[‘salary‘]}</td><td>{$result[‘position‘]}</td>";
echo "</tr>";
}
echo "</table>";


tip:該方法類似each,調用一次該方法,指標位移一次。

 

 

 

 

 


 

通過php簡單操作mysql

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.