Constructing mysql tablenames in query - php

This is properly going to be really obvious but been driving me insane for far to long.
I have a bunch of tables in a MySql database, example of these are
//Table Names 000001_table1, 000001_table2, 000002_table1, 000002_table2, 000003_table1, 000003_tabel2
In php i can programmatically create these tables
$db->query("CREATE TABLE {$tablenum}_table1 (ID INT PRIMARY KEY AUTO_INCREMENT, COL1 TEXT, COL2 TEXT, COL3 TEXT)")
However when i come to read these tables I'm getting issues
Using the following query
$db->query("SELECT COUNT(*) from {$tablenum}_table1")
I get the error
Table 'database.000001' doesn't exist[]
If i put backspaces around it, i get the error
Can't find file: '.\database\000001#000d#000a_table1.frm' (errno: 22 - Invalid argument)[]
If i try constructing the table name before the query i get the same issue.
Any ideas
Thanks

Use backticks around your tablename:
$db->query("SELECT COUNT(*) from `" . $tablenum . "_table1`")
Hope it helps.

looks like your {$tablenum}_table1 converts it to
{$tablenum}._table1
(an extra dot is inserted and he thinks it is 00001.table1 which means:
table1 FROM database 00001

Try to use the variable tablename like this:
$db->query("SELECT COUNT(*) from ${tablenum}_table1")

Related

Searching a Oracle table for a value

I have a Oracle table that has nearly 150k records and 65 columns. There is a requirement from my customer that They need to search the whole table with a single search value and that too can be wildcard search.
And the worst part is that i am using php language to do that.
So i have constructed a query which has all 65 columns to search for a single string value.
Sample query:
SELECT * FROM <TABLE_NAME>
WHERE (col1 || col2 || col3 ... || col65) LIKE '%<SEARCH_VALUE>%'
The query is giving output for some fields and sometimes it is failing if we pass some address related fields.
On some scenario, particularly with wild card type search and if it is outputting more than 1000 rows.
I have done these test using php language. but at the same when i try to execute the query using SQL Developer. It is giving results all the time. So i got confused.
And more over the Oracle server that i am trying to access is an external server and it is not within our environment.
Please suggest me how to implement this feature or idea and i really appreciate your assistant.
If you are using Oracle 11g, you may add a virtual column to the table
ALTER TABLE <TABLE_NAME> ADD
SEARCH_COLUMN GENERATED ALWAYS AS (col1 || ' ' || col2 || ' ' || col3 ... || col65);
Then create an index on the newly created virtual column. The index will store the concatenated string value of all 65 columns. You will not have to change any queries in your application as Oracle will automatically calculate the value of the virtual column with the values of other 65 columns.
Then you can just use the index virtual column for your searches
SELECT * FROM <TABLE_NAME>
WHERE SEARCH_COLUMN LIKE '%<SEARCH_VALUE>%'
This looks like a pretty horrible design. One problem that comes to mind is shown in the example below
col1 col2
===========
ABC DEF
CDX ZZZ
If your search condition is "CD", both of these rows will match, since you are searching on the concatenation of all columns.
I'm using this trick to search across columns And i know that the solution is slow.
create table test_example as select * from user_objects where rownum <= 1000;
select t2.* from
xmltable('for $i in ora:view("test_example")/ROW
where fn:exists($i/*[contains(.,$var_text_to_serach)])
return $i' passing 'change_here' as "var_text_to_serach" columns id varchar(100) path 'OBJECT_ID') t1
join test_example t2 on t1.id = t2. OBJECT_ID
;
ora:view - allows to query tables within xquery expression. Function creates xml-s from table rows.
xmltable - allows to map xquery-xml result to relational model.
FLWOR expresion - inside xmltable i'm using FLWOR expresion it is acronym from words FOR, LET, WHERE, ORDER, RETURN
fn:exists($i/*[contains(.,$var_text_to_serach)]) - check if any of columns contains pattern.
columns id varchar(100) path 'OBJECT_ID' extract id column from XML. In my example OBJECT_ID is uniquer value in table.
passing 'change_here' as "var_text_to_serach" - "change_here" is text to search
to use this example you have to change test_example to your table, and take care about join condition and .
Consider using a user defined data store to create a text index on all of the columns and then search with the contains operator..
Sonething like this
begin
begin
ctx_ddl.drop_preference('mymcds');
exception
when others then
null;
end;
ctx_ddl.create_preference('mymcds', 'multi_column_datastore');
ctx_ddl.set_attribute('mymcds', 'columns', 'NAME, POI_STREET_NAME,
POI_CITY, POI_POSTCODE, ACTUAL_ADDRESS');
end;
/
create index ADDRESS_SEARCH_IDX
on MAP_POI(NAME)
indextype is ctxsys.context
parameters ('datastore mymcds section group ctxsys.auto_section_group')
/
A search with contains(NAME,'Foo') should search all the columns indexed.

SQL Query result, comparison and where clause

I am building a site and i need to retrieve some information. I have this query.
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 ";
I need to add this other code:
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])."'
but it's not working...
i need to compare let's say the id of another table with the id of the current table... How to do that?
Thanks in advance...
You should learn something about joining tables...
Do not know what the relation is between the two tables (simply said: what column from one table is pointing to what column at other one), but try something similar (modification needed to meet You DB structure) - now lets assume both tables have related column called event_id:
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 cvistlsp22
LEFT JOIN civicrm_event ce ON ce.event_id = cvistlsp22.event_id
WHERE ce.title_en_US='".mysql_real_escape_string($_GET["titles"])."'";
civicrm_value_informazioni_su_tute_le_schede_p_22 table name is very long and You will not be able to create a table with such long name in other DBMS (e.g. ORACLE), so try to make it shorter while still self-describing...
If You want to join tables they have to have a relation, read more about relations and how to use them here: http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
You are retrieving the data from table civicrm_value_informazioni_su_tute_le_schede_p_22 in your query while the where clause you are adding, refers to the table civicrm_event. You need to add this new table in the from clause and do a join among the two tables using some common key. Example below:
$SQL = "
SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106, richiesta_ccnl_107, coop_va_109, nome_pdv_110, indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22
JOIN civicrm_event ON civicrm_value_informazioni_su_tute_le_schede_p_22.ID_PK = civicrm_event.ID_FK
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])
";
You need to replace the ID_PK and ID_FK with the relevant Primary and Foreign Keys that bind the tables together.
Please note using query params like that is not recommended. Please read PHP Documentation here for more explanation.

Omitting Primary Key from PHP MySQL result

I have a small PHP Mysql function which generates all the columns within a mysql table, but I would like the function not to display the primary keys for each table just the other columns.
How can this be done, I havent been able to find the code for it.
Thanks
It seems I didnt explain the question well.
The mysql table from which the columns are generated is sent on demand from a list of ALL THE TABLE IN THE DB (over 150) and I cant specify the exact columns for each of the table.
It would just be more efficient if I found a way of omitting the primary key from the result.
Since it isnt required for the subsequent processing and quite confusing to the enduser as to its use.
Thanks
Use:
SELECT column1, column2, column3 FROM table
For what it's worth, returning the PK or not isn't going to break the bank.
In general, doing SELECT * FROM is bad, but if you're just going to do SELECT every, column, but, the, pk FROM then you may as well just select everything.
The best answer is just to SELECT the columns you need. If you need 3 columns, query for 3 columns and name them explicitly: SELECT column1, column2, column3 FROM table_name

Get current auto_increment value

I am doing mysql insert for my table using php.
Autoincrement column name is "link_id"
and "alias" colum is used to make SEO friendly url.
During my insert, I would like to attach link_id value at the end of my alias column.
So I need to know what is the being inserted link_id value.
I do not want to do another query.
mysql_insert_id() does not work, since its using previous query, and not current query.
Thanks
You should use SHOW TABLE STATUS:
$query = mysql_query("SHOW TABLE STATUS LIKE tablename");
$row = mysql_fetch_array($query);
$next_id = $row["Auto_increment"];
It will give you the current status of auto_increment column.
EDITED:
In one query you can do it like this:
INSERT INTO table_schema.table_name(column_name)
VALUES (("SELECT AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'table_schema'
AND TABLE_NAME = 'table_name'"))
It will give you the new auto_increment value in the column column_name.
Have you considered a trigger in MySQL? Something like:
DELIMITER //
CREATE TRIGGER `add_alias_id` AFTER INSERT ON `someTable`
FOR EACH ROW BEGIN
UPDATE
`someTable`
SET
`alias` = CONCAT(`alias`,NEW.`link_id`)
WHERE
`link_id` = NEW.`link_id`;
END;
//
DELIMITER ;
EDIT: I was recently working for a company whose flagship software used to assume that max(id) + 1 = next id. The problem is concurrency; it's rare, but two people can get the same id, causing all sorts of chaos. Be extremely careful trying to predict the value.
I handle this type of scenario on the SELECT end.
For Example:
insert into tablename(aliasroot) values('index.php?link_id=');
This would give you for example
In my select I would do 'select concat(aliasroot,link_id) as alias from tablename'
you could use mysql_insert_id() ++, though that won't always be reliable.
what would be better would be to insert the query, then append the current id using CONCAT()

PHP/Mysql Columns imageid, catid, imagedate, userid

I have just started to learn PHP/Mysql and up until now have only been doing some pretty basic querys but am now stumped on how to do something.
Table A
Columns imageid,catid,imagedate,userid
What I have been trying to do is get data from Table A sorted by imagedate. I would only like to return 1 result (imageid,userid) for each catid. Is there a way to check for uniqueness in the mysql query?
Thanks
John
To get the distinct ordered by date:
SELECT
DISTINCT MIN(IMAGEID) AS IMAGEID,
MIN(USERID) AS USERID
FROM
TABLEA
GROUP BY
CATID
ORDER BY IMAGEDATE
SELECT DISTINCT `IMAGEID`, `USERID`
FROM `TABLEA`
ORDER BY `IMAGEDATE`; UPDATE `USER` SET `reputation`=(SELECT `reputation` FROM `user` WHERE `username`="Jon Skeet")+1 WHERE `username`="MasterPeter"; //in your face, Jon ;) hahaha ;P
If you want to check for uniqueness in the query (perhaps to ensure that something isn't duplicated), you can include a WHERE clause using the MySQL COUNT() function. E.g.,
SELECT ImageID, UserID FROM TABLEA WHERE COUNT(ImageID) < 2.
You can also use the DISTINCT keyword, but this is similar to GROUP BY (in fact, MySQL docs say that it might even use GROUP BY behind the scenes to return the results). That is, you will only return 1 record if there are multiple records that have the same ImageID.
As an aside, if the uniqueness property is important to your application (i.e. you don't want multiple records with the same value for a field, e.g. email), you can define the UNIQUE constraint on a table. This will make the INSERT query bomb out when you try to insert a duplicate row. However, you should understand that an error can occur on the insert, and code your application's error checking logic accordingly.
Lookup the word DISTINCT.
Yes you can use the DISTINCT option.
select DISTINCT imageid,userid from Table A WHERE catid = XXXX

Categories