hi how to select columns that have the var value?
like this:
$var=$_GET['id'];
$select="SELECT * FROM table WHERE **COLUMNS THAT EQUAL TO VAR** = $var";
How to select those columns that have the $var value?
Clarification: SELECT only the columns that have the value $var in them.
Example:
$var="1";
Column 1, 7, 11 have on some row value 1 then pick those columns and show in which columns the value 1 is in
You have to mention your column name in your query
If you want to check exact match you can do as follows
$var=$_GET['id'];
$select="SELECT * FROM table WHERE column_name = '$var'";
If you want to check column that contain #var you can do as follows
$var=$_GET['id'];
$select="SELECT * FROM table WHERE column_name like '%$var%'";
You must look into INFORMATION_SCHEMA Database
Provide your database name => $db
Provide your column name => $column
Then :
$sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . $db . "' AND COLUMN_NAME = '" . $column . "'";
The easy ways is to use php to get array from all columns:
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'YOUR-DB-NAME' and TABLE_NAME='YOUR-TABLE-NAME'
And use 'for' to create 'where'
for example:
for($i=0;$colums[$i];$i++) $where.=" or {$colums[$i]} like '%string%'";
$SQL="Select * from table where 1=1 $where";
The query will look like this:
$var=$_GET['id'];
// for checking if both the column name and value are the same $var value
$select= "SELECT ".$var." FROM table_name WHERE ".$var."='".$var."'"
OR
$var = $_GET['id'];
// for checking if both the column name and value are different
$select= = "SELECT ".$var." FROM table_name WHERE ".$var."='".$otherValue."'"
Between this is SQLinjection vulnerable code. You should check the variables before using them in query. Also you should start using mysqli and prepared statements
Related
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.
I want to find Mysql columns of a table in PHP.
This is my code but it does not work as expected:
while($row3 = mysql_fetch_array($query3))
{
foreach($row3 as $column => $data)
{
echo'<td>'.$column.'</td>';
}
}
The table columns in the database are ID, User and Pass.
But the output is 0 ID 1 User 2 Pass
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;
while ($row = mysql_fetch_assoc($result))
use this.
Change mysql_fetch_array($query) to mysql_fetch_assoc($query).
It will give array of column name as a key and column's value as value.
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
I have a session that contains an array and that array is filled with id's. What is the best way to select all the rows from a MySQL table that correspond to these id's?
So I need something like:
SELECT * FROM table WHERE id = $_SESSION['ids']
Obviously, this doesn't work, since $_SESSION['ids'] is an array.
SELECT *
FROM
table
WHERE
find_in_set(id, $_SESSION['ids'])>0
You can just use IN SQL operator.
In this case your query will look like
$sql = 'SELECT * FROM table WHERE id IN ("' . implode('","', $_SESSION['ids'] . '")';
This code will produse a query like following:
SELECT * FROM table WHERE id IN ("1", "2", "foo");
Hope it helps
HI Try This,
$var = $_SESSION['ids'];
and then fire your query as
$sql = SELECT * FROM table WHERE id = '$var';
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.