mysql 資料庫 增刪改查
阿新 • • 發佈:2018-12-10
//建立表的函式 function creatTabel($table){ //建立 myspl 物件 mysqli(伺服器地址,使用者名稱,密碼,資料庫的名字) $mySql = new mysqli("127.0.0.1","root","","zxbCreat"); //2, if ($mySql->connect_error) { exit("資料庫連線錯誤,錯誤資訊{$mySql->connect_error}"); } else { echo "資料庫連線成功<hr>"; } //3,設定 utf-8 $mySql->set_charset("utf-8"); //4,編寫sql語句 $sql = "create table if not exists {$table}(id int primary key auto_increment, name text, sex text, age int)"; //5,執行sql語句 $result = $mySql->query($sql); if ($result) { echo "建立表成功<hr>"; } else { echo "建立表失敗<hr>"; } //6,關閉資料庫 $mySql->close(); }
插入資料只需要改動 sql語句 : insert into Student (name,sex,age) values('{$name}','{$sex}',{$age})
更新資料庫 update Student set name = '{$name}',sex = '{$sex}', age = {$age} where id = {$id}
刪除資料 delete from Student where id = {$id}
查詢資料庫資訊 查詢所有
//4,編寫sql語句 $sql = "select * from Student"; //5,執行sql語句 //當執行查詢語句時,query 方法的返回值 是一個物件 一個mysqli_result 型別的物件該物件中儲存的是查詢到的所有資訊 $result = $mySql->query($sql); //num_rows查詢到的資料條數 if($result -> num_rows){ for ($i=0; $i < $result -> num_rows; $i++) { //獲取每行的資料物件 $row = $result -> fetch_object(); //資料庫欄位名就是屬性名 echo "id = {$row->id}<br>"; echo "name = {$row->name}<br>"; echo "sex = {$row->sex}<br>"; echo "age = {$row->age}<hr>"; } };
根據 id 查詢資料
//4,編寫sql語句 $sql = "select * from Student where id = {$id}"; //5,執行sql語句 $result = $mySql->query($sql); while ($row = $result -> fetch_object()) { echo "id = {$row->id}<br>"; echo "name = {$row->name}<br>"; echo "sex = {$row->sex}<br>"; echo "age = {$row->age}<hr>"; }