2014-10-29 2 views
0

나는 약간의 도움이 필요하다. 나는 3 개의 키워드를 기반으로 데이터베이스에서 검색을 수행하는 PHP 스크립트를 가지고 있으며 쿼리는 데이터베이스의 phpadmin에서 훌륭하게 작동하지만 반환 된 JSON 응답은 찾는다. 결과 없음 ("empresa found"). 아무도 왜 내게 말할 수 있습니까? 단일 표 검색을 수행하면 완벽하게 작동합니다. (경우에 그냥 하나 개의 테이블과 관련된 키워드를 사용)PHP 스크립트가 의도 한 JSON 응답을 반환하지 않음

키워드 1 표 A에 이름입니다 키워드 2 키워드 3 표 분야에 부문을위한 테이블 가격

테이블처럼에 PriceRange입니다 :

Table A       Table Prices    Table Sectors 
Name PriceRange Sector  ID  Pricerange   ID  Sector 
XY   1   2   1   100€ to 200€  1   Computers 
YX   2   1   2   200€ to 300€  2   Tablets 

당신의 코드로

<?php 

error_reporting(0); 

require_once('db_config.php'); 

$conn = mysql_connect($db_server, $db_user, $db_password) or die(mysql_error()); 

$db= mysql_select_db($db_database, $conn); 

header('content-type: application/json; charset=utf-8'); 
mysql_query('SET character_set_connection=utf8'); 
mysql_query('SET character_set_client=utf8'); 
mysql_query('SET character_set_results=utf8'); 

// array for JSON response 
$response = array(); 

// get empresa based on keyword 
$keyword=$_GET["keyword"]; 
$keyword2=$_GET["keyword2"]; 
$keyword3=$_GET["keyword3"]; 

if($keyword2 == "Todos os Setores" and $keyword3 == "Qualquer Investimento"): 
    $result = mysql_query("SELECT * FROM empresa WHERE marca LIKE '%$keyword%' and ficha LIKE '%1' ") or die(mysql_error()); 
elseif($keyword2 == "Todos os Setores"): 
    $result = mysql_query("SELECT empresa.ficha, empresa.marca, empresa.empresa, empresa.descricao, empresa.imagempequena from empresa , investimento where investimento.investimento='%$keyword3%' and empresa.nivelinvestimento=investimento.id and empresa.ficha LIKE '%1' and empresa.marca LIKE '%$keyword%'") or die(mysql_error()); 
elseif($keyword3 == "Qualquer Investimento"): 
    $result = mysql_query("SELECT empresa.ficha, empresa.marca, empresa.empresa, empresa.descricao, empresa.imagempequena from empresa, sector where sector.sector='%$keyword2%' and empresa.sector=sector.id and empresa.ficha LIKE '%1' and empresa.marca LIKE '%$keyword%'") or die(mysql_error()); 
else: 
    //query a funcionar 
    $result = mysql_query("SELECT empresa.ficha, empresa.marca, empresa.empresa, empresa.descricao, empresa.imagempequena from empresa , investimento, sector where investimento.investimento='%$keyword3%' and empresa.nivelinvestimento=investimento.id and sector.sector='%$keyword2%' and empresa.sector=sector.id and empresa.ficha LIKE '%1' and empresa.marca LIKE '%$keyword%'") or die(mysql_error()); 
endif; 

// check for empty results 
if (mysql_num_rows($result) > 0) { 
    // looping through all results 
    $response["empresa"] = array(); 

    while ($row = mysql_fetch_array($result)) { 
     // temp user array 
     $empresa= array(); 
     $empresa["marca"] = $row["marca"]; 
     $empresa["empresa"] = $row["empresa"]; 
     $empresa["descricao"] = $row["descricao"]; 
     $empresa["imagempequena"] = $row["imagempequena"]; 

     // push single empresa array into final response array 

     array_push($response["empresa"], $empresa); 
    } 
    // success 
    $response["success"] = 1; 

    // echoing JSON response 
    echo json_encode($response); 
} else { 
    // no products found 
    $response["success"] = 0; 
    $response["message"] = "No empresa found"; 

    // echo no users JSON 
    echo json_encode($response); 
} 
?> 
+3

** 경고 ** 귀하의 코드는 SQL 주입 공격에 매우 취약합니다! –

+0

나는 그것을 많이 얻는다. 이 방법이 처음에는 어떻게 작동하는지 이해하고 싶습니다. 어떻게 든 처리 할 수 ​​있습니다. – Acejakk

+0

http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php –

답변

1

는 여기에 귀하의 문제입니다. 직접 동등성 테스트 =을 수행 할 때 와일드 카드는 특별한 의미가없는 일반 문자입니다.

즉, 키워드 foo을 검색하는 경우 DB에 정확히 일치하는 문자열을 포함하도록 DB에 알립니다 리터럴 문자 %, f, o, o%.

이 두 쿼리는 직접 동일합니다

WHERE foo = '%bar%' 
WHERE substr(foo, 0, 1) = '%' AND substr(foo, 1, 1) = 'b' AND .... 

이 두뿐만 아니라

WHERE foo LIKE '%bar%' 
WHERE LOCATE('bar', foo) <> 0 

그리고 다른 사람들이 지적, 당신은 sql injection attacks에 취약있어, 점에 유의.

+0

지금 사용해 보겠습니다. 나는 SQL 주입을 막기 위해서 모든 키워드를 위의 문장으로 변경했다. – Acejakk

+0

이것은 절대적으로 맞다. mysql_real_escape_string ($ keyword). '% keyword %'대신 '%'를 사용하면 SQL 인젝션 문제를 해결할 수 있습니까? – Acejakk

+0

번호. 적절한 해결책은 쓸모가 없기 때문에 mysql _ *() 함수를 버리고 미리 준비된 명령문과 플레이스 홀더로 PDO를 사용하도록 전환하는 것입니다. –

0

문제는 따옴표함께 PHP 스크립트대신이 코드를 사용해보십시오 '%".mysql_real_escape_string($keyword)."%' 솔직히 SQL 코드를 사용하면 코드 조각이 대부분의 걱정을 처리해야합니다.

쿼리의 대부분에서
where investimento.investimento='%$keyword3%' 
           ^--- 

, 당신은 LIKE 연산자를 사용하는 경우에만 작동 SQL 와일드 카드를 사용하고 있습니다 :)

+0

나는 최대한 빨리 시도 할 것입니다. 그 또한 내 SQL 주입 문제의 대부분을 다루고 있습니까? – Acejakk

+0

예! 기본 보안. 그것이 당신의 문제를 해결할 경우 투표를하는 것을 잊지 마십시오. –

+0

모든 키워드에 적용 했으므로 첫 번째 쿼리는 계속 작동합니다. 그러나 다른 세 가지 쿼리의 문제는 남아 있습니다 (키워드 1과 2, 키워드 1과 3 또는 키워드 1,2와 3 사용). 다중 테이블 쿼리는 작동하지 않는 유일한 쿼리입니다. – Acejakk

관련 문제