I want to know how to find a nth column of a mysql table since I know that the query ->
SHOW COLUMNS FROM TABLENAME
shows all the columns but I want to fetch only selected columns. Is there a way to pass all the column names in an array and then echo the nth column like:
echo $fields[n];
I saw that this query can also be done but I do not know how to get the column numbers from this query:
SELECT * FROM Information_Schema.Columns WHERE TABLE_NAME = #tablename AND ORDINAL_POSITION = nth but it
I am using mysqli db connection method.
Related
My MySQL database has column names like clnt_1001,clnt_1002 .... so how can I fetch the value from all clients runtime? ,
where clients can be added later,
like where column name like '%CLNT_%' and id =2001;(all values in 'CLNT_' are integers)
You will need to query INFORMATION_SCHEMA to get the column names and use it in your SELECT query, e.g.:
SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'your_table'
AND COLUMN_NAME like 'CLNT_%';
This will give you (comma separated) column names, you can then use the result of this query to construct the SELECT query, e.g.:
SELECT <columns>
FROM your_table;
Here, you can replace <columns> with result of the first query and get the data for all the columns.
Here's MySQL documentation on INFORMATION_SCHEMA tables.
$sql = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table' AND table_schema='PPcontent';";
$query = mysqli_query($con, $sql);
while($result = mysqli_fetch_array($query)){
echo "<option value=\"", $result[0], "\">", $result[0], "</option>";}
I am trying to get a handle on mysqli objects and how they work. I have the above query that I am using to find the table names of a database and insert them into a select dropdown. When I used similar code to populate another select dropdown I used $result['some_row_name'] to fetch the results when the while loop runs. Then my select statement was SELECT 'some_row_name from 'some_table' When I do it with the select statement above I need to use the index 0 instead of "Table_name". Why is that? When I run the select statement above in PHP MyAdmin I get a table back with the row name 'Table_name' so I would think I would use that as an index instead of 0.
mysql is generally case insensitive with column names so if the column is called MYCOLUMN you could effectively query as follows in the mysql console or with php
SELECT mycolumn FROM mytable;
SELECT MYCOLUMN from mytable;
SELECT myColumn from mytable;
however when you use php's mysqli_fetch_array, you will have to access the column data using the exact capitalization that you used in the query here. That is because PHP is case sensitive when it comes to variable names. With languages that are not case sensitive it would not matter.
If you wanted the column to have a completely different name you can use an alias
SELECT mycolumn AS some_other_name FROM mytable;
Wondering if there's a way to get MySQL to return the column names when the query result returns no rows? The issue is that our system has multiple large queries sometimes:
SELECT * FROM table
SELECT table1.*, table2.field1, table2.field2
SELECT table1.field1 AS f1, SUM(table2.field1) AS f2
etc. So only way to get the column names when the returned result is empty, would be to parse the queries, and attempt to run a query on the information_schema table. Which is possible, but would be rather complex. Any ideas?
Some PHP interfaces for MySQL have a function for result set metadata, which should return information even for a result set with zero rows.
MySQLi has mysqli_stmt::result_metadata().
PDO has PDOStatement::getColumnMeta(), but it's labeled "experimental," which probably just means it's not well tested in all PDO drivers.
One technique that you can use is to create a view on the query and then query information_schema with the view name.
That is, something like this:
create view v_JustForColumns as
<your query here>;
select *
from information_schema.columns
where table_name = 'v_JustForColumns';
drop view v_JustForColumns;
Try the below one. Here replace the YOUR_SCHEMA with your actual schema name and YOUR_TABLENAME with your actual table name:
select column_name from information_schema.columns
where not exists(select * from YOUR_SCHEMA.YOUR_TABLENAME)
and table_name='YOUR_TABLENAME';
I want to add data to a table, one column at a time. Therefore I don't want to always add a new row, as the column I'm adding to may not have much data in compared to the other columns. As a result I suppose I want to add the data to the first empty cell in the specified column without necessarily adding a new row to the whole table (as there may already be enough rows).
My table has 5 columns.
I'm currently using:
$sql=("INSERT INTO [MY_TABLE] ([MY_COLUMN]) VALUES ('[MY_DATA]')");
Please could someone assist with the correct code? I know it's basic stuff but I'm new to mySQL.
Thanks in advance.
So you can use UPDATE statement with a WHERE condition to target that specific row
UPDATE table_name SET column_name = 'whatever' WHERE column_name = '' AND id = '1'
If you want to update all rows where that column is blank than simply use
UPDATE table_name SET column_name = 'whatever' WHERE column_name = ''
no need of using id in above query
Reference on UPDATE
I want to do a SELECT on an empty table, but i still want to get a single record back with all the column names. I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query.
I know this one works when i run it directly in MySQL:
SELECT * FROM cf_pagetree_elements WHERE 1=0;
But i'm using PHP + PDO (FETCH_CLASS). This just gives me an empty object back instead of an row with all the column names (with empty values). So for some reason that query doesn't work with PDO FETCH_CLASS.
$stmt = $this->db->prepare ( $sql );
$stmt->execute ( $bindings );
$result = $stmt->fetchAll ( \PDO::FETCH_CLASS, $class );
print_r($result); // Empty object... I need an object with column names
Anyone any idea if there's another method that i can try?
Adding on to what w00 answered, there's a solution that doesn't even need a dummy table
SELECT tbl.*
FROM (SELECT 1) AS ignore_me
LEFT JOIN your_table AS tbl
ON 1 = 1
LIMIT 1
In MySQL you can change WHERE 1 = 1 to just WHERE 1
To the other answers who posted about SHOW COLUMNS and the information scheme.
The OP clearly said: "I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query."
Learn to read.
Anyway, to answer your question; No you can't. You cannot select a row from an empty table. Not even a row with empty values, from an empty table.
There is however a trick you can apply to do this.
Create an additional table called 'dummy' with just one column and one row in it:
Table: dummy
dummy_id: 1
That's all. Now you can do a select statement like this:
SELECT * FROM dummy LEFT OUTER JOIN your_table ON 1=1
This will always return one row. It does however contain the 'dummy_id' column too. You can however just ignore that ofcourse and do with the (empty) data what ever you like.
So again, this is just a trick to do it with a SELECT statement. There's no default way to get this done.
SHOW COLUMNS FROM cf_pagetree_elements;
This will give a result set explaining the table structure. You can quite easily parse the result with PHP.
Another method is to query the infomrmation schema table:
SELECT column_name FROM information_schema.columns WHERE table_name='cf_pagetree_elements';
Not really recommended though!
You could try:
SELECT * FROM information_schema.columns
WHERE table_name = "cf_pagetree_elements"
Not sure about your specific PHP+PDO approach (there may be complications), but that's the standard way to fetch column headings (field names).
this will list the columns of ANY query for PDO drivers that support getColumMeta. I am using this with SQL server and works fine even on very complex queries with aliased tables, sub-queries and unions. Gives me columns even when results are zero
<?php
// just an example of an empty query.
$query =$PDOdb->query("SELECT * from something where 1=0; ");
for ($i=0; $i<$query->columnCount(); $i++) {
echo $query->getColumnMeta($i)['name']."<br />";
}
?>
Even without PDO in the way, the database won't return the structure without at least one row. You could do this and ignore the data row:
SELECT * FROM cf_pagetree_elements LIMIT 1;
Or you could simply
DESC cf_pagetree_elements;
and deal with one row per field.
WHERE 1=0 does not work for me. It always returns empty set.
The latest PDO for SQLSVR definitely works with get column meta.
Simply set up your statement and use this to get an array of useful information:
$stmt->execute();
$meta= array();
foreach(range(0, $stmt->columnCount() - 1) as $column_index)
{
array_push($meta,$stmt->getColumnMeta($column_index));
}
Complete solution for Oracle or MySQL
for any or some columns (my goal is to get arbitrary columns exactly as they are in DB regardless of case)
for any table (w or w/o rows)
$qr = <<<SQL
SELECT $cols
FROM (SELECT NULL FROM DUAL)
LEFT JOIN $able t ON 1 = 0
SQL;
$columns = array_keys($con->query($qr)->fetchAll(PDO::FETCH_ASSOC)[0]);
if($cols === "*") {
array_shift($columns);
}
YOu could use MetaData with;
$cols = mysql_query("SHOW COLUMNS FROM $tableName", $conn);