I need the simplest way to get all table names used in MySQL query
"select * From Tab1 " $result= Tab1
"select * From Tab1, Tab2 Where ID1=ID2" $result= Tab1, Tab2
"delete From Tab1" $result= Tab1
You can use EXPLAIN for SELECT statements - simply prepend EXPLAIN keyword in front of your query and execute it. It will give you MySQL query execution plan, which will also include list of tables involved - check out this SQLFiddle.
It should also work For DELETE statements, but beware that it may actually delete rows as side effect, which may not be desirable for your task.
You can use php function mysql_info which return information about last query executed.
string mysql_info ([ resource $link_identifier = NULL ] )
i'm not completely sure about your intention but to list all tables from a database simply execute the following command
SHOW TABLES from 'dbname'
Related
I am trying to create a temporary table from the results of multiple tables that are alike (same table structure). After creating the temporary table and runing the subsequent queries, I would like to store the results from the temporary table in an array to be accessible later in the script/program. I have tried searching for an answer and can't seem to find one.
I have tried nextRowset() as well as separating the queries, but nothing seems to be working like I expect it to work.
Here is my code:
$pdo = new PDO("mysql:host=".$_SESSION['server'].";dbname=data".$_SESSION['sysident'],$user,$pass);
$stmt = $pdo->prepare("DROP TABLE IF EXISTS $tabletocreate;
CREATE TEMPORARY TABLE $tabletocreate LIKE table1;
INSERT INTO $tabletocreate (SELECT * FROM table1 WHERE (MISC LIKE '%:memno%' OR MEMNO = :memno)) UNION (SELECT * FROM table2 WHERE (MISC LIKE '%:memno%' OR MEMNO = :memno)) UNION (SELECT * FROM table3 WHERE (MISC LIKE '%:memno%' OR MEMNO = :memno)) ORDER BY SLIPNO;
SELECT * FROM $tabletocreate");
$stmt->bindParam(":memno",$_SESSION['memno']);
$stmt->execute();
$stmt->nextRowset();
$test = $stmt->fetchAll();
print_r($test);
I am unsure as to why the results are not being stored into the array. From what I can tell, everything seems right and no errors occur when the script is ran. I appreciate any help that anyone can offer.
UPDATE - I found out why the query wasn't working. I was using a "-" in the table name I was trying to create which isn't allowed.
You cannot run multiple queries in a single ->query() call. This is a security measure in the underlying PHP mysql drivers, to prevent some form of SQL injection attacks. Doesn't matter which DB interface library you're using, because they all use the same underlying drivers. You'll have to run each seperate query separately:
->query("DROP TABLE IF EXISTS ...");
->query("CREATE TEMPORARY TABLE ...");
->query("INSERT INTO ...");
etc...
I was trying to create a table name with a "-" in the table name. After removing this from the table name, all the queries executed successfully and my PHP code worked as intended.
im making a simple admin module to query the database to show the results. Im using this query via php:
SELECT
*
FROM myTable
WHERE id in(SELECT
id_registro
FROM myOtherTable
where id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
)
order by id DESC
The result shows, however, it takes very long like 2 minutes..Anyone can help me out?
Thanks!
Without seeing your database, it is hard to find a way to make it faster.
Maybe you can try to turn your WHERE IN to INNER JOIN. To something like this
SELECT * FROM myTable INNER JOIN myOtherTable
ON (myTable.id = myOtherTable.id_registro)
WHERE myOtherTable.id_forma = '$id_club'
AND myOtherTable.fecha_visita LIKE '%$hoy%'
ORDER BY myTable.id DESC
Noted that you should sanitize your variable before putting it SQL query or using PDO prepare statement.
Sub Queries takes always time, so its better to ignore them as much as possible.
Try to optimize your query by checking its cardinality,possible keys getting implemented by DESC or EXPLAIN , and if necessary use FORCE INDEX over possible keys.
and I guess you can modify your query as:
SELECT
*
FROM myTable
inner join id_registro
on (id = id_forma )
where
id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
order by id DESC
LIKE in mysql may take a long time ,with or without index.
Do u have a very large DB?
I have two SQL queries:
$res1 = mysql_query("SELECT * FROM `table1` WHERE `user`='user'");
$i = mysql_fetch_assoc($res1);
$value1 = $i['num'];
And:
$res2 = mysql_query("INSERT INTO `table2` (`name`,`num`) VALUE ('name','$value1')");
How to combine the two SQL queries into one? I need to get the value of the variable from of a second query for the first request. Is it possible?
This query with a subquery should do the trick nicely for you:
insert into table 2 (`name`, `num`)
values ('name', (select `num` from table1 where `user`='user'));
This assumes that you aren't using anything but the num from your second query as it doesn't seem to be used in your original code.
Edit: Also, I see that this is an insert, not just a select statement, but you might well benefit from reading a rather lengthy question and answer I put up which covers off multiple tables and SQL covering unions, joins, subqueries and a bunch more stuff.
Can you use the INSERT INTO ... SELECT ... syntax?
E.g. something like:
INSERT INTO table2 (name, num)
SELECT 'name', num
FROM table1
WHERE user='user'
(untested so please forgive any minor errors here...)
Scrap this.
The best answer is to have PHP have the data that MYSQL is going to need. Doing it any other way will cause bottlenecks and is inefficient.
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);
i am using php with mySql server, pretty new to all the sql and i have a question:
i have a query:
$book_copy_user = "SELECT * FROM copy_book " .
"JOIN copy_user_own " .
"ON copy_book.copy_id = copy_user_own.copy_id " .
"WHERE copy_user_own.user_id=1";
$res1 =mysql_query($sql1) or die (mysql_error());
which returns something like
[{"copy_id":"1","book_id":"1","user_id":"1"},
{"copy_id":"2","book_id":"2","user_id":"1"},
{"copy_id":"3","book_id":"3","user_id":"1"},
{"copy_id":"4","book_id":"4","user_id":"1"}]
i would like to do 3 different select on the result with a where clause, but when trying to so it tells me that there is more the one column.
my question is:
is there a way that i can use the select result and apply select on it?
if so how can i relate to the fields of the in the select result?
please provide code samples
thanks you all you are saints :)
You can select the data into a temporary table and perform more queries on that table.
CREATE TEMPORARY TABLE temp_table SELECT ...
But I think it would be best if you posted your actual problem, it is very likely that there are much better solutions.
SELECT * FROM (SELECT * FROM copy_book JOIN copy_user_own ON copy_book.copy_id = copy_user_own.copy_id WHERE copy_user_own.user_id=1) WHERE copy_id = 4
althrough I'm not sure if it works in mysql.
No, after running select you cannot apply another on it.