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);
?>