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 />";
}
1
  • Change $colsq = mysql_query($q); with $colsq = mysql_query($q) or die(mysql_error()); and probably you will see error. Commented Mar 29, 2013 at 12:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

+1 for being the first person ever to give me a mysqli example instead of just whining about it. i'm still not switching though. see above comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.