PHP tp5中使用原生sql查詢程式碼例項
阿新 • • 發佈:2020-10-29
注意事項:
1.先在database.php中配置好資料庫
2.只要是資料庫操作必須引用 use/think/Db;嚴格區分大小寫。
下面是方法:
public function hello5() { //所有查詢必須 use/think/Db; /* 1 配置資料庫 * 2 使用DB 名稱空間 * */ /****************tp5中使用原生語句*******************/ //query 用於查詢 其他的用execute // 插入記錄 // $result = Db::execute('insert into sb_ad (ad_name,ad_content,status) values (1,"456",1)'); // dump($result); // 更新記錄 // $result = Db::execute('update sb_ad set ad_name = "framework" where ad_id = 1 '); // dump($result); // 查詢資料 // $result = Db::query('select * from sb_ad where ad_id = 1'); // print_r($result); // 刪除資料 // $result = Db::execute('delete from sb_ad where ad_id = 2 '); // dump($result); //其它操作 // 顯示資料庫列表 // $result = Db::query('show tables from tpshop1'); // print_r($result); // 清空資料表 // $result = Db::execute('TRUNCATE table sb_ad'); // dump($result); /**************多個數據庫操作************/ //在application/config.php中加入配置 //例子: /* * // 資料庫配置1 'db2' => [ // 資料庫型別 'type' => 'mysql',// 伺服器地址 'hostname' => '127.0.0.1',// 資料庫名 'database' => 'tpshop2',// 資料庫使用者名稱 'username' => 'root',// 資料庫密碼 'password' => '',// 資料庫連線埠 'hostport' => '',// 資料庫連線引數 'params' => [],// 資料庫編碼預設採用utf8 'charset' => 'utf8',// 資料庫表字首 'prefix' => 'tp_',],依次類推 */ //connect為連結資料庫 // $result = Db::connect('db2')->query('select * from sb_ad where ad_id = 1'); // print_r($result); // $result = Db::connect('db3')->query('select * from sb_ad where ad_id = 1'); // print_r($result); // $db1 = Db::connect('db1');獲取資料庫物件 // $db2 = Db::connect('db2');獲取資料庫物件然後再操作 // $db1->query('select * from sb_ad where ad_id = 1'); // $db2->query('select * from sb_ad where ad_id = 1'); /*****引數繫結******/ // Db::execute('insert into sb_ad (ad_name,status) values (?,?,?)',[3,'thinkphp',1]); // $result = Db::query('select * from sb_ad where ad_id = ?',[3]); // print_r($result); /******命名佔位符繫結*****/ // Db::execute('insert into sb_ad (ad_name,status) values (:ad_name,:ad_content,:status)',['ad_name' => 11,'ad_content' => 'thinkphp','status' => 1]); // $result = Db::query('select * from sb_ad where ad_id=:id',['id' => 10]); // print_r($result);
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。