我創建了一個連接數據庫的php文件,從表中獲取數據並以json格式顯示它。url上的PHP/JSON參數
該文件在被調用的index.php。
要查看JSON我剛去的文件瀏覽器:
http://127.0.0.1/json/index.php and it displays:
{"title":[{"id":"1","title":"Title1","desc":"Description1"},{"id":"2","title":"Title2","desc":"Description2"}]}
我需要做的是能夠通過添加參數,如過濾此:
For example: http://127.0.0.1/json/index.php?id=1 to just show the data with an id of 1 but it still shows all the data.
這裏是php代碼:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("mydb",$dbhandle)
or die("Could not select mydb");
$result = mysql_query("SELECT * FROM contacts");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['title'][] = $r;
}
print json_encode($rows);
?>
我在做什麼錯在這裏或失蹤?
請不要用'mysql_ *對新代碼'功能。他們不再被維護,社區已經開始[棄用流程](http://news.php.net/php.internals/53799)。看到[**紅框**](http://php.net/mysql-connect)?相反,您應該瞭解[準備好的陳述](http://en.wikipedia.org/wiki/Prepared_statement)並使用[PDO](http://php.net/pdo)或[MySQLi](http:// php.net/mysqli)。如果你不能決定,試試[這篇文章](http://php.net/mysqlinfo.api.choosing)。如果你關心學習,[這裏是很好的PDO教程](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers)。 –