Dynamically assign alias to all the field names in msyql query - php

I have 2 tables in mysll DB. Both tables have few fixed and few dynamic columns (Fields / Schema). I want to join both these tables with following query:
SELECT *
FROM `cd` cd
LEFT JOIN cd_n cn ON cd.id = cn.fk_cd
And I want to result as
CD_Column1 CD_Column1 CD_Column3 ...... CN_Column1 CN_Column2 CN_Column3 .....
value value value ...... value value value ...
value value value ...... value value value ...
Where ..... is dynamic column names of both the tables.
So the case is I dont know the column names because they are dynamic and I want rename (alias) it on query level. Please let me know how can I do this?

You would need to query the information_schema to get the column names of that two tables. Lets assume You would have the cd column names stored in the array $cd_columns and the cd_n column names in the array $cdn_columns.
Then in PHP when creating the query loop through the column arrays and do something like this:
$sql = 'SELECT ';
// add the cd columns
$i = 0;
foreach($cd_columns as $col) {
$sql .= "{$col} AS CD_Column{$i},";
$i++;
}
// add the cd_n columns
$i = 0;
foreach($cdn_columns as $col) {
$sql .= "{$col} AS CN_Column{$i},";
$i++;
}
// remove the trailing comma
$sql = trim($sql, ',');
// continue the SQL
$sql .= ' FROM ...';
Was this helpful?

Related

SELECT all tables from DB and query same column name in each one of them

I have several tables that are being imported by an external app. Their names are e.g Table_1, Table_296 and so on.
In each table, there is one column named Name.
My question is: How do I retrieve the names of all tables so I can put them into another query that will retrieve rows from each column Name?
Basically, I need to check for value and list a table (or tables) that contains it.
I can retrieve all tables names using the code below, but as far as I know, they can't all be SELECTED using a variable.
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME LIKE '%Table%' AND TABLE_SCHEMA='mydb'
I also know that the same column name cannot be selected if table names are not specified. Correct me if I'm wrong, please
First get all the table name then loop like below
$con = mysqli_connect("localhost","root","","databaseName");
$listdbtables = array_column(mysqli_fetch_all($con->query('SHOW TABLES FROM databaseName')),0);
foreach ($listdbtables as $key => $value) {
$sqlqry = "select Name from ".$value;
$nameResult = mysqli_query($con,$sqlqry);
while($nam = $nameResult->fetch_array()) {
echo($nam['Name']);
}
}

Dynamic SQL Command

I want to be able to get only values where there is a '1' in multiple columns.
My column names are stored dynamically in a variable though.
How would I go about this?
This is what I have.
Columns are layed out like this
$Columns = "Computer, Science, Algebra, Biology, Networking"; //This is Dynamic so $Columns may be like this next time $Columns = "Biology, Networking";
$SQL = "SELECT * FROM users WHERE '1' IN(".$Columns.")";
Right now, it selects any users that have a "1" in any of the columns
I only want to retrieve the users that have a "1" in ALL of the variables in the array $Columns not just one of them
Since your $columns variable can be different sizes, you will need to build your sql statement based on the number of columns in the array in a for loop:
// SET your first column IN
$sql = "SELECT * FROM users WHERE '1' IN (".$Columns(0).")"
//Run the for loop to build sql on all subsequent columns
// size of will give you the number of columns in your array
$max = sizeof($columns);
for($i = 1; $i < $max;$i++)
{
//Use the "AND" to make sure "1" is in all columns
$sql.=" AND '1' IN (".$Columns($i).")
}
$sql.=";"
My code may not be perfect, but should get you in the right direction.

SUM values of specific column from all tables LIKE table_%

I need help to create an SQL query in order to SUM the values of specific column from all tables LIKE table_% as the tables will grow over time and this must cater for new table names based on the format below
Scheme Name: database_01
Table Names: tb_data_'YEAR'_'MONTH'
YEAR and MONTH are both values which range from all 12 months and years from 2011 to 2018.
Each Table contains a column called TOTAL_VALUE. I have a php script that triggers an SQL query to pull data from the database.
I would like to SUM the total of each tables TOTAL_VALUE column and save the value for my script below to push the array.
$sql = "SELECT TOTAL_VALUES FROM tb_data_2017_october";
$result = mysqli_query($conn, $sql);
$data = array(); while($enr = mysqli_fetch_assoc($result)){
$a = array($enr['TOTAL_VALUES']);
foreach ($a as $as){
echo "'".$as."', ";}
array_push($data, $as); }
I have been trying to alter the SQL with options such as:
SELECT id FROM table1
UNION
SELECT id FROM table2
UNION
SELECT id FROM table3
UNION
SELECT id FROM table4
However i need to cater for the ability to check all tables that are like tb_data_%
See this question for information about getting the list of tables: Get table names using SELECT statement in MySQL
You can get the list of tables in one query result, and then query each table. I'll rework your code slightly to give an example:
// Get the tables
$tables_sql = "SELECT table_name
FROM information_schema.tables
WHERE table_schema='<your DB>'
AND table_name LIKE 'tb_data%'";
$tables = mysqli_query($conn, $sql);
// Iterate over the tables
while($table = mysqli_fetch_assoc($tables)){
{
/*
* Your code
*/
// This query assumes that you can trust your table names not to to an SQL injection
$sql = "SELECT TOTAL_VALUES FROM " . $table['table_name'];
$result = mysqli_query($conn, $sql);
$data = array(); while($enr = mysqli_fetch_assoc($result)){
$a = array($enr['TOTAL_VALUES']);
foreach ($a as $as){
echo "'".$as."', ";
array_push($data, $as); }
}
You can do whatever you need once your have your list of tables. You can build one big union query (which would be more efficient than querying each table individually), or feed the tables to the MERGE engine, as in barmar's answer
Use the MERGE storage engine to create a virtual table that combines all the monthly tables.
CREATE TABLE tb_all_data (
...
) ENGINE=MERGE UNION=(tb_data_2017_october, tb_data_2017_november, ...);
List all the tables in the UNION= list, and update it whenever you create a new table.
Then you can just query from tb_all_data.
Try this- it will loop through all the tables with the pattern you want and create sums for you:
declare #table table (rowid int identity, name varchar(max))
insert #table
select name from sys.tables where name like '%yourname%'
declare #holding table (name varchar(max), sumvalue int)
declare #iterator int = 1
declare #tablename varchar(max)
while #iterator<=(select max(rowid) from #table)
begin
select #tablename=name from #table where rowid=#iterator
insert #holding
exec('select '+#tablename+' sum(TOTAL_VALUE)TOTAL_VALUE from '+#tablename+' group by +'+#tablename+'')
set #iterator=#iterator+1
end
select * from #holding

check array values exist in mysql table

I need to check the array values which contains more than 400 values which is existing in the MySQL table where i should get result for all the values which I am passing even if it not exist in the column.
for example:
cont table
----------
Column1
---------
9xxxxxxxxx
91xxxxxxxx
92xxxxxxxx
my array contains 9xxxxxxxxx & 91xxxxxxxx. How can i iterate to get the column exist or not.
I tried with foreach and building query
$sql = 'SELECT cont WHERE num IN(';
foreach($jsonString as $val){
$sql = $sql . "'$val', ";
echo $val;
}
if(mysqli_query($con,$sql)){
echo "exist";
}else {
echo "error";
}
Is there any efficient way other than the above which is faster in time?
First of all if cont is your table name than where is FROM keyword.
If cont is column name than where is TABLE name?
As per your question, you have 400+ ids, than why are you using loop here? you can simply use implode() with comma seperated values, like
<?php
$ids = implode(",",$jsonString);
$sql = "SELECT * FROM cont WHERE num IN ($ids)"; // assuming cont is table name
?>
In your loop you will get the "," in last iteration at the end this will break your query.

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Categories