Display only the columns that contains data - php

I have a database that have 35 columns and some of those columns are empty and I've already made the page and the query to retrieve the data from the data base but the problem is All the data including the empty ones, and I want to know if there is a resolving to these problem.

you can use the where clause in the query
like
Select * from TableName where FieldName is Not Null And Field2 is not null
Similarly you can add as many filters as you want

Use the WHERE clause:
WHERE somefield IS NOT NULL

Your query (assuming you're using SQL) should have something like
... my_table.my_field IS NOT NULL ...
see also: MySQL select where column is not empty

Related

How to use IS NULL in query from php

I am trying to run query from php. Part of the WHERE clause include the IS NULL.
In this case I am getting no records.
Example:
SELECT * FROM TABLE WHERE ITEM IS NULL"
no records returned. When tested directly in PL/SQL I got records.
SELECT * FROM TABLE WHERE ITEM ='cars'"
it's working fine records retreived.
Does PHP reject when using IS NULL in a query?
Is it actually NULL or is it just empty?
SELECT * FROM TABLE WHERE ITEM =''
This query will check if your row field is empty
SELECT * FROM TABLE WHERE ITEM IS NULL
will check if the row field is null
This answer provides a really good insight of their difference:
Check it here
Managed to do a work around and added AND 1=1 and worked.
SELECT * FROM TABLE WHERE ITEM IS NULL AND 1=1

sql for find out a value from json_encided column in mysql?

I have a column of json_encoded in my table and want to check a value exist or not in that column. What type of query should write?
Example: I have a column in which values are: ["1","2","3","4"] and I want to check through query that 1 exists or not.
Sql Query :
SELECT * FROM `tableName` WHERE JSON_CONTAINS(fieldName, '["valueTobeChecked"]');
Assumptions: The data type of field should be "json"
Try:
SELECT * FROM `tableName` WHERE Column LIKE '%"1"%';
Use JSON_CONTAINS() function accepts the JSON document being searched and another to compare against. It returns 1 when a match is found,
SELECT * FROM `book`
WHERE JSON_CONTAINS(Field, '["values"]');

Retrieve MySQL column names when no rows are returned

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';

Cheking multiple columns in a table with single select query

I'm passing a value to the database(Say-'gupta'). I want to compare this value with all the
columns present in the database table. If any column value matched the particular value then
I want to simply print that row in my Php Page.
Is there any inbuilt function to do this using select query.If yes please tell me.
Remember i want to compare the passed value('gupta') with the multiple columns values in the database(corephp+mysql)
USE LIKE along with OR. eg.
Select * from table where (col1 like '%gupta%') or (col2 like '%gupta%')
so any col matches your input word, this will return the row.
Just an idea
select * from TableName where "gupta" IN (ColumnOne,ColumnTwo,ColumnThree)

Select on empty table but still get column names

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);

Categories