简体   繁体   English

PHP PDO AJAX查询无法正常工作,我的视线在交叉

[英]PHP PDO AJAX Query not working, my eyes are crossing

I am re-writing a file that will dynamically build queries to search and match any word in an string passed by an ajax event... 我正在重新编写一个文件,该文件将动态生成查询以搜索和匹配由ajax事件传递的字符串中的任何单词。

I cannot get the thing to return data. 我无法得到返回数据的东西。 It acts like everything worked perfectly, but it didn't. 它的行为就像一切正常,但事实并非如此。 All I get in firebug is success: true..which is good because that means there wasn't an error but my SQL results aren't being passed. 我在firebug中得到的只是成功:true ..这很好,因为这意味着没有错误,但是我的SQL结果没有通过。

I know this code is going to be all over the place for you guys, but it doesn't work... 我知道这些代码将会为你们所有人提供,但它不起作用......

I've spent most of the day re-working this code so its not pretty or perfect yet, I just want it to return search results again... 我花了整整一天的时间重新处理这段代码,所以它还不是很漂亮或完美,我只想让它再次返回搜索结果...

Bill, if you are reading this, I didn't get a chance to look into the %LIKE alternatives you suggested last week ha...still waiting on your book in the mail. 比尔,如果你正在读这篇文章,我没有机会研究你上周建议的%LIKE替代方案......还在等你邮寄的书。

Sorry to dump a ton of code on you guys but I just can't see what's wrong here. 抱歉在您身上丢了很多代码,但是我看不到这里有什么问题。

function CreateOptions($columns, $num_elements, $condition="AND") {
$colcount = count($columns);
$optionString = " ";

for ($ii=0; $ii < $num_elements; $ii++) {
    if ($ii > 0)
        $optionString .= " AND (";

    for ($i=0; $i<$colcount; $i++) {
        if ($i>0)
            $optionString .= " OR ";

        $optionString .= $columns[$i] . " LIKE '%:search$ii%'";
    }

    //$optionString .= ")";
}

return $optionString;
}

include_once('../sys/core/init.inc.php');

$json = array();
$result = array();


if (isset($_POST['searchTerm'])){
try {
        $search = trim($_POST['searchTerm']);
    $search = preg_replace('/\s+/', ' ', $search);
    $search = explode(" ", $search);
    $num_search_elements = count($search);

    switch($_POST['category']) {
        case ("account"):
        $querySyntax = "SELECT
                            idAccount, 
                FirstName,
                LastName,
                Email,
                Phone,
                CCCity,
                db_name.states.Abbreviation 
                FROM
                    db_name.account Right Join
                                    db_name.states On  
                                    db_name.account.CCState =
                                    db_name.states.ID 
                    WHERE";

            $cols = Array ("FirstName", "LastName", "Phone", "Email", "idAccount"); 


            $querySyntax .= CreateOptions($cols, $num_search_elements);

            break;
                        default:
                            break;
                    }

                    $querySyntax .= " LIMIT 50";


                    // Build and run query (change to execute)
                    $dbs = $dbo->prepare($querySyntax);

                    for($i=0; $i<$num_search_elements; $i++) {
                        if ($dbs->bindValue(":search$i", $search[$i], (is_int($search[$i]) ? PDO::PARAM_INT : PDO::PARAM_STR))) {
            // yea i know... nothing here its all below still
        } else {
            die("BIND_ERROR");
        }
    }

    $dbs->execute();

    // Put the array together
    $search_results = $dbs->fetchAll(PDO::FETCH_ASSOC);
    //print_r($search_results);
    foreach($search_results as $col=>$val) {
        $result[$i][$col] = $val;
        $i++;
        //echo "$col >> $val";
    }           

    $stmt = null;
    $result["success"] = true;




}
catch (PDOException $e) {
    $result["success"] = false;
    $result["error"] = $e->getMessage() . " >> SQL: $querySyntax";

}



} else {
$result["success"] = false;
$result["error"] = "INVALID DATA";
}

header('Content-type: application/json');

echo json_encode($result);

Here is the generated SQL taken straight from Firebug when I tell it to echo the query: 这是我告诉Firebug回显查询时直接从Firebug中获取的SQL:

SELECT
idAccount,
FirstName,
LastName,
Email,
Phone,
CCCity,
db_name.states.Abbreviation
FROM
db_name.account Right Join
db_name.states On db_name.account.CCState =
    db_name.states.ID 
WHERE 
FirstName LIKE '%:search0%' OR 
LastName LIKE '%:search0%' OR
phone LIKE '%:search0%' OR 
email LIKE '%:search0%' OR 
idAccount LIKE '%:search0%' 
LIMIT 50

replace :search0 with "mar" you get this from my db in terminal and phpmyadmin: 用“mar”替换:search0你从终端和phpmyadmin的db中得到这个:

1   Mar     <my real name> myemail@email    1231231234  City    FL
2   Martin  Short   mshort@movies.com   2147483647  Beverly Hills   CA
4   Martin  Short   mshort@email.com    2146791243  Beverly Hills   CA
5   Martin  Short   mshort@movies.coms  2146791243  Beverly Hills   CA

Try using: 尝试使用:

header('Content-Type: text/javascript');

Check your http results using something like Firebug/Network view - it might be returning correctly, just isn't getting parsed in Javascript. 使用Firebug / Network视图之类的内容检查您的http结果-它可能会正确返回,只是没有在Javascript中进行解析。

Your problem comes from the SQL query you generate. 您的问题来自您生成的SQL查询。 I would suggest you get your query out of PDO and try it in phpmyadmin or mysql console. 我建议您从PDO中获取查询,然后在phpmyadmin或mysql控制台中尝试。 If it works there, then your php script is not generating the sql properly. 如果它在那里工作,那么你的PHP脚本没有正确生成SQL。 If it's that case it'll be a lot of help if you show us the real sql query and the results from your database. 如果是这样的话,如果您向我们展示真实的sql查询和数据库中的结果,将会有很多帮助。

Edit: Try replacing this: 编辑:尝试替换此:

for ( $i = 0; $i < $num_search_elements; $i++ ) {
    if ( $dbs->bindValue(":search$i", $search[ $i ], (is_int($search[ $i ]) ? PDO::PARAM_INT : PDO::PARAM_STR)) ) {

With this 有了这个

for ( $i = 0; $i < $num_search_elements; $i++ ) {
    $var = ":search".$i;
    if ( $dbs->bindValue($var, $search[ $i ], (is_int($search[ $i ]) ? PDO::PARAM_INT : PDO::PARAM_STR)) ) {

And see if it works. 看看它是否有效。

Your problem could be in this line: 您的问题可能在以下行中:

foreach($search_results as $col=>$val) {
    $result[$i][$col] = $val;
    $i++;
    //echo "$col >> $val";
}

At this point in the code $i starts as the value of $num_search_elements, and counts upward from there. 此时,代码$ i从$ num_search_elements的值开始,并从那里向上计数。 It is never re-initialized and set to 0 after a previous loop in the code which uses $i to count up to $num_search_elements. 在代码中使用$ i最多计数$ num_search_elements的上一个循环之后,它永远不会重新初始化并设置为0。

What happens when you print_r($result) after the above loop? 在上面的循环之后print_r($ result)会发生什么? What happens when you print_r($search_results) before this loop? 如果在此循环之前使用print_r($ search_results)会发生什么? Do they match? 他们匹配吗?

The above code could be replaced with: 上面的代码可以替换为:

foreach($search_results as $col=>$val) {
    $result[][$col] = $val;
}

Which will index upward starting from 0. 从0开始向上索引。

它没有工作的共鸣是因为我在''中有绑定的搜索迭代(:search0 ...),它将它变成一个与数据库中的任何东西都不匹配的文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM