Query entire DB for certain value - php

I am creating a php application that is the front end for a database.
Database Server Type: MySQL version 5.5.32
Web Server Type: Apache/2.4.4
OpenSSL: 0.9.8y
PHP 5.4.16
When populating the DB any blank fields that would need to be addressed in the future were entered as "TBD". I would like to create a query that searches the entire DB for fields that are equal to "TBD". If possible I would like the output of the query to have the following information:
Table Name:
Field Name:
Primary Key:
The PKs for all of my tables are named with the following convention: table name + ID. For example if a table is named "client" it's primary key field is called "clientID". I have set up a version of this report using arrays of the table names and fields name to generate multiple sql queries but I have to believe that there is a SQL wiz out there who can get this done in if not 1, just a query per table? This would be extremely beneficial because it would not require me to update the report, every time I make a change to the DB. Thanks!

You can use a script called anywhereindb
Download it here:
https://code.google.com/p/anywhereindb/
You simply have to upload a php file to your server, add the DB credentials and it'll search for a string throughout the DB. It has been very helpful.
Remember to delete the file after using it if is publicly accesible.

Try constructing your queries like this:
SELECT *
FROM tbl,
tbl1,
tbl2...tblx
WHERE tabl.condition OR ...

Related

PHPMyAdmin Grab specific strings from table

So I have a table in my SQL and it saves ServerID from discord, now like 500 users verified and on the table it says like ServerID: 123 User: Test
Now I accidentally I have deleted the server on dashboard and all things with the server id 123 have been deleted, I have made a backup earlier, now my question is can I do it like I only search id 123 can download only the strings with it and add it to my old database? Thanks!
Standard query language (SQL) makes this beautifully simple to do.
SELECT * FROM table WHERE id = 123;
Explain
The SELECT portion indicates you wish to select/inspect a given record.
The * indicates that you wish to select all records.
The FROM indicates the desired table - and lowercase table indicates the table name. The table will need to be customized to your environment.
The WHERE is your filter and indicates what type of wheres to search.
The id = 123 is restricting your WHERE to results when the keyword id is equal to 123
You should finish all SQL queries with a semicolon. This is language syntax, but may not be required depending on your interface.
I would load the entire SQL file to a new database (you'll want to open the SQL file in a text editor to search and replace any references to the old database name; not all database dumps will contain the database name but if it does, you don't want to accidentally import to the wrong database).
Once you have the new database, it's relatively simple to search across all tables for the rows that reference the id 123 and either manually or programmatically replicate that back to the original database.
There are 2 ways to recover it.
You have to restore the backup and then grab the required string and then later on delete the unnecessary data.
Open the file via a text editor, use ctrl+f to find the required string and then insert/update it in your database via SQL query.

PHP create a copy command like phpmyadmin

I am new with PHP development and just wondering if theres a existing function on PHP than duplicate the copy command on phpmyadmin, i know that the query sequence is below, but this is like a long query/code since the table has alot of columns. i mean if phpmyadmin has this feature maybe its calling a build in function?
SELECT * FROM table where id = X
INSERT INTO table (XXX)VALUES(XXX)
Where the information is based from the SELECT query
Note: The id is primary and auto increment.
Here is the copy command on phpmyadmin
i mean if phpmyadmin has this feature maybe its calling a build in function?
There is no built-in functionality in MySQL to duplicate a row other than an INSERT statement of the form: INSERT INTO tableName ( columns-specification ) SELECT columns-specification FROM tableName WHERE primaryKeyColumns = primaryKeyValue.
The problem is you need to know the names of the columns beforehand, you also need to exclude auto_increment columns, as well as primary-key columns, and know how to come up with "smart defaults" for non-auto_increment primary key columns, especially composite keys. You'll also need to consider if any triggers should be executed too - and how to handle any constraints and indexes that may be designed to prevent duplicate values that a "copy" operation might introduce.
You can still do it in PHP, or even pure-MySQL (inside a sproc, using Dynamic SQL) but you'll need to query information_schema to get metadata about your database - which may be more trouble than it's worth.

Can I have specific selectable values for a column in MySQL

Basically just as the title says, in MySQL can I specify a specific range of values for a column so a choice can be selected when a record is added.
I am only starting to understand MySQL and I know that you can do this MS-Access. I'm not sure but do I have to put something special in the 'Length/Values' column when designing? If I can do it, where do I specify what values would be selectable?
If not, is there a more efficient work around then creating a new table and relating the specified values as a foreign key.
Cheers
MS Access combines a few functionalities into a single program:
A database engine (MS Jet)
A programming environment with a programming language (VBA)
A table editor
A table data editor
A form editor
A report editor
A query editor
... more
MySQL is a database engine only. So there is no natural "Select Box" to input data. This would need to come from your programming environment or form generator.
That said, there is support for such a data type: Use ENUM - e.g. CREATE TABLE test (saluation ENUM ('Mr.', 'Mrs.'));

Check for changes in database schema and update

At our company we have a business solution which includes CMS, CRM and several other systems.
These are installed in several domains, for each of our clients.
The systems are still in development, so new tables and fields are added to the database.
Each time we want to release a new version to our clients, i have to go through their database and insert the new fields and tables manually.
Is there a way that this could be done automatically(a script maybe that detects the new fields and tables and inserts them?)
We are using php and mysql.
We would like to avoid backing up the clients data, dropping the database tables, running the sql query to insert all the database tables(including the new ones) and then re-inserting the customers data. Is this possible?
Toad for MySQL
DB Extract, Compare-and-Search Utility — Lets you compare two MySQL databases, view the differences, and create the script to update the target.
What you are looking for is
ALTER TABLE 'xyz' ADD 'new_colum' INT(10) DEFAULT '0' NOT NULL;
or if you want to get rid of a colum
ALTER TABLE 'xyz' DROP 'new_colum';
Put all table edits into an update.php file and the either call and delete it once manually or try to select "new_colum" once and update the database when it's not present.
OR what I do: "I have a settingsfield "software version" and use this as a trigger to update my tables.
But since you have to install the new scripts anyways you can just call it manually.

Create Table Else Alter Table

This seems to be a simple problem, but after a while of searching I can't figure out the answer.
I currently have a MySQL table in my local database used by a webapp, and them same table on a database in a remote server. Right now, I'm using the CREATE TABLE IF NOT EXISTS command through PHP to create the table on the databases:
CREATE TABLE IF NOT EXISTS users (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(18) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
However, let's say I make a modification to the local database, adding a collumn, for example. It would be really annoying to have to go and change the remote database every time I change the local one. Is there an easier way to run code to create a table if it doesn't exist, and if it does exist, make sure it's structure matches that of the create table structure?
Here's an example, to make what I'm trying to convey a little clearer. Let's say on the local database I have a users table, and I decide that in my webapp I want to have another collumn, password. So I go to the local database and add a password collumn. Is there PHP/MySQL code I can run to check if the users table exists, and if it does, make sure it has a password collumn, and if not, add it?
What you are actually looking for are Migrations, e.g. you are looking for a Schema Management Tool that lets you manage your Database structure in versioned code diffs.
For instance, for your described scenario you would first create a script to create the table, e.g. 001_create_user_table.sql. Then you'd use the schema manager to connect and deploy these changes to your databases.
When you want to change or add something, you just write another script, for instance, 002_Add_Password_Column_To_User_Table.sql. Fill in just the code to do that change. Then run the schema manager again.
Typically, you tell the Schema Manager to go through all existing migrations files. On each run, the Schema manager will update a changelog table in the database, so when you run it, it will know which of your scripts it should apply.
The good thing is, you can add these migrations to your regular VCS, so you will always know which database schema you had at which version of your application. And you will have a proper changelog for them.
To directly answer your question you can create temporary procedures to detect field existence like using a query like this:
SHOW COLUMNS FROM table_name LIKE 'column_name';
However in the real world, database changes are general rolled into three scripts. A create script and two deltas one up and one down. Then the database is versioned so that you know at what state the database is in at any given time.
To specifically check for a password column you can use DESCRIBE:
$colExists = false;
$res = mysql_query('DESCRIBE `users`');
while ($row = mysql_fetch_assoc($res)) {
if ($row['Field'] == 'password') {
$colExists = true;
break;
}
}
if (!$colExists) {
// create column
}
However, you should check into replication or some other automated tool to see if they would be a better solution for you.
Follow these steps (you can easily implement this in PHP, I assumed that the name of the table is Foo)
1.) Run the following code:
desc Foo
2.) Based on the result of the first step you can make your create table command (and you should)
3.) Store your data from the existing table which will be replaced in a variable (Optional, you only need this if you can potentially use data from the old table)
4.) Modify the extracted rows from step 3.) so they will be compatible with your new definition (Optional, you only need this if you can potentially use data from the old table)
5.) Get the rows from your new Foo table
6.) Merge the results got in steps 4.) an 5.) (Optional, you only need this if you can potentially use data from the old table)
7.) Run a drop table for the old table
8.) Generate a replace into command to insert all your rows into the newly created Foo table (you can read more about this here)
After these steps, as a result, you will have the new version of the table. If your tables are too large, you can do a CREATE TABLE IF NOT EXISTS command and if that was not successful, run the alter command.
Also, you can make a library to do these steps and will use that in the future instead of solving the same problem several times.
EDIT:
You can connect the database using this function: mysql-connect (documentation here)
You can run a query using this function: mysql-query (documentation here)
Based on the first step you will get the field names (let's assume you store it in a variable called $bar) and you can use your result to generate your select command (connecting to the database where you have important data. It may be both):
$field_list = "1";
foreach ($bar as $key => $value)
$field_list.= ",".$bar[$key];
mysql_connect(/*connection data*/);
mysql_query("select ".$field_list." from Foo");
You can use your new resource to build up an insert command to insert all your important data after deletion recreation (about resources read more here, about how you can generate your insert you can read here, but I suggest that you should use replace into instead of insert which works like the insert, except that it replaces the row if it already exists, it's better here than an insert, read more here)
So, use mysql_connect and mysql_query, and the resource returned by the mysql_query function can be used for replace into later (I've linked now the URL's for everything you need, so I'm pretty sure you'll solve the problem.), apologies for being not specific enough before.

Categories