2016-02-04 58 views
0

我使用mysqli的更新是被廢棄(mysql_*)一個應用程序,我有這個查詢的煩惱:遷移過時的應用程序(mysql_ *到mysqli的):類對象的mysqli不能轉換成字符串

mysqli_query("INSERT INTO login (user, password, date) 
     VALUES ('$user', '$password', CURDATE())", $con) or die ("Error query."); 

根據該公報的文檔,代碼應該是:

mysqli_query($con,"INSERT INTO login (user, password, date) 
     VALUES ('$user', '$password', CURDATE())") or die ("Error query."); 

但是,這將引發以下:

Catchable fatal error: Object of class mysqli could not be converted to string 

我檢查過是否使用mysqli連接而不使用mysql,因爲之前發生的錯誤是由於我查詢的是mysql並與mysqli連接造成的。另一個選擇是將查詢保存到一個變量中,然後解決它。

我connection.php:

define('DB_SERVER','myserver'); 
define('DB_NAME','mydbname'); 
define('DB_USER','myuser'); 
define('DB_PASS','myDBPass'); 
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS); 
mysqli_select_db($con,DB_NAME); 
+0

嘗試更換: $ CON = mysqli_connect(DB_SERVER,DB_USER,DB_PASS); mysqli_select_db($ con,DB_NAME); 與 $ con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); 並添加調試: if(mysqli_connect_errno()) echo「無法連接到MySQL:」。 mysqli_connect_error(); } – yannik995

+0

mysqli_query中的第一個參數必須是$ con。請檢查變量'$ user'和'$ password'的類型。如果'$ user'和'$ password'是字符串,確定你可以運行。 –

+0

變量是正確的,因爲我的登錄正在工作,只有註冊查詢失敗。 – Pablo

回答

0

我會嘗試改變

$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS); 
mysqli_select_db($con,DB_NAME); 

$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); 

然後,如果你想交換數據庫使用mysqli_select_db。

0

讓我們看到了婁代碼運行良好,

define('DB_SERVER','127.0.0.1'); 
define('DB_NAME','test'); 
define('DB_USER','root'); 
define('DB_PASS',''); 
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS); 
mysqli_select_db($con,DB_NAME); 

$name = 'Vu Tuan Anh' 
mysqli_query($con, "INSERT INTO sample (name, date) 
    VALUES ('$name', CURDATE())") or die ("Error query."); 

但是,如果我做了一些錯誤,$name =>得到$con值一樣$name = $con

=>錯誤:Object of class mysqli could not be converted to string

但如果我犯了其他錯誤,$name =>就像$name= array('abc')

=>錯誤:Array to string conversion in testdb.php on line 12

所以,僅僅靠的var_dump檢查你的代碼

$query = "INSERT INTO login (user, password, date) VALUES ('$user', '$password', CURDATE())"; 
var_dump($query); 
mysqli_query($con, $query) or die("error query");