【问题标题】:PHP and MySQLi query always returning 0PHP 和 MySQLi 查询总是返回 0
【发布时间】:2015-11-12 02:36:21
【问题描述】:

以下代码似乎无法正常工作。我是 PHP 和 jQuery 新手。

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','c@W)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;
  • 我该如何解决?抱歉,我是 PHP 新手,所以到现在和凌晨 2 点都在反复试验,哈哈
  • 您是否记录了运行查询时收到的错误?好像您的查询中有无效的表/字段名称。你的表和字段名真的都是cscart_postcode_location_descriptions吗?
  • 我没有收到错误,它只是总是转为 0(真),事实并非如此,所以我的代码有问题:)

标签: php jquery mysql mysqli


【解决方案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
    }
}

【讨论】:

  • 请参考@DGS的回答。
  • 我尝试了这两种解决方案,但总是返回 0,即使是结果中没有的随机数... :( 也许我的查询在某种程度上是错误的?
  • 可能是您的代码中的问题$postcode_q = mysqli_real_escape_string($mysqli, $_POST['postcode_locator_search']); $postcode_q = htmlentities($postcode_q);
  • 没有错误,无论我在搜索中输入什么,console.log(data) 总是返回 0
  • 你能print_r($results); 吗?在 if 和 else 语句之外?
【解决方案2】:

使用mysqli_num_rows检测是否有结果

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

我建议将其分为两个 if 条件,以便您将错误与没有结果的查询分开处理

【讨论】:

  • 我试过了,但和其他答案一样,我输入了一些不是有效结果的东西,而应该是并且都返回有效的东西?
  • 什么无效?当您期望它失败时回显您的查询并查看它实际查询的内容
  • 回显您的查询echo "SELECT description FROM cscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1"
  • 我认为查询错误,我收到错误我需要在表 cscart_postcode_location_descriptions 中搜索列描述
  • 如果我从 cscart_postcode_location_descriptions WHERE description LIKE '6060' LIMIT 1 中选择描述;如果我喜欢 'dddddddd' 则返回结果不......所以工作就像那样......我需要改变什么?
猜你喜欢
  • 2011-09-26
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2017-02-11
  • 2014-03-20
  • 2011-06-28
  • 1970-01-01
相关资源
最近更新 更多