2013-03-24 22 views
1

我正在開發一個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%'"; 

您的建議將高度讚賞。

+0

絕對了解準備好的語句,因爲您的代碼是SQL注入attck的完美候選者。 – 2013-03-24 15:56:40

+0

另外,規範鏈接:[爲什麼要從mysql API升級](http://blog.ulf-wendel.de/2012/php-mysql-why-to-upgrade-extmysql/)。請考慮使用PDO或mysqli_函數(並使用預準備語句)。 – mabi 2013-03-24 16:08:20

回答

0

SQL查詢到目前爲止正確,但您傳遞的值是空的。

$code = $_POST["code"]; 
    $price = $_POST["price"]; 
    $module = $_POST["module"]; 

的值是空的。嘗試確保該值已設置。

有時雙引號是可以響應的。然後嘗試用單引號替換它們

$code = $_POST['code']; 
    $price = $_POST['price']; 
    $module = $_POST['module']; 
+0

欣賞您的回覆。你想要多一點合作,我的意思是價值觀是如何解決的? – 2013-03-24 16:00:06

+0

我只使用'$ code'' $ price'和'$ module'在我的應用程序中執行搜索功能,並且它們在我的應用程序中正常工作。 – 2013-03-24 16:06:08

+0

@ OliverSmith-Jones 1.確保您按要求提供正確的參數。 2.嘗試用$ _POST ['...']替換$ _POST [「...」]; – 2013-03-24 16:08:15