0

So I've been struggling with my database to get it to give me the name of columns contained within a table.

Here's my PHP :

  $sql = "SELECT * FROM hacklvrf_db.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'generators'" ; 
  $result = mysqli_query($con, $sql); 
  $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
  $generators = $row['generators'];
  foreach ($row as $lol) {
  echo ($lol);
  }

For some reason this isn't answering with anything (PHP doesn't pop an error but my variables seem to be empty) and I don't really understand what I'm missing.

  echo (gettype ($row));

Shows a 'NULL'

I know this question has been asked before and I actually got my SQL query from other places but I since I can't work it out... here I am !

Thanks in advance guys !

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
taze totero
  • 199
  • 1
  • 1
  • 8

1 Answers1

2

Change

$sql = "SELECT * FROM hacklvrf_db.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'generators'";

To

$sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='database-name' AND `TABLE_NAME`='table-name'";

Used your sql query after changing database name and table name, I got error

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.COLUMNS WHERE TABLE_NAME

Updated Code (Just put your database name and table name in query)

<?php
$sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='database-name' AND `TABLE_NAME`='table-name'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
  echo $row['COLUMN_NAME']."<br>";
}

?>

For more info, click MySQL query to get column names?

Community
  • 1
  • 1
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
  • I'll do that right now and update, thanks for your help! – taze totero Aug 17 '16 at 12:17
  • Works flawlessly! Thank you a lot! Any chance you could quickly explain why the first way didn't work ? (it looks like it's pretty much the same thing) Thanks again! – taze totero Aug 17 '16 at 12:21
  • I don't have much idea to it. I tried your query in my system and it gave me error which I posted in my answer. So, I searched it and got new query which I posted as link in my answer too. Go through it. There you will get a better explanation. *Glad It Worked.* @tazetotero – Nana Partykar Aug 17 '16 at 12:23