ravi
ravi

Reputation: 109

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

I wanted to arrange the array of table list with sort() function but i am getting same kind of warning.

<?php 
require_once("lib/connection.php"); 

$result = mysql_query("SHOW TABLES FROM `st_db_1`");
 
sort($result);
foreach ($result as $result){
    echo $result ;
} 
?>

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

Upvotes: 0

Views: 28767

Answers (5)

vbence
vbence

Reputation: 20333

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.

Upvotes: 0

Trott
Trott

Reputation: 70065

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";
 }

Upvotes: 2

Raffael Luthiger
Raffael Luthiger

Reputation: 2211

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;
}

Upvotes: 2

Spudley
Spudley

Reputation: 168655

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.

Upvotes: 1

vindia
vindia

Reputation: 1678

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() https://www.php.net/mysql_query

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

Upvotes: 2

Related Questions