jQuery Autocomplete从mysql DB获取提要

时间:2012-12-18 08:34:53

标签: php javascript jquery arrays

您是否知道如何从mysql中提取数据,将其放入数组中然后将其提供给自动填充字段?

我尝试过硬编码的值,但我在想的是当我添加新记录时,我必须重新编码数组。我是PHP的新手,所以请原谅。

请检查我到目前为止所尝试的内容:

protected function jsGenerateResourcesAutocomplete(){


    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';

    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }

    $sql = "SELECT employee_name FROM employee" ;

    mysql_select_db('test', $conn);
    $retval = mysql_query($sql);

    $row = mysql_fetch_assoc($retval); 


    if(!$retval )
    {
        die('Could not select data: ' . mysql_error());
    } 

    $employeeNames = $this->employeeNames;
    $html = "";     $html .= 'var employeenames = [' . PHP_EOL;
    foreach ($employeeNames as $employeeName) {
        $html .= '"' . $employeeName-> $array . '",' . PHP_EOL;
    }
    $html .= '];';
    $html .= '$(".resource-input input").autocomplete({source: employeenames});' .PHP_EOL;
    $html .= '});' . PHP_EOL; 
    $html .= '</script>' . PHP_EOL;
    return $html;
} 

我相信这一行:

$html .= '"' . $employeeName-> $array . '",' . PHP_EOL;

我必须提出阵列,但我不知道该怎么做。真的很感激任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

$sql = "SELECT employee_name FROM employee" ;

mysql_select_db('test', $conn);
$retval = mysql_query($sql);

if(!$retval )
{
    die('Could not select data: ' . mysql_error());
} 
$data = array();

while($row = mysql_fetch_array($retval)){
  $data[] = $row['employee_name'];
}

$html = "<script>";
$html .= 'var employeenames = '.json_encode($data);
$html .= '$(".resource-input input").autocomplete({source: employeenames});';
$html .= '});'; 
$html .= '</script>';
return $html;