简体   繁体   中英

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...

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.

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.

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:

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:

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.

Your problem comes from the SQL query you generate. I would suggest you get your query out of PDO and try it in phpmyadmin or mysql console. If it works there, then your php script is not generating the sql properly. 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.

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. 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.

What happens when you print_r($result) after the above loop? What happens when you print_r($search_results) before this loop? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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