Jump to content

Recommended Posts

Hello people,

 

I'm working with an autocomplete script, which is actually working.

I've got 2 problems though, the first problem should be very easy but I'm really noobish.

I don't know how to fill my array correctly, right now it seems that I'm filling my array with just 1 result, instead of all results.

 

The second problem is, although it's actually working, an error log is created everytime I use the autocomplete box.

Error: [30-Jul-2010 18:19:29] PHP Warning:  Invalid argument supplied for foreach() in /home/admin/public_html/adminpanel/autocomplete/search-artistnames.php on line 79

 

 

I really could use some help here, I'm lost atm. I hope you guys have the answer for me.

The code:

<?php
$link = mysql_connect('localhost', '****', '****');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db(' ****')) {
    exit;
}

$text = strtolower($_GET["term"]);
if (!$text) return;
$sql = "SELECT artistID, artistname FROM artists WHERE artistname LIKE '%".mysql_real_escape_string($text)."%' LIMIT 5";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) 
{
$items = array($row['artistname'] => $row['artistID']);
}

function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = "\"".addslashes($key)."\"";

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "\"".addslashes($value)."\"";
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $text) !== false) {
	array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
	break;
}
echo array_to_json($result);


mysql_close($link);
?>

I don't know how to fill my array correctly, right now it seems that I'm filling my array with just 1 result, instead of all results.

Add square brackets after $items on this line

$items = array($row['artistname'] => $row['artistID']);

So its

$items[] = array($row['artistname'] => $row['artistID']);

 

Now $items will be a multidimensional array of results from your query. Otherwise you're just redefined $lists variable.

I don't know how to fill my array correctly, right now it seems that I'm filling my array with just 1 result, instead of all results.

Add square brackets after $items on this line

$items = array($row['artistname'] => $row['artistID']);

So its

$items[] = array($row['artistname'] => $row['artistID']);

 

Now $items will be a multidimensional array of results from your query. Otherwise you're just redefined $lists variable.

 

Thanks but now it returns nothing anymore at the end. Do I have to alter this line too in some way?

foreach ($items as $key=>$value)

Try this:

 

$result = array();
foreach ($items as $item) {
if (strpos(strtolower($item[0]), $text) !== false) {
	array_push($result, array("id"=>$item[1], "label"=>$item[0], "value" => strip_tags($item[0])));
}
if (count($result) > 11)
	break;
}

Try this:

 

$result = array();
foreach ($items as $item) {
if (strpos(strtolower($item[0]), $text) !== false) {
	array_push($result, array("id"=>$item[1], "label"=>$item[0], "value" => strip_tags($item[0])));
}
if (count($result) > 11)
	break;
}

 

Doesn't return anything :(

This thing is really eating me alive...  :shrug:

Before the foreach() place this:

 

echo "<pre>" . print_r($items, true) . "</pre>";

 

and post the output.

 

Edit: Why are you defining your own function to convert the array to a JSON representation? Why don't you just use json_encode?

In your original script, I would suggest changing:

//This line:
$items = array($row['artistname'] => $row['artistID']);
//To this:
$items[$row['artistname']] = $row['artistID'];

 

Leaving the rest as it is, and see how it works.

In your original script, I would suggest changing:

//This line:
$items = array($row['artistname'] => $row['artistID']);
//To this:
$items[$row['artistname']] = $row['artistID'];

 

Leaving the rest as it is, and see how it works.

 

Thanks but, doing that I get this error

[31-Jul-2010 08:55:06] PHP Parse error:  syntax error, unexpected T_DOUBLE_ARROW in /home/admin/public_html/adminpanel/autocomplete/search-artistnames.php on line 17

 

Which is the line we just changed

Before the foreach() place this:

 

echo "<pre>" . print_r($items, true) . "</pre>";

 

and post the output.

 

 

So I've done that while entering the characters 'NI', and there are 2 artists with NI in their names.

 

 

Array

(

    [sirenia] => 10

)

[ { "id": "10", "label": "Sirenia", "value": "Sirenia" } ]

 

Which actually should include Nickelback => 8, so my array isn't being filled properly. :(

So here's how the deal is right now.

 

The array is filled with the following

Array

(

    [0] => Array

        (

            [Nickelback] => 8

        )

 

    [1] => Array

        (

            [Nightwish] => 15

        )

 

    [2] => Array

        (

            [sirenia] => 10

        )

)

 

Which is correct, so hooray for that.

But the foreach is giving problems, the foreach is giving an empty array.

foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $text) !== false) {
	array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
	break;
}

Is returning: []

That's because you're looping through the array in the wrong way. Each loop in $key will be 0, 1, 2, ... and $value will be an array. Instead try the loop I suggested before:

 

$result = array();
foreach ($items as $item) {
if (strpos(strtolower($item[0]), $text) !== false) {
	array_push($result, array("id"=>$item[1], "label"=>$item[0], "value" => strip_tags($item[0])));
}
if (count($result) > 11)
	break;
}

 

or change the way the $items array is constructed like jcbones suggested.

 

Thanks but, doing that I get this error

[31-Jul-2010 08:55:06] PHP Parse error:  syntax error, unexpected T_DOUBLE_ARROW in /home/admin/public_html/adminpanel/autocomplete/search-artistnames.php on line 17

 

Which is the line we just changed

 

I suspect you thought I missed an arrow, but I didn't.

 

//Incorrect:
$items[$row['artistname']] => $row['artistID'];
//Correct:
$items[$row['artistname']] = $row['artistID'];

 

This would be the only reason, that I can think of, for PHP to see a double arrow on that line.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.