将mysql转换为mysqli
问题描述:
我对Mysql和PHP完全陌生。我写了一个脚本,但工作,但现在意识到,我应该使用mysqli而不是mysql。我试图将所有的'mysql _...'改为'mysqli_',但是没有工作。任何人都可以告诉我如何重写下面的代码?
I'm completely new to Mysql and PHP. I wrote a script that works but now realise that I should be using mysqli not mysql. I tried changing all the 'mysql_...' to 'mysqli_' but that didn't work. Can anyone tell me exactly how to rewrite the code below?
$tableName = "Fixtures";
//==== CONNECT TO DATABASE
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
//==== PUT DATA INTO ARRAY
$array = array();
while ($row = mysql_fetch_row($result)) {
$array[] = $row;
}
//==== ECHO AS JSON
echo json_encode($array);
答
很简单
$db = new mysqli("host", "user", "password", "db");
$result = $db->query("SELECT * FROM $tableName");
while ($row = $result->fetch_row()) {
//etc.
}
我发现 php.net文档mysqli 有用查找功能以及codesnippets。这也可以回答您的问题 php.net/mysqli_fetch_row
I find the php.net documentation on mysqli useful for looking up functions as well as codesnippets. This also answers your question php.net/mysqli_fetch_row