PHP: Warning: sort() expects parameter 1 to be array, resource given [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I wanted to arrange the array of table list with sort() function but i am getting same kind of warning my code as follows :

 

and the warning i am getting are :

Warning: sort() expects parameter 1 to be array, resource given in C:\wamp\www\Copy (4)       of st_db_1\test_2.php on line 9 Warning: Invalid argument supplied for foreach() in C:\wamp\www\Copy (4) of st_db_1\test_2.php on line 10 

回答1:

The warning is pretty clear: mysql_query does not return an array with results from the query, but a resource. You need a function like mysql_fetch_array() to return the data you need (and on which you can perform a sort operation).

See the manual for the use of mysql_query() http://nl3.php.net/mysql_query

And maybe unrelated, but you can sort your results in MySQL right away by adding ORDER BY to your query.



回答2:

The variable $result is only a resource of the type result. You need to fetch then the data from the result set with e.g. mysql_fetch_assoc().

$result = mysql_query("SHOW TABLES FROM `st_db_1`"); $array = array(); while ($row = mysql_fetch_assoc($result)) {     $array[] = $row["Tables_in_st_db_1"]; } sort($array); foreach ($array as $item) {    echo $item; } 


回答3:

I'm not providing the most efficient code imaginable, but this should make it clear what's going on and solve your problem:

 $result = mysql_query("SHOW TABLES FROM `st_db_1`");   $my_array_of_table_names = array();  while ( $row = mysql_fetch_array($result, MYSQL_NUM)) {      $my_array_of_table_names[] = $row[0];  }  sort($my_array_of_table_names);   foreach ($my_array_of_table_names as $table_name){      echo "$table_name\n";  } 


回答4:

Your problem is that you aren't actually getting the data from the query.

mysql_query() doesn't give you a recordset.

What it does is query the database and returns a database resource which you can then use to get the data.

What you need is after calling mysql_query(), you then need to also call mysql_fetch_array() or similar. (there are a range of functions available, but that's probably the best one to use in this case). Then sort() the data from that, not $result.



回答5:

It clearly says: it expects an array and you pass something else.

If you had checked the type of $result you would have seen that it is not an array, intead a resource.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!