php/mysql get all tables and columns in a database - php

i want to check a database and get all table names first and then
show some kind of report from data inside each table
$query = $db3->query("SELECT `table_name` from INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db3' ") or die("$db3->error");
while ( $table = $query->fetch_assoc() )
{
//echo $table['table_name'].'<br />';
$t = trim($table['table_name']);
//i get all table names now i want to select all columns from that table name :
$select = $db3->query("SELECT * FROM ".$t." ") or die($db3->error);
$row = $select->fetch_assoc();
// checking to see if query worked fine
echo gettype($row);
//it returns NULL
}
am i doing it the right way ?
what should i do ?

For security reasons you should have a whitelist of databases/tables you want to generate reports from. Querying for all tables assumes that all future tables will need to be part of this system.
You can query for the columns in each table using show columns from tableName and iterate the results.

You can use this query in mysql
mysql> SELECT table_name, table_type, engine
-> FROM information_schema.tables
-> WHERE table_schema = 'db5'
-> ORDER BY table_name DESC;

SELECT table_name, column_name FROM Information_schema.columns WHERE table_name like '%example%' ORDER BY table_name DESC
Or you can try this
SELECT table_name, column_name FROM Information_schema.columns WHERE column_name like '%example%' ORDER BY table_name DESC

Related

sql - How Can I truncate Multiple Tables in MySql?

$tblarray = array("abc1","abc2","abc3");
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE table_type ='base table' and TABLE_CATALOG='mydb' order by TABLE_NAME";
$res = mssql_query($sql);
while($rowTable = mssql_fetch_array($res))
{
if(in_array($rowTable['TABLE_NAME'],$tblarray))
{
$sqlDel = "SELECT DISTINCT concat('TRUNCATE TABLE',TABLE_NAME,';')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'abc%' AND TABLE_SCHEMA = 'mydb'";
$res_sqlDel = #mssql_query($sqlDel);
}
}
First I get all the tables name from database then truncate specific tables. But this code not working properly.
select Table_name from information_schema.tables where table_schema='YOUR_DB_NAME';
Will return all the table names
1) Iterate over the result set.
2) Create another sql query like
$query= "truncate table ".$resultSetRow['Table_name'];
Execute it in the loop. Basically it will iterate over result set and truncate all the tables one by one.

How to select data from columns that match a criteria?

Hi i have a table in mysql database which has columns like UI_12-Apr-2016,DA_12-Apr-2016.
----------------------------------------------------------------------
| DA_12-Apr-2016 | UI_13-Apr-2016 | UI_12-Apr-2016 | DA_13-Apr-2016 |
|---------------------------------------------------------------------
| |
----------------------------------------------------------------------
How do i fetch data from the table whose columns have 12-Apr-2016 in it. Is there any way to select data according to the criteria. I know i can run this query:-
SELECT UI_12-Apr-2016,DA_12-Apr-2016 from table;
but the date and the code before it can be anything. I want to create a dynamic query to fetch data from the columns that match the date criteria.
I would be highly grateful if anyone can please provide a solution to do it.
This may help:
select COLUMN_name
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='Table1' and column_name like "%12-Apr-2016%";
in the above query, we can search for column names from INFORMATION_SCHEMA.COLUMNS table(which holds data related to table specified).
Output of above query should:
UI_12-Apr-2016
DA_12-Apr-2016
The result of above query is a list of columns with the pattern given(%12-Apr-2016%). You may save this result in a list and use it to fetch data accordingly from the table.
There is no direct method or query to do the same.
maybe you can create a new table tbl_column with one column column_name include all your columns~
SELECT * FROM tbl_column WHERE column_name LIKE '%12-Apr-2016%';
then you can use the query result to generate a new dynamic sql~
Did you mean:
SELECT * FROM table WHERE column LIKE '%13-Apr-2016%';
?
Update: you should look into information_schema database:
SELECT COLUMN_NAME from `COLUMNS` where `TABLE_NAME` = 'table_name' AND `COLUMN_NAME` LIKE '%12-Apr-2016%';
Simple PHP example script could be:
$table_name = 'table_name';
$col_pattern = '12-Apr-2016';
$mysqli = new mysqli($config['host'], $config['user'], $config['password'], $config['dbname']);
$sql1 = "SELECT COLUMN_NAME from `COLUMNS` where `TABLE_NAME` = '{$table_name}' AND `COLUMN_NAME` LIKE '%{$col_pattern}%'";
$res1 = $mysqli->query($sql1);
$acol = array();
while ($r1 = $res1->fetch_assoc()) {
$acol[] = $r1['COLUMN_NAME'];
}
if (!empty($acol)) {
$sql2 = 'SELECT ' . implode(', ', $acol) . ' FROM ' . $table_name;
$res2 = $mysqli->query($sql2);
while ($r2 = $res2->fetch_assoc()) {
echo var_export($r2, 1) . PHP_EOL;
}
}
You must put together your SQL statement dynamically. E.g. the following statement uses the Oracle view ALL_TAB_COLUMNS to produce a select column_name from table_name statement for every column that contains 12-Apr-2016:
SELECT 'SELECT ' || COLUMN_NAME || ' FROM ' || TABLE_NAME || ';'
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'MY_TABLE'
AND COLUMN_NAME LIKE '%12-Apr-2016%'
This may not be exactly what you want, however, this illustrates the general idea.
It is not possible to dynamically come up with names of columns since MySQL does not have an eval() function. Since you are using PHP, it is preferable to construct the query from your application in order to achieve this.
If you really insist for a solution using MySQL, there is one using prepared statements that is not too hard to come up with as follows:
set #table='your_table_name';
select group_concat(column_name)
from information_schema.columns
where table_name='your_table_name'
and column_name like '%12_Apr_2016'
into #colnames;
set #construct= CONCAT('SELECT ', #colnames, ' FROM ', #table);
prepare query from #construct;
execute query;
SQL Fiddle for reference.
But overall, having columns named using dynamically generated DDL is not the best schema modeling practice.

Retrieve database table comments in CodeIgniter

I have created a database table in PHPMyAdmin with table comments. I plan to use the table comments to store table version. I want to retrieve the table comments in CodeIgniter database mysql driver.
I tried to execute the query via the query method:
SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='{$table}' AND table_name='{$database}';
but the it returns nothing. Is there any workaround or proper way to do this?
Thank you!
Try this
$query = "SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_SCHEMA = '{$database}' AND TABLE_NAME = '{$table}'";
$result = $this->db->query($query);
print_r($result);
And your query is not executing because you have a typo within your query
TABLE_SCHEMA = '{$table}'
needs to be
TABLE_SCHEMA = '{$database}'
and
TABLE_NAME = '{$database}'
needs to be
TABLE_NAME = '{$table}'

How to SELECT DEFAULT value of a field

I can't seem to find or write a sqlquery that SELECTS the DEFAULT VALUE
(and I don't think I can generate it in phpmyadmin for me to copy)
I tried to SELECT it as if it was a record but to no avail...
$defaultValue_find = mysql_query(
"SELECT $group FROM grouptable WHERE $group='DEFAULT'")
or die("Query failed:".mysql_error());
$defaultValue_fetch = mysql_fetch_row($defaultValue_find);
$defaultValue = $defaultValue_fetch[0];
echo $defaultValue;
"SELECT $group FROM grouptable WHERE $group=DEFAULT( $group ) "
Or I think better:
"SELECT DEFAULT( $group ) FROM grouptable LIMIT 1 "
Update - correction
As #Jeff Caron pointed, the above will only work if there is at least 1 row in grouptable. If you want the result even if the grouptable has no rows, you can use this:
"SELECT DEFAULT( $group )
FROM (SELECT 1) AS dummy
LEFT JOIN grouptable
ON True
LIMIT 1 ;"
Get the default values of all fields in mytable in the associative array $res:
// MySQL v.5.7+
$res = [];
$sql = "SHOW FULL COLUMNS FROM `mytable`";
foreach ($PDO->query( $sql, PDO::FETCH_ASSOC ) as $row) {
$res[$row['Field']] = $row['Default'] ;
}
print_r($res);
You can get the default column of any table, and in fact lots of interesting information about it, by looking at the INFORMATION_SCHEMA.COLUMNS tables. As the documentation states...
INFORMATION_SCHEMA provides access to database metadata, information about the MySQL server such as the name of a database or table, the data type of a column, or access privileges. (Source: MySQL 8.0 Reference Manual / INFORMATION_SCHEMA Tables / Introduction.)
So, to get the column default, just SELECT COLUMN_DEFAULT, like...
SELECT COLUMN_DEFAULT
FROM information_schema.columns
WHERE TABLE_SCHEMA = 'YourSchema'
AND TABLE_NAME = 'YourTable' AND
COLUMN_NAME = 'YourField';
You can then just wrap this into a subquery, SELECT * FROM YourTable WHERE YourField = (queryabove). This lets you make a much more customizable, default-based list in your MySQL query.

Need to find out of a table has certain columns before running alter table

I am writing a plugin for wordpress. When the plugin is initialised I need to find out if the users table contains the columns I am trying to insert to ensure I am not overwriting anything. Can someone provide me with the syntax that does this; I think it looks something like this:
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
Thanks
If you're just trying to find out if the column exists, I'd do
SELECT 1
FROM information_schema.COLUMNS
WHERE COLUMN_NAME = 'column_name'
AND TABLE_NAME = 'table_name'
AND TABLE_SCHEMA = 'database_name'
LIMIT 1
pseudocode:
DBQuery("SHOW COLUMNS FROM ".$table);
while (DBGetRow())
{
$columns[]=$access["Field"];
}

Categories