exclude certain items from fields in mysql - php

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

Related

How to select data from columns that match a criteria?

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.

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>";
}

SQL query to find the table name

I have 5 different tables in my dB with the structure Name|Price|Id..
I have a unique price and Id entry combination.
Using these 2, what could be the possible SQL query to fetch the name of the table in which this entry is present?
I need to fetch the name of this table in order to update the value of Price.
You really should normalise your database properly and use a single table, but if you really need a kludge then:
SELECT name, brand, id, 'Tea' as tablename
FROM TableTea
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Coffee' as tablename
FROM TableCoffee
WHERE brand = 'abc'
AND id = 100
UNION
SELECT name, brand, id, 'Chocolate' as tablename
FROM TableChocolate
WHERE brand = 'abc'
AND id = 100
And you'll have to change it if you ever add new products
if your DBMS is MySQL you can use this Query:
SELECT Result.TABLE_NAME FROM (
SELECT TABLE_NAME,COLUMN_NAME,COUNT(*) AS QTA FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'NAME_DB'
and COLUMN_NAME IN ('Name','Price','Id')
GROUP BY TABLE_NAME
) as Result
WHERE Result.QTA = 3
i have already tried to do without php
Replace NAME_DB with your Database.
You would first need to know the tables in which it's possible to have the entry. Use a loop to iterate over those tables and run the query, each time returning a result set and testing if records exist in the result set. This will tell you what tables have the entry.
General Approach:
$array = array("table1", "table2", "table3", "table4", "table5");
foreach($array as $table) {
//build your query using the table name
$query = "SELECT something FROM " . $table;
//exec your query against your db and return results
//test if records exist in result set. If true, you know the table name based on the loop iteration ($table).
}

how to use isset in yii criteria

is there anyway to use isset in yii criteria?
i have two tables named equipment and supply.. They are pretty much the same except that equipment has this field named stock_no. Now I have a search function to show equipment or supply records depending on a dropdown.
Basically what I want is to use if isset to check if *stack_no* exists to prove that it is from equipment table.
if($this->itemType=="Equipment"){
$criteria->isset('stock_no', true ); // what may be the correct way to check if this column is existing?
}
if($this->itemType=="Supply"){
}
You can exequte a this query.
SELECT count(*) exist FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'yourSchema'
AND TABLE_NAME = 'yourTable'
AND COLUMN_NAME = 'stock_no'
This return 1 or 0 if exist this column on the table specified.

Mysql Query In codeigniter

This is my mysql query
$acountry = 1;
$this->db->where_in('varcountry', $acountry);
$val = $this->db->get('tblagencies')->result();
In database table the varcountry filed is stored like this 1,2,3,4 its type is varchar.Each row in table have multiple countries that is the reason to use varchar datatype.
Here i want to select table rows which have $acountry value in the filed varcountry.
How can i do that?The above code is it correct?
You have choosen a wrong data type for storing a comma separated value 1,2,3,4 into varchar,
you should chose a data-type of set, or normalize into a separate table, like :-
create table country (id, name ...);
create table agencies_country ( agency_id, country_id);
insert into agencies_country (agency_id, country_id)
values (x,1), (x,2), (x,3), (x,4);
// meaning 1,2,3,4 = 4 rows
// grabbing result using inner join
Using set is easier, but common practice is to normalize the data (which require some understanding).
I don't like the active record in codeigniter,
is easy to use (not doubt with this),
but it dis-allowed lost of flexibility
Personally I like the construct my own query,
provided you have the understanding of the table schema (which you have to anyway)
use this query..
$search_field = array('varcountry'=>$acountry)
$result = $this->db->get_where('tblagencies' , $search_field );
but in codeignator you can use your own queries like
$sql = "select * from tblagencies where varcountry like '%acountry%'";
$result = $this->db->query($sql);

Categories