How to select data from columns that match a criteria? - php

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.

Related

Column number in mysql 'WHERE' condition

How is it possible to select the first column in the Where clause. I am trying to make a php function to retrieve table data based on the id, yet since the titles of the id columns are different in various tables, I need to refer to the first column in the Where clause as the first column is always the id column.
The scenario would be something like the following, but it throws errors and says that there is an error in the SQL syntax.
$stmt = $this->conn->prepare("SELECT * FROM $table WHERE column(1) = :id");
Thanks in advance.
I don't think there's a built-in way to do this. But you can query INFORMATION_SCHEMA.COLUMNS to get the column names.
$col_stmt = $this->conn->prepare("
SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND ordinal_position = 1
AND table_name = :table");
$col_stmt->execute([':table' => $table]);
$first_col = $col_stmt->fetchColumn();
$stmt = $this->conn->prepare("SELECT * FROM `$table` WHERE `$first_col` = :id");
Since there is no built-in way to do this, I came up with the following code block to get the first column and then use it in my SELECT statements.
$stmt = $this->conn->query("SHOW columns FROM $table");
return $stmt->fetch(PDO::FETCH_LAZY)[0];
I think this strategy is a bit shorter than Barmar's, though his is completely right and to the point.

how to search all the tables of the database using php mysqli and display the answer

i am just beginning to learn mysqli and php ...so i am a novice.
i am trying to build a site for babynames.
i have a database of babynames in phpmyadmin. having tables country1, country2, country3....and so on. all the tables have the same columns id, name, meaning, gender and alphabet.
i print the names table using the following code using PHP and MYSQLI
$sql1="SELECT id,name, meaning, alpha, gender FROM $country WHERE gender='$gender' AND alpha='$alpha' $limit";
$query=mysqli_query($con,$sql1);
while($rows=mysqli_fetch_array($query)){
echo "<td><a href='meaning-of.php?name=$rows[name]'>".$rows['name']."</a></td>";
echo "<td>".$rows['meaning']."</td>";
echo "<td>".$rows['gender']."</td></tr>";
}
the name column is linked to meaning-of.php?name=$rows[name]
Now i want a code in PHP and MYSQLI to search all the tables(say 100 tables) of the database "babynames" for a particular name and display the same name and meaning please.
if the name exists more than once in the tables than all the names should be displayed along with their respective meanings please.
how do i search all the tables for a particular name and display using PHP and MYSQLI please.
i want to search the database by passing only the name variable into the address bar like this http://localhost/meaning-of.php?name=John or http://localhost/meaning-of.php?name=samson and find the meaning by searching all the tables of the database based on only the name please.like if the name is set than getting the name by $name=$_GET["name"]; and then search the whole database tables and display the meaning
is there a code something like this
SELECT *(all columns) FROM * (all the tables or the database name or all the databases) WHERE name=$name;
Please help. Thank You in advance please.
Keep all your data in a single table, adding a field country to distinguish the country.
This is the only proper answer to this question.
You can use UNION clause to get results from multiple select statements mysql doc
(SELECT * FROM county1 WHERE name=$name)
UNION
(SELECT * FROM county2 WHERE name=$name);
You can query all table names from information_schema
SELECT table_name FROM information_schema.tables
WHERE table_name LIKE "country%"
AND table_schema = "<name_of_country_database>";
So the full solution would be something like this:
$tables_sql = "SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'country%' AND table_schema = 'babynames'";
$tables_query = mysqli_query($con,$tables_sql);
$sql1 = '';
while ($table = mysqli_fetch_array($tables_query)) {
if ($sql1 != '') {
$sql1 .= ' UNION ';
}
$sql1.= " (SELECT name, meaning FROM " . $table['table_name'] . " WHERE name='$name') ";
}
$query=mysqli_query($con,$sql1);
while($rows=mysqli_fetch_array($query)){
echo "<tr>";
echo "<td>".$rows['name']."</td>";
echo "<td>".$rows['meaning']."</td>";
echo "</tr>";
}

php/mysql get all tables and columns in a database

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

exclude certain items from fields in mysql

lets say you want to get all the columns of a table, but exclude ones that have for example _images in the name without having to do
mysql_query("SHOW COLUMNS FROM " . $table. " WHERE Field NOT IN ('project_images_1' .etc)")
is this possible?
field example:
header
bodytext
project_images_1 (exclude)
project_images_2 (exclude)
Yes, this is possible. I could do it with the LIKE operator:
SHOW COLUMNS FROM $table WHERE NOT Field LIKE '%_images%';
Or if you need more control, this might be helpful:
$query = <<<SQL
SHOW COLUMNS FROM $table WHERE Field NOT IN (
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = $table
AND column_name LIKE 'project_images_%'
);
SQL;
This works by using the information schema tables (maybe that's what you look for anyway) within a so called subquery.
Related:
How do I use SHOW COLUMNS as a valid data source

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.

Categories