$db = new mysqli('localhost', 'root', '', 'tran');
$name = 'jack';
$sql_1 = sprintf('INSERT INTO `tb_user` (name)VALUES("%s")',mysql_real_escape_string($name));
$db->query($sql_1);
為什麼會出現
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'@'localhost'
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in
這兩個句錯誤的,我知道如果連不上資料庫mysql_real_escape_string是會報錯的,但我明明串連上了,
如果換回mysql_connect() mysql_select_db mysql_query()這樣的連結就沒問題
還有就是我的欄位 name 設定的是not null 為什麼上面的sql語句執行了拋出 Warning 這樣嚴重的錯誤還會儲存一個空值的?not null 不是不可為空否則不能儲存的嗎?
回複討論(解決方案)
mysqli和mysql模組不是一回事。mysql_real_escape_string()需要 mysql_connect()建立的串連。
想實現同樣的功能,參見: mysqli_real_escape_string 這個是mysqli模組下的函數。
不過大多數用PDO或者mysqli的查詢都會採用類似的方法:
http://www.php.net/manual/zh/mysqli.prepare.php
資料由模組根據類型設定自動轉義,像你的C風格寫法很少見。
class db_mysqli extends mysqli { private $link; private $result; private $bol=false; function __construct(){ $this->open_link(); } //開啟串連 private function open_link(){ $this->link=new mysqli($GLOBALS['HOST'],$GLOBALS['USER'],$GLOBALS['PASSWORD'],$GLOBALS['DBNAME']) or die("資料庫連接失敗!".mysqli_error()); $this->link->select_db($GLOBALS['DBNAME']) or die("資料庫選擇失敗!".mysqli_error()); $this->link->set_charset("UTF-8"); } //關閉串連 private function close_result(){ //if($this->result){ //$this->result->free_sult();//關閉結果集 //} } public function db_query($sqlstr){ if(empty($this->link)){ $this->open_link(); } $this->result=$this->link->query($sqlstr); if($this->result){ $row=$this->result->fetch_array(); }else { $row=null; } $this->close_result(); return $row; }
我一般是這樣寫的 ,你寫的我看了好像也沒什麼問題 ,你看一下 ,希望可以協助你。。。。
mysqli和mysql模組不是一回事。mysql_real_escape_string()需要 mysql_connect()建立的串連。
想實現同樣的功能,參見: mysqli_real_escape_string 這個是mysqli模組下的函數。
不過大多數用PDO或者mysqli的查詢都會採用類似的方法:
http://www.php.net/manual/zh/mysqli.prepare.php
資料由模組根據類型設定自動轉義,像你的C風格寫法很少見。
對我很有啟發
class db_mysqli extends mysqli { private $link; private $result; private $bol=false; function __construct(){ $this->open_link(); } //開啟串連 private function open_link(){ $this->link=new mysqli($GLOBALS['HOST'],$GLOBALS['USER'],$GLOBALS['PASSWORD'],$GLOBALS['DBNAME']) or die("資料庫連接失敗!".mysqli_error()); $this->link->select_db($GLOBALS['DBNAME']) or die("資料庫選擇失敗!".mysqli_error()); $this->link->set_charset("UTF-8"); } //關閉串連 private function close_result(){ //if($this->result){ //$this->result->free_sult();//關閉結果集 //} } public function db_query($sqlstr){ if(empty($this->link)){ $this->open_link(); } $this->result=$this->link->query($sqlstr); if($this->result){ $row=$this->result->fetch_array(); }else { $row=null; } $this->close_result(); return $row; }
我一般是這樣寫的 ,你寫的我看了好像也沒什麼問題 ,你看一下 ,希望可以協助你。。。。
對我很有啟發