MySQL - Get column names from table and display them (using PHP) - php

I want to take the column names from a table and display them, so i can compare them later.
To get the names, i tried:
$entry = mysqli_query($con, 'SHOW COLUMNS FROM table');
and
$entry = mysqli_query($con, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '$db' AND TABLE_NAME = 'table'");
I don't know whether this runs correctly or not, since i don't get an error message there.
If i try to print the contents of $entry via echo, i keep getting errors.
Previously in my code, i print other entries using:
$test = mysqli_query($con, 'SELECT DISTINCT LK_Release FROM table');
while($row = mysqli_fetch_object($test))
{
echo "Releasename: " . "$row->LK_Release". "<br>";
... }
This output works for me.
What i tried to output the columnnames:
while($row = mysqli_fetch_object($entry))
{
echo $row;
}
Any ideas?

Your query is already correct. But you lack something in the fetching:
while($row = mysqli_fetch_object($entry))
{
echo $row->Field . '<br/>';
// ^ access the objects properties
}

The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
You can use DESCRIBE:
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
Or you can use SHOW COLUMNS:
SHOW COLUMNS FROM my_table;

Related

PHP SQL query won't work

I want to get the last time my database was updated, so I use this query in my PHP code:
$query = mysqli_query($mysqli, "SELECT UPDATE_TIME
FROM information_schema.tables
WHERE TABLE_SCHEMA = 'map_db'
AND TABLE_NAME = ".$objects_tab."");
$lastUpdateTime = mysqli_fetch_array($query);
echo "<div id ='lastUpdate'>".$lastUpdateTime."</div>";
For some reason the query won't work, does anyone know whats the problem?
It works when I do other queries so its not the $mysqli connect variable or the table name variable that's wrong.
Table name value should be wrapped in single quotes:
"SELECT UPDATE_TIME
FROM information_schema.tables
WHERE TABLE_SCHEMA = 'map_db'
AND TABLE_NAME = '".$objects_tab."'"
I think that's incorrect. mysql_fetch_array() returns an array of results. You must to modify like this:
$rows = mysqli_fetch_array($query);
echo "<div id ='lastUpdate'>".$rows['lastUpdateTime']."</div>";
Assuming lastUpdateTime as the key in the database.

How do I sort in alphabetical order this SQL query?

I have tried with sort() in front of $new but it won't work, where should I put it?
$new = mysql_query("SHOW COLUMNS FROM Professors");
while($row = mysql_fetch_array($new)) {
$output .= "{$row['Field']}";
echo $output;
}
I have also tried something like this:
$new = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'Professors' ORDER BY column_name";
but, while on my SQL compiler it will sort them correctly, they won't get printed on the page with the exact code above.
Try this, then:
$new = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'Professors' ORDER BY column_name";
while($row = mysql_fetch_array($new)) {
$output = $row['column_name'] . "<br>";
echo $output;
}
You were ordering it correctly and selecting by column name but you weren't getting the correct field names.

Display table names with INFORMATION_SCHEMA.TABLES

I am kinda new to PHP and MySql and I am trying to find a way to echo the table names of my database in my page.
When I use : SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'myDBname'
directly in PHPMyAdmin, I get the results I want but I just don't know I to "echo" it in my page.
This is what I am using at the moment :
$statement = $db->prepare("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'myDBname'");
$row = $statement->fetchAll();
What would be, in your opinion, the best way to display it on my page if I want to eventually echo the result of the query in a dropdown menu ?
This works for me.
$tables = array();
$stmt = $db->query("SHOW TABLES");
while($row = $stmt->fetch(PDO::FETCH_NUM)){
$tables[] = $row[0];
}
var_dump($tables);

Getting the table name of a row from a mysql query that grabs from multiple tables

I have some PHP/MySQL code that pulls data from multiple different tables (using Inner Joins). It looks something like this:
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data)) {
echo $row[1];
}
So the code is simple enough, but what I want to do is echo the table each row is in inside of that while loop, since it could be in one of 2 tables.
I saw there was some old mysql functions like mysql_field_table and mysql_tablename that would do the trick, but they all seem to be deprecated.
Would appreciate any advice on how to accomplish this.
You could select the data with a special identifier for each table instead of using *
select table1.row1 as t1r1, table2.row1 as t2r1,..... from .....
And inside php you could look for the strings t1 and t2 and do stuff accordingly.
What you can do is echo more than one field from your result table (which hopefully now contains information from both the tables.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data))
{
echo $row[1] . " " . $row[2];
}
...and then $row[3] etc...
Or access the column name/field by the column name or alias provided by AS.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($data))
{
echo $row["c_name1"] . " " . $row["c_name2"];
}
Where "c_name1" and "c_name2" are your column names.
Use an AS keyword to rename all columns.
$select_clause = '';
$tables = array('tblA', 'tblB');
foreach($tables as $tbl) {
mysql_query('SHOW COLUMNS FROM ' . $tbl);
while ($row = mysql_fetch_assoc())
$select_clause .= '`'.$tbl.'`.`'.$row['Field'].'` AS `'.$tbl
.'_'.$row['Field'].'`,';
}
$select_clause = substr($select_clause, 0, -1);
mysql_query('SELECT '.$select_clause.' FROM /*...*/ ');

Exclude certain columns from SHOW COLUMNS mysql

I have this query: SHOW COLUMNS FROM mash which works fine in my while loop for building a select element made from table column names. But in my table i have "id" and "tstamp" which i dont want in the select element, is this possible to exclude these columns?
echo "<form action='".$_SERVER['PHP_SELF']."' method='get'>";
connectDB();
$result = mysql_query("SHOW COLUMNS FROM mash") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
closeConn();
echo '</select>';
echo "</form>";
PHP Way:
Use a continue in the while loop, when those fields are fetched, like this:
echo "<form action='".$_SERVER['PHP_SELF']."' method='get'>";
connectDB();
$result = mysql_query("SHOW COLUMNS FROM mash") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result))
{
if($row[0] == 'id' || $row[0] == 'tstamp')
continue;
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
closeConn();
echo '</select>';
echo "</form>";
This will just skip the id and tstamp fields and process all others. continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
MySQL Way:
Remove those fields in the query like this:
SHOW COLUMNS FROM mash WHERE Field NOT IN ('id', 'tstamp');
Yes, it's possible. Instead of using SHOW COLUMNS use INFORMATION_SCHEMA.
INFORMATION_SCHEMA is the ANSI way of extracting metadata from a relational database. In MySQL you can use:
$sql = "select column_name from information_schema.columns c " +
" where c.table_schema = 'db_name' " +
" and c.table_name='table_name' " +
" and c.column_name like 'name%'";
Information Schema has the advantage that is SQLANSI compliant. You can use it in MySQL, PostgreSQL, SQLServer and other relational databases.
You can use LIKE operator.
SHOW COLUMNS FROM mash LIKE "name%"
To see just the "Collation" column that shows up in SHOW FULL COLUMNS from tablename for just one field, it's:
select COLLATION_NAME from information_schema.columns
where TABLE_SCHEMA = 'tableschemaname' and TABLE_NAME = 'tablename' and COLUMN_NAME = 'fieldname';
Ddrop the fieldname in the where, if you want to see that column for all field names.
To see all possible column names that show up from SHOW FULL COLUMNS so that you can select what you want:
select * from information_schema.columns
where TABLE_SCHEMA = 'tableschemaname' and TABLE_NAME = 'tablename' and COLUMN_NAME = 'fieldname';

Categories