我有一個php函數,它將從users
數據庫的列中獲得名稱列表。我想要做的是從列name
中獲取所有值並將其插入到數組中。使用mysql查詢從單列返回值
我從PHP端所做的是:
header('Content-type: application/json');
include ('../Core/Initialization.php');
$courseName = $_POST['courseName'];
$semester = $_POST['semester'];
$sql = mysql_query("SELECT DISTINCT `name` FROM `users` WHERE `programme` = '$courseName' AND `semester` = '$semester'") or trigger_error(mysql_error().$sql);
$column = mysql_fetch_assoc($sql);
$arr = array();
foreach($column as $value) {
$arr[] = array('name' => $value['name']); //I have tried it this way but it didn't work when I try to display the values.
}
echo json_encode($arr);//I have tried to remove the array and just json_encode($column). I have successfully print out the first values, but fail to print out the next values collected from the column.
JS的功能,將處理/打印出了名:
function nameProcess(data) {
alert(data.name); //This will only display the full values from the first(?) index
nameArray = data.name;
for (var i=0; i < nameArray.length; i++) {
alert(nameArray[i]); //But, this loop only displays one character each time of the alert. Example: Each character from the word "Hello" will show up one by one as alert.
}
}
});
有沒有什麼更好的方法來做到這一點?我想要做的是,將列name
中的所有值導出到數組中,並將其每個值作爲選擇框的選項進行迭代。但現在,我該如何解決這個問題?
**警告**:如果您只是學習PHP,請不要使用['mysql_query'](http://php.net/manual/en/function.mysql-query.php)界面。這是非常可怕和危險的,在PHP 7中被刪除了。[PDO的替代品並不難學](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps- pdo-for-database-access /)和[PHP The Right Way](http://www.phptherightway.com/)等指南介紹了最佳實踐。你的用戶參數是**不是** [正確轉義](http://bobby-tables.com/php),並且有[SQL注入漏洞](http://bobby-tables.com/)可以被利用。 – tadman