我正在開發一個android應用程序,我需要有一個PHP API才能讓我的應用程序與SQL數據庫交談。PHP API中的語法錯誤
我有上getJarrayFromString();
然後我試圖登錄實際的錯誤錯誤解析成JSON和它如下:
03-24 15:41:12.175: E/JustDealsUtils(480): Error parsing to json on getJarrayFromString(); org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONArray
03-24 15:41:12.175: E/log_tag(480): Failed data was:
03-24 15:41:12.175: E/log_tag(480): Database query failed You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'bCode` LIKE '%%' AND `bTitle` LIKE '%%' AND `bModule` LIKE '%%'' at line 1
現在上面的日誌澄清很清楚,錯誤在於我books.php
API是如下:
<?php
include("MysqlConnection.php");
header('Content-Type: application/json');
$from = $_POST["from"];
$nr = $_POST["nr"];
// those variables are for search
$title = $_POST["title"];
$code = $_POST["code"];
$price = $_POST["price"];
$module = $_POST["module"];
$order = $_POST["order"];
$by = $_POST["by"];
$sql = "SET CHARACTER SET utf8";
$db->query($sql);
if(isset($from) && isset($nr)){
// we need to know how many rows are in total for this query
<PROBLEM IS HERE---> $sql = "SELECT * FROM `books` WHERE `bSpecialOffer`='false' AND `bCode` LIKE '%$code%' AND `bTitle` LIKE '%$title%' AND `bModule` LIKE '%$module%'";
$query = $db->query($sql);
$rows = array();
$rows[] = array("numRows"=>$db->numRows($query));
// if those 2 var are set then we order the query after them
if(isset($order) && isset($by)){
$sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
}else{
$sql .= "LIMIT $from, $nr";
}
$query = $db->query($sql);
if($db->numRows($query)!=0){
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
}
}
$db->closeConnection();
?>
我很困惑以上登錄貓提到我的發言是怎麼錯的PHP!
是否有寫下面的另一種方式:
$sql = "SELECT * FROM `books` WHERE `bSpecialOffer`='false' AND `bCode` LIKE '%$code%' AND `bTitle` LIKE '%$title%' AND `bModule` LIKE '%$module%'";
您的建議將高度讚賞。
絕對了解準備好的語句,因爲您的代碼是SQL注入attck的完美候選者。 – 2013-03-24 15:56:40
另外,規範鏈接:[爲什麼要從mysql API升級](http://blog.ulf-wendel.de/2012/php-mysql-why-to-upgrade-extmysql/)。請考慮使用PDO或mysqli_函數(並使用預準備語句)。 – mabi 2013-03-24 16:08:20