2

您是否知道如何从 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;

我必须提出数组,但我不知道该怎么做。任何帮助都非常感谢。谢谢。

4

1 回答 1

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;
于 2012-12-18T08:52:16.373 回答