2015-08-19 2 views
0

Следующий код выглядит неправильно. Я новичок в PHP и jQuery.Запрос PHP и MySQLi всегда возвращается 0

PHP:

<?php 

//if (!defined('BOOTSTRAP')) { die('Access denied'); } 

//if we got something through $_POST 
if (isset($_POST['postcode_locator_search'])) { 
    // here you would normally include some database connection 
    //include('config.local.php'); 

    //Open a new connection to the MySQL server 
    $mysqli = new mysqli('localhost','test','[email protected])ukmd[0bm','test'); 

    //Output any connection error 
    if ($mysqli->connect_error) { 
     die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); 
    } 

    // never trust what user wrote! We must ALWAYS sanitize user input 
    $postcode_q = mysqli_real_escape_string($mysqli, $_POST['postcode_locator_search']); 
    $postcode_q = htmlentities($postcode_q); 

    // A select query. $result will be a `mysqli_result` object if successful 
    $result = mysqli_query("SELECT description FROM cscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1"); 

    if($result === false) { 
     // Handle failure - log the error, notify administrator, etc. 
     echo '1'; 
    } else { 
     // Fetch all the rows in an array 
     echo '0'; 
    } 

    $mysqli->close(); 

} 
?> 

JS/HTML:

{assign var="prod_id" value=$product.product_id} 

<form action="search_postcode.php" method="post" class="postcode_locator_form" name="postcode_locator_form"> 
    <div class="ty-control-group"> 
     <label for="postcode_locator_search{$block.block_id}" class="ty-control-group__title">{__("postcode_search")}</label> 
     <p class="filling-notice">{__("postcode_search_desc")}</p> 
     <div class="ty-input-append ty-m-none"> 
      <input type="text" size="20" class="ty-input-text" id="postcode_locator_search" name="postcode_locator_search" value="{$postcode_locator_search.q}" /> 
      {include file="buttons/go.tpl" but_name="postcode_locator.search" alt=__("search")} 
     </div> 

    </div> 
</form> 

<div class="filling-status filling-success"> 
    <h3>Add filling to your bean bag</h3> 
    <p>Searched postcode: <span class="searched-postcode"></span></p> 
    <p class="beans-msg">{__("add_some_beans_success")} <a href="{"checkout.add_bean_bag_filling&product_id=`$product.product_id`"|fn_url}">{__("click_here")}</a></p> 
</div> 
<div class="filling-status filling-failure"> 
    <h3>Add filling to your bean bag</h3> 
    <p>Searched postcode: <span class="searched-postcode"></span></p> 
    <p class="beans-msg">{__("add_some_beans_error")}</p> 
</div> 

<script> 
$(function() { 

    $(".filling-status").hide(); 
    $(".postcode_locator_form .ty-btn-go").click(function() { 
     // getting the value that user typed 
     var searchString = $("#postcode_locator_search").val(); 
     // forming the queryString 
     var data   = 'postcode_locator_search='+ searchString; 

     // if searchString is not empty 
     if(searchString) { 
      // ajax call 
      $.ajax({ 
       type: "POST", 
       url: "search_postcode.php", 
       data: data, 
       beforeSend: function(html) { // this happens before actual call 
        $(".searched-postcode").html(searchString); 
       }, 
       success: function(data){ // this happens after we get results 
        console.log(data); 
        if(data == '0'){ 
         $(".filling-status.filling-success").show(); 
        } else if(data == '1'){ 
         $(".filling-status.filling-failure").show(); 
        } 
       } 
      });  
     } 
     return false; 
    }); 
}); 
</script> 

Коммуникация это все работает, но он всегда возвращает 0, как успех, из какого бы я искать и, кажется, не проверить базу данных для результат.

Что мне нужно, если я что-то ищу, и это совпадение, чтобы вернуть 0 как успех, но если не найдено/совпадение, чтобы вернуть 1 как отказ.

+0

Потому что это говорит о вашем состоянии. Он извлекает все ваши данные и эхо-строку 0; – aldrin27

+0

Как я могу это исправить? извините im new для PHP, поэтому проб и ошибок до сих пор и почти 2 часа ночи haha ​​ – James

+0

Вы зарегистрировали ошибку, которую получаете при запуске запроса? Похоже, что у вас есть недопустимые имена таблиц и полей в вашем запросе. Являются ли ваши таблицы и имя вашего поля 'cscart_postcode_location_descriptions'? – DGS

ответ

0

Используйте mysqli_num_rows обнаружить, если у вас есть результат

if($result === false or mysqli_num_rows($result) === 0) { 
    echo '1'; 
} 

Я рекомендовал бы ломать это в два, если условия, хотя, так что вы обрабатывать ошибки отдельно от запроса без результата

+0

Я пробовал это, но так же, как и другой ответ, набираю то, что не является допустимым результатом и чем-то что должно быть и оба верны? – James

+0

Что недействительно? откликните свой запрос, когда вы ожидаете его сбой, и посмотрите, что он на самом деле запрашивает – DGS

+0

и его всегда возвращает 0 на консоль .... – James

1

Если вы хотите Извлеките свои данные:

$result = mysqli_query("SELECT description FROMcscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1"); 

if($result === false) { 
    // Handle failure - log the error, notify administrator, etc. 
    echo '1'; 
} else { 
    // Fetch all the rows in an array 
    while($row = mysqli_fetch_assoc($result)){ 
    echo $row['id']; //prints the resulted id 
    } 
} 
+0

И, пожалуйста, обратитесь к ответу @DGS. – aldrin27

+0

Я пробовал оба решения, но всегда возвращает 0, даже что-то случайное, что не в результате ... :(Может быть, мой запрос в некотором роде? – James

+0

может быть, это проблема в вашем коде '$ postcode_q = mysqli_real_escape_string ($ mysqli , $ _POST ['postcode_locator_search']) $ postcode_q = htmlentities ($ postcode_q); ' – aldrin27

Смежные вопросы