2013-06-30 44 views
0

我有一個上傳形式的PHP代碼,並試圖更新這個MySQL到推薦的mysqli。我正在嘗試學習OO風格(也是程序性的,但我傾向於學習OO風格)。需要幫助轉換這個PHP的MySQL代碼mysqli

我已經成功上更新我的所有代碼,到目前爲止,除了這個片段:

function query($query) { 
$database = $this->options['database']; 
$host = $this->options['host']; 
$username = $this->options['username']; 
$password = $this->options['password']; 
$link = mysql_connect($host,$username,$password); 
if (!$link) { 
    die(mysql_error()); 
} 
$db_selected = mysql_select_db($database); 
if (!$db_selected) { 
    die(mysql_error()); 
} 
$result = mysql_query($query); 
mysql_close($link); 
return $result; 
} 

誰能幫我翻譯成庫MySQLi,面向對象的風格?我嘗試瞭如此多的組合,我不知道自己在哪裏出錯(我在嘗試上傳照片時遇到了數據庫錯誤)。

謝謝!

+1

請添加收到了一些代碼,你試過了,錯誤訊息,我們會盡量通過指出什麼地方錯了,幫助你.. –

+0

在大多數情況下,只要程序風格的話,你可以只用'mysqli_'替換每個'mysql_'的實例。 –

回答

0

這應該適合你。我不確定mysqli結果是否能夠在mysqli-> close()中生存下來,所以我已經將$ result中的數據檢索到數組中並返回了。你可能想要測試這個。

我還想知道爲什麼要打開連接並在每個查詢周圍重新關閉連接。我通常會打開連接並保持打開狀態,直到腳本完成所有查詢。

function query($query) { 
    // no real need for this - the variables can be used directly 
    $database = $this->options['database']; 
    $host = $this->options['host']; 
    $username = $this->options['username']; 
    $password = $this->options['password']; 

    // instantiate the mysqli object. Select the database at the same time. 
    $mysqli = new mysqli($host, $username, $password, $database); 

    if ($mysqli->connect_error) { 
    die($mysqli->connect_error); 
    } 

$result = $mysqli->query($query); 
if ($result !== false) { 

    // retrieve data 
    $data = array(); 
    while ($data[] = $result->fetch_assoc()) {} 

    // release the result set and close the connection 
    $result->free(); 
    $mysqli->close(); 
    return $data; 
} else { 
    syslog(LOG_ERROR, "SQL error:".$mysqli->error); 
    $mysqli->close(); 
    return false;  
} 
} 
+0

感謝您的回覆(並評論你做了什麼,非常感謝)......雖然此代碼允許照片上傳,併發送電子郵件(單獨的文件,上傳後觸發的電子郵件),但我得到我的上傳頁面中出現「內部服務器錯誤」。我試圖找出爲什麼它說,而不是顯示成功...我會讓你知道,如果我發現......再次感謝! – gamehendgeVA

+0

看看你的服務器日誌 - 那裏應該有一個錯誤消息,這將解釋'內部服務器錯誤' – 2013-06-30 22:28:46

+0

謝謝你的好主意......我清除了日誌,嘗試上傳,並看到這個:PHP致命錯誤:致電在818行 – gamehendgeVA