您好,登錄后才能下訂單哦!
這篇文章主要介紹PHP tp5中如何使用原生sql查詢代碼,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
注意事項:
1.先在database.php中配置好數(shù)據(jù)庫
2.只要是數(shù)據(jù)庫操作必須引用 use/think/Db;嚴(yán)格區(qū)分大小寫。
下面是方法:
public function hello5() { //所有查詢必須 use/think/Db; /* 1 配置數(shù)據(jù)庫 * 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); // 查詢數(shù)據(jù) // $result = Db::query('select * from sb_ad where ad_id = 1'); // print_r($result); // 刪除數(shù)據(jù) // $result = Db::execute('delete from sb_ad where ad_id = 2 '); // dump($result); //其它操作 // 顯示數(shù)據(jù)庫列表 // $result = Db::query('show tables from tpshop1'); // print_r($result); // 清空數(shù)據(jù)表 // $result = Db::execute('TRUNCATE table sb_ad'); // dump($result); /**************多個數(shù)據(jù)庫操作************/ //在application/config.php中加入配置 //例子: /* * // 數(shù)據(jù)庫配置1 'db2' => [ // 數(shù)據(jù)庫類型 'type' => 'mysql', // 服務(wù)器地址 'hostname' => '127.0.0.1', // 數(shù)據(jù)庫名 'database' => 'tpshop2', // 數(shù)據(jù)庫用戶名 'username' => 'root', // 數(shù)據(jù)庫密碼 'password' => '', // 數(shù)據(jù)庫連接端口 'hostport' => '', // 數(shù)據(jù)庫連接參數(shù) 'params' => [], // 數(shù)據(jù)庫編碼默認(rèn)采用utf8 'charset' => 'utf8', // 數(shù)據(jù)庫表前綴 'prefix' => 'tp_', ], 依次類推 */ //connect為鏈接數(shù)據(jù)庫 // $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');獲取數(shù)據(jù)庫對象 // $db2 = Db::connect('db2');獲取數(shù)據(jù)庫對象然后再操作 // $db1->query('select * from sb_ad where ad_id = 1'); // $db2->query('select * from sb_ad where ad_id = 1'); /*****參數(shù)綁定******/ // Db::execute('insert into sb_ad (ad_name, ad_content ,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, ad_content ,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);
以上是“PHP tp5中如何使用原生sql查詢代碼”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。