0

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 />";
}
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • Change `$colsq = mysql_query($q);` with `$colsq = mysql_query($q) or die(mysql_error());` and probably you will see error. – Narek Mar 29 '13 at 12:50

2 Answers2

5

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • Thanks captain. They're not even currently working on PHP6 and even when they do it will be months if not years before the majority of people switch to it. i think i'm safe. – I wrestled a bear once. Mar 29 '13 at 16:40
1

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 />";
}
Suhel Meman
  • 3,702
  • 1
  • 18
  • 26