尝试使用mysql结果集在while循环中构建数组的PHP语法错误[关闭]

尝试使用mysql结果集在while循环中构建数组的PHP语法错误[关闭]

问题描述:

Why do I get an unexpected ']' error on the $columnArray[]... line?

<?php

$con=mysqli_connect("localhost","user","password","test");
if (mysqli_connect_errno($con))  { echo "Failed to connect to MySQL: " . mysqli_connect_error();}

 $sql = "SELECT column_comment,column_name FROM information_schema.columns  
  WHERE table_name = 'mytable'; 
 $query = mysqli_query($con,$sql) or die(mysql_error());
 $columnArray = array();

 $columnArray = array();

 while($result = mysqli_fetch_array($query)){


   $columnArray[] = array('column_comment' => $result['column_comment'], 'column_name' => $result['column_name']);

 }

PHP Parse error: syntax error, unexpected ']', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

Even StackOverflow's syntax highlighting shows that you got your code broken. You need to close query string, so instead of:

$sql = "SELECT column_comment,column_name FROM information_schema.columns 
        WHERE table_name = 'mytable'; 

you need:

$sql = "SELECT column_comment,column_name FROM information_schema.columns  
        WHERE table_name = 'mytable'"; 

Get yourself something better than Notepad :)

The syntax highlighting shows you the error. You're missing a closing quote:

 $sql = "SELECT column_comment,column_name FROM information_schema.columns  
  WHERE table_name = 'mytable';

should be

 $sql = "SELECT column_comment,column_name FROM information_schema.columns  
  WHERE table_name = 'mytable'";

replace old query with this..

 $sql = "SELECT column_comment,column_name FROM information_schema.columns WHERE table_name = 'mytable'";