I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

MYSQL returning tables with PHP

I'm confused as to how this works...

I'm trying to assign the table column names into an array in php. I'm trying to do it the same way I do any other query but it's not working. Please tell me what I'm doing wrong.

$q ="SHOW COLUMNS FROM disp";
$colsq = mysql_query($q);
$c = mysql_fetch_assoc($colsq);
foreach($c['Field'] as $asdf){
    echo $asdf."<br />";
}

Upvotes: 0

Views: 81

Answers (2)

Rikesh
Rikesh

Reputation: 26421

You are doing it wrong, try this.

$q = "SHOW COLUMNS FROM disp";
$colsq = mysql_query($q) or die(mysql_error()); 
while ($row = mysql_fetch_assoc($colsq)) {
     echo $row['Field']."<br/>";
}

Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Upvotes: 5

Suhel Meman
Suhel Meman

Reputation: 3852

use mysqli instead of mysql. try this :

$mysqli = new mysqli($db_host,$db_user,$db_password,$db_name);
if ($mysqli->connect_errno) 
{
   echo "Failed to connect to MySQL:(".$mysqli->connect_errno.")" .$mysqli->connect_error;
}

$q ="SHOW COLUMNS FROM disp";
$res=$mysqli->query($q);

while($data=$res->fetch_assoc())
{
    echo $data['Field']."<br />";
}

Upvotes: 1

Related Questions