PHP
$table = $_REQUEST['table'];
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = $table";
$result = mysql_query($query);
$i = 0;
$arr = array();
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr[$i] = $row['COLUMN_NAME'];
$i++;
}
echo json_encode($arr);
Javascript
$("#verticalSelect").change(function() {
var table = $("#verticalSelect option:selected").attr('value');
$.post(PROCESSORFILE, {"task": "getTableDupeFields", "table": table}, function(data) {
alert(data);
}, "json");
});
I want take the array $arr from php and pass it to javascript where I can print its contents one by one. So far the code I have and variations of have returned errors, resource Id’s and often just nothing at all.
How can this be done in the most trite way?
Firstly, what’s wrong:
You’re specifying
MYSQL_NUM, which instructsmysql_fetch_array()to return a numeric array. With that flag set, you’d access the first value as$row[0]. To get an associative array and access the fields by name, you can either usemysql_fetch_assoc()instead, not pass any flag tomysql_fetch_array(), or pass itMYSQL_ASSOC.Also, the
$ivariable you’re using is unnecessary – you can append elements to an array without specifying an index, like so:Finally, your script is open to SQL injection when you insert a
$_REQUESTvariable directly into your sql. At the very least, you should runmysql_real_escape_string()on the value before adding it to the SQL.