how to query the column names of a table - php

Hi guys i need help about displaying a column name of a specific table example i have a table named account and it has account_id, first_name, last_name and stuffs like that what i need is to display the account_id, first_name, last_name and so on and not the data inside that column really need your help.. thanks :)
SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'mydatabase'
that's the code i found while i was researching for answers but i don't know how to excecute this one.. i really have no idea how would i use this to display the column name..

$result = mysql_query("SHOW COLUMNS FROM sometable");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
the result maybe:
Array
(
[Field] => id
[Type] => int(7)
[Null] =>
[Key] => PRI
[Default] =>
[Extra] => auto_increment
)

How about using DESCRIBE
DESCRIBE tablename;
Try it here: http://sqlfiddle.com/#!2/a2581/2823/0

i need is to display the account_id, first_name, last_name and so on and not the data inside that column
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'B'
SQLFiddle Demo

SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME='table';
This should take the columns right from the information schema.

It is recommended to use MySQLi over MySQL in terms of PHP.
You can use mysqli_fetch_field()
$query = "SELECT blah from blah ORDER BY blah LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}

$query= "SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'mytablename' ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {echo "$row[acount_id] $row[first_name] $row[last_name]";}
Use the above to echo all three data from database

Related

order database tables by creation time

hi i want to list all my tables from a database and order them by time, how can i do that so far i can list all my tables from the database but i can't order them by time;
$dbname = "album";
if (!mysql_connect("localhost", "root", "")) {
echo "Could not connect to mysql";
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo "MySQL Error: " . mysql_error();
exit;
}
$sorts = array();
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}"."<br>";
}
mysql_free_result($result);
This may help you:
$sql = "
SELECT create_time, table_name
FROM information_schema.tables
WHERE table_schema = '$dbname'
ORDER BY create_time
";
Also change while loop's inner part as below:
while ($row = mysql_fetch_array($result)) {
echo "Table: {$row['table_name']} - {$row['create_time']} <br/>";
}
Use the information_schema tables
select * from information_schema.columns
order by create_time, column_name, table_name;
Or if you want a more narrow resultset:
select column_name, table_name, data_type, character_maximum_length,
is_nullable, column_default, create_time
from information_schema.columns
order by create_time, column_name, table_name;
this might be the solution
select * from information_schema.columns
order by create_time, column, table;

SQL multiple table query with UNION, how to get table names

I have the following table structure. One table EQUITIES and a table for each row in this table.
EQUITIES table:
id instrument
and tables for every instrument with are all similar to this:
Tables named like EE5367126893 (various names and the names are stored in equities table).
EE5367126893
id chg
EDIT:
My code is BAD. It somehow gets me wrong results and i can't seem to find an error.
<?
//CREATION OF TOP MOVERS
include('connect.php');
$sql = "SELECT * FROM equities";
$result = mysql_query($sql) or die(mysql_error());
$instruments = array();
while ($row = mysql_fetch_array($result)) {
array_push($instruments, $row["instrument"]);
}
$i=0;
foreach($instruments as $instrument) {
$sqlx .= "(SELECT id, chg, vol, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
if ($i<count($instruments)-1){
$sqlx .= " UNION ";
$i++;
}
}
$gsql = $sqlx;
$lsql = $sqlx;
$vsql = $sqlx;
//Gainers
$gsql .= " ORDER BY chg DESC LIMIT 3";
$gresult = mysql_query($gsql) or die(mysql_error());
while ($grow = mysql_fetch_array($gresult)) {
$g[$grow['name']] = $grow['chg'];;
}
print_r($g);
//losers
$lsql .= " ORDER BY chg ASC LIMIT 3";
$lresult = mysql_query($lsql) or die(mysql_error());
while ($lrow = mysql_fetch_array($lresult)) {
$l[$lrow['name']] = $lrow['chg'];;
}
print_r($l);
//most volume
$vsql .= " ORDER BY vol DESC LIMIT 3";
$vresult = mysql_query($vsql) or die(mysql_error());
while ($vrow = mysql_fetch_array($vresult)) {
$v[$vrow['name']] = $vrow['vol'];;
}
print_r($v);
?>
It got me results:
Array
(
[LV0057869] => 0.68
[EE310054309] => 0.00
[EE3100034553] => -5.03
)
Array
(
[LV0054359] => -0.84
[LT0000543337] => -3.83
[LT00453127375] => -4.03
)
Array
(
[EE310054334653] => 791
[EE3100003609] => 58538
[LT000543337] => 33240
)
Its pretty obvious that I'm not getting the the highest, lowest or values with most vol (as -0.84>-5.03).It looks like random values got locked with this query. Where's the catch? Im pretty sure theres something bad with my sql query...
You can add name to select
SELECT id, chg, 'table_name or instrument_name' as inst_name from ...
Example:
$sqlx .= "(SELECT id, chg, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
It seems that vol has got VARCHAR type and rows are sorted by chars not by integers.
Could you provide your table scheme?

MYSQL match text fields

I have a mysql database with around 1.5 million company records(name, country and other small text fields) I want to mark the same records with a flag (for example if two companies with the same name are in USA then I have to set a field (match_id) equal to say an integer 10) and likewise for other matches. At the moment its taking a long time (days) I feel I am not utilizing MYsql properly I am posting my code below, Is there a faster way to do this???
<?php
//Create the table if does not already exist
mysql_query("CREATE TABLE IF NOT EXISTS proj (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
company_id text NOT NULL ,
company_name varchar(40) NOT NULL ,
company_name_text varchar(33) NOT NULL,
company_name_metaphone varchar(19) NOT NULL,
country varchar(20) NOT NULL ,
file_id int(2) NOT NULL ,
thompson_id varchar(11) NOT NULL ,
match_no int(7) NOT NULL ,
INDEX(company_name_text))")
or die ("Couldn't create the table: " . mysql_error());
//********Real script starts********
$countries_searched = array(); //To save record ids already flagged (save time)
$counter = 1; //Flag
//Since the company_names which are same are going to be from the same country so I get all the countries first in the below query and then in the next get all the companies in that country
$sql = "SELECT DISTINCT country FROM proj WHERE country='Canada'";
$result = mysql_query($sql) or die(mysql_error());
while($resultrow = mysql_fetch_assoc($result)) {
$country = $resultrow['country'];
$res = mysql_query("SELECT company_name_metaphone, id, company_name_text
FROM proj
WHERE country='$country'
ORDER BY id") or die (mysql_error());
//Loop through the company records
while ($row = mysql_fetch_array($res, MYSQL_NUM)) {
//If record id is already flagged (matched and saved in the countries searched array) don't waste time doing anything
if ( in_array($row[1], $countries_searched) ) {
continue;
}
if (strlen($row[0]) > 9) {
$row[0] = substr($row[0],0,9);
$query = mysql_query("SELECT id FROM proj
WHERE country='$country'
AND company_name_metaphone LIKE '$row[0]%'
AND id<>'$row[1]'") or die (mysql_error());
while ($id = mysql_fetch_array($query, MYSQL_NUM)) {
if (!in_array($id[0], $countries_searched)) $countries_searched[] = $id[0];
}
if(mysql_num_rows($query) > 0) {
mysql_query("UPDATE proj SET match_no='$counter'
WHERE country='$country'
AND company_name_metaphone LIKE '$row[0]%'")
or die (mysql_error()." ".mysql_errno());
$counter++;
}
}
else if(strlen($row[0]) > 3) {
$query = mysql_query("SELECT id FROM proj WHERE country='$country'
AND company_name_text='$row[2]' AND id<>'$row[1]'")
or die (mysql_error());
while ($id = mysql_fetch_array($query, MYSQL_NUM)) {
if (!in_array($id[0], $countries_searched)) $countries_searched[] = $id[0];
}
if(mysql_num_rows($query) > 0) {
mysql_query("UPDATE proj SET match_no='$counter'
WHERE country='$country'
AND company_name_text='$row[2]'") or die (mysql_error());
$counter++;
}
}
}
}
?>
I would go for pure sql solution, something like :
SELECT
GROUP_CONCAT(id SEPARATOR ' '), "name"
FROM proj
WHERE
LENGTH(company_name_metaphone) < 9 AND
LENGTH(company_name_metaphone) > 3
GROUP BY country, UPPER(company_name_text)
HAVING COUNT(*) > 1
UNION
SELECT
GROUP_CONCAT(id SEPARATOR ' '), "metaphone"
FROM proj
WHERE
LENGTH(company_name_metaphone) > 9
GROUP BY country, LEFT(company_name_metaphone, 9)
HAVING COUNT(*) > 1
then loop through this results to update ids.
I'm not sure what your are trying to do, but what I can see in your code is that you are making a lot of searches in arrays with a lot of data, I think your problem is your PHP code and not SQL statements.
you will need to adjust the group by fields to suit your matching requirements
if your script times out (quite likely due to the large amount of data), set_time_limit(0)
otherwise you can also add a limit of 1000 or something to the $sql, and run the script multiple times as the where clause will exclude any matched rows already processed (but will not keep track of $match_no inbetween calls, so your would need to handle that yourself)
// find all companies that have multiple rows grouped by identifying fields
$sql = "select company_name, country, COUNT(*) as num_matches from proj
where match_no = 0
group by company_name, country
having num_matches > 1";
$res = mysql_query($sql);
$match_no = 1;
// loop through all duplicate companies, and set match_id
while ($row = mysql_fetch_assoc($res)) {
$company_name = mysql_escape_string($row['company_name']);
$country = mysql_escape_string($row['country']);
$sql = "update proj set match_no = $match_no where
company_name = '$company_name', country = '$country';
mysql_query($sql);
$match_no++;
}

Get table column names in MySQL?

Is there a way to grab the columns name of a table in MySQL using PHP?
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;
Or to get column names with comma in a line:
SELECT group_concat(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
[AND table_schema = 'db_name']
[AND column_name LIKE 'wild']
SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']
Reference: INFORMATION_SCHEMA COLUMNS
I made a PDO function which returns all the column names in an simple array.
public function getColumnNames($table){
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
$output = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $row['COLUMN_NAME'];
}
return $output;
}
catch(PDOException $pe) {
trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
}
}
The output will be an array:
Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )
Sorry for the necro but I like my function ;)
P.S. I have not included the class Core but you can use your own class.. D.S.
There's also this if you prefer:
mysql_query('SHOW COLUMNS FROM tableName');
This solution is from command line mysql
mysql>USE information_schema;
In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement
mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND TABLE_NAME='<--TABLENAME-->';
I needed column names as a flat array, while the other answers returned associative arrays, so I used:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names now equals:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
It's also interesting to note that you can use
EXPLAIN table_name which is synonymous with DESCRIBE table_name and SHOW COLUMNS FROM table_name
although EXPLAIN is more commonly used to obtain information about the query execution plan.
How about this:
SELECT #cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
SET #cCommand = CONCAT( 'SELECT ', #cCommand, ' from my_database.my_table;');
PREPARE xCommand from #cCommand;
EXECUTE xCommand;
Look into:
mysql_query('DESCRIBE '.$table);
The MySQL function
describe table
should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
The mysql_list_fields function might interest you ; but, as the manual states :
This function is deprecated. It is
preferable to use mysql_query() to
issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
You may also want to check out mysql_fetch_array(), as in:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}
in mysql to get columns details and table structure by following keywords or queries
1.DESC table_name
2.DESCRIBE table_name
3.SHOW COLUMNS FROM table_name
4.SHOW create table table_name;
5.EXPLAIN table_name
you can get the entire table structure using following simple command.
DESC TableName
or you can use following query.
SHOW COLUMNS FROM TableName
$col = $db->query("SHOW COLUMNS FROM category");
while ($fildss = $col->fetch_array())
{
$filds[] = '"{'.$fildss['Field'].'}"';
$values[] = '$rows->'.$fildss['Field'].'';
}
if($type == 'value')
{
return $values = implode(',', $values);
}
else {
return $filds = implode(',', $filds);
}
this worked for me..
$sql = "desc MyTableName";
$result = #mysql_query($sql);
while($row = #mysql_fetch_array($result)){
echo $row[0]."<br>";
}
I have write a simple php script to fetch table columns through PHP:
Show_table_columns.php
<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
$link = mysql_select_db($db) or die("no database") . mysql_error();
$count = 0;
if ($link) {
$sql = "
SELECT column_name
FROM information_schema.columns
WHERE table_schema = '$db'
AND table_name = 'table_name'"; // Change the table_name your own table name
$result = mysql_query($sql, $con);
if (mysql_query($sql, $con)) {
echo $sql . "<br> <br>";
while ($row = mysql_fetch_row($result)) {
echo "COLUMN " . ++$count . ": {$row[0]}<br>";
$table_name = $row[0];
}
echo "<br>Total No. of COLUMNS: " . $count;
} else {
echo "Error in query.";
}
} else {
echo "Database not found.";
}
} else {
echo "Connection Failed.";
}
?>
Enjoy!
mysqli fetch_field() worked for me:
if ($result = $mysqli -> query($sql)) {
// Get field information for all fields
while ($fieldinfo = $result -> fetch_field()) {
printf("Name: %s\n", $fieldinfo -> name);
printf("Table: %s\n", $fieldinfo -> table);
printf("Max. Len: %d\n", $fieldinfo -> max_length);
}
$result -> free_result();
}
Source: https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp
The easy way, if loading results using assoc is to do this:
$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);
This you load a single result using this query, you get an array with the table column names as keys and null as value.
E.g.
Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)
after which you can easily get the table column names using the php function array_keys($result)

How can I check if mysql table column even exists?

How can I check if mysql table field even exists ?
The column name is 'price' and I need to see if it exists.
Haven't understood really how the 'EXISTS' works...
Any examples or ideas ?
Thanks
In PHP:
$fields = mysql_list_fields('database_name', 'table_name');
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if (!in_array('price', $field_array))
{
$result = mysql_query('ALTER TABLE table_name ADD price VARCHAR(10)');
}
This should also help you:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
ALTER TABLE TEST ADD TEST_DATE DATETIME
END
Or you can do:
Show columns from table like 'string';
There has been a similar question posed on SO here before.
Try:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TEST' AND COLUMN_NAME = 'Price')
BEGIN
-- do something, e.g.
-- ALTER TABLE TEST ADD PRICE DECIMAL
END
Another way of doing it in PHP:
$chkcol = mysql_query("SELECT * FROM `table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(isset($mycol['price']))
echo "Column price exists! Do something...";
Well, one way is to do:
select price from your_table limit 1
If you get an error:
#1054 - Unknown column 'price' in 'field list'
then it does not exists.
I found this very useful. It will list all the tables that has that column name.
SELECT table_name,
column_name
FROM information_schema.columns
WHERE column_name LIKE '%the_column_name%'
well here is a function to check out if a particular column exists or not.
public function detect_column($my_db, $table, $column)
{
$db = mysql_select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'"; //query
$result = mysql_query($sql); //querying
if(mysql_num_rows($result) == 0) //checks the absence of column
echo "column $column doesn't exist !";
// write your code here!
else
echo "column $column exists!";
}
well if you are designing a frame work, then this function may come to your aid. This function checks for the presence of column when $flag is set to '1' and absence of column when $flag is set to '0'.
public function detect_column($my_db, $table, $column, $flag)
{
$this->select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == $flag)
return true;
else
return false;
}
You could get a description of all the column in your table.
desc your_table;
I just done something like this using this function for Wordpress, this for update tables that having new chnages on it
public function alterTable() {
$table_name = $this->prefix . $this->tables['name'];
$select = "select * from `{$table_name}` where 0=0 limit 1;";
$query = $this->db->get_results($select, ARRAY_A);
if (isset($query[0]) && !key_exists('adv', $query[0])) {
$sql = "ALTER TABLE `{$table_name}` ADD `me` INT NULL DEFAULT NULL ;";
$this->db->query($sql);
}
}

Categories