Dummy SQL query - php

I am creating an install file for a script I created and will also provide the fields to enter the database details. Anyway, before storing those database details in a config.php file, I'd like to see if they work. What would be the best way to see if the provided details are valid? I thought of running a dummy query and if it's successful then store the details in a file. I don't know what the best query would be? I am using PDO for the whole thing. So, I basically need to check if a database connection succeeded in order to continue.
Could you please tell me your ideas how to verify if everything is alright with the user input? Is my dummy query idea a good way to handle this? If yes, what query should I run? If no, what do you suggest?
Thanks.

If you are using sql server somethig like "select 1" will do the job. I guess many other database engines will support this query too.

The best thing to do would be to issue a series of queries/commands that test every thing you need individually.
Can open connection
Database is there/can be created
User can see data/can construct data
etc..
Then as part of the installation you can tell the user if something isn't right and point them directly at the problem for them to solve. You should do this early in the installation so that you don't have to roll back too much.
Think about the installation experience. What would you want when installing a program. Would you like it to just say
"Error. Can't connect",
or
"Error: Cannot connect to DATABASEX the SERVERY with the USERID_W",
or even better
"Error: Can connect to the DATABASEX the SERVERY with the USERID_W, but table X is missing, have you completed step ABC first?"
Do as much work as you can for the user.

First of all, check if PHP connects to the database correctly (returned values, mysql errors). Then You can use something like SHOW VARIABLES LIKE "%version%" to determine the database engine version, so all functions and methods will work as intended. This way You can also inform Your users, that their db version is to old to be used with Your software.
EDIT
Also, a query of SHOW GRANTS FOR 'user'#'host' is a good idea to check permissions for connected user

Well, you can assume the connection is successful if the connection function returns the expected value without generating any errors/exceptions. Aside from that...
SHOW TABLES FROM $database;
Should show that they have at least basic permissions to the database, but won't indicate if they can create tables and insert data.

Related

Recreate a database using existing php code

So I have an old website which was coded over an extended period of time but has been inactive for 3 or so years. I have the full PHP source to the site, but the problem is I do not have a backup of the database any longer. I'm wondering what the best solution to recreating the database would be? It is a large site so manually going through each PHP file and trying to keep track of which tables are referenced is no small task. I've tried googling for the answer but have had no luck. Does anyone know of any tools that are available to help extract this information from the PHP and at least give me the basis of a database skeleton? Otherwise, has anyone ever had to do this? Any tips to help me along and possibly speed up the process? It is a mySQL database I'm trying to use.
The way I would do it:
Write a subset of SQLi or whatever interface was used to access the DB to intercept all DB accesses.
Replace all DB accesses with the dummy version of yours.
The basic idea is to emulate the DB so that the PHP code runs long enough to activate the various DB accesses, which in turn will allow you to analyze the way the DB is built and used.
From within these dummy functions:
print the SQL code used
regenerate just enough dummy results to let the rest of the code run, based on the tables and fields mentioned in the query parameters and the PHP code that retrieves them (you won't learn much from a SELECT *, but you can see what fields the PHP code expects to get from it)
once you have understood enough of the DB structure, recreate the tables and let the original code work on them little by little
have the previous designer flogged to death for not having provided a way to recreate the DB programatically
There are currently two answers based on the information you provided.
1) you can't do this
PHP is a typeless language. you could check you sql statements for finding field and table names. but it will not complete. if there is a select * from table, you can't see the fields. so you need to check there php accesses the fields. maybe by name or by index. you could be happy if this is done by name, because you can extract the name of the fields. finally the data types will missing. also missing: where are is an index on, what are primary keys, constrains etc.
2) easy, yes you can!
because your php is using a modern framework with contains a orm. this created the database for you. a meta information are included in the php classes/design.
just check the manual how to recreate the database.

How do I restrict MySQL user from dropping, and adding tables and databases

I am trying to find the SQL command to create a user that can read and write in tables found in one database, but is not allowed to do anything else.
Also if you can recommend other limits I should add to the MySQL user I would appreciate it.
The reason I am asking is because one of my tables was dropped and I have no idea how... I think it's PHP but I am not sure... Maybe someone connected via my SSH... The thing is all my mysql logs are empty and no evidence of a another user trying to do something are to be found in the other logs...
So for now I am assuming there is something wrong with my PHP... This is why I would like to limit it to only adding, removing, and dropping rows and content in the rows... But not more. So that I don't loose my table again or my other DBs.
Create the user using CREATE USER, and specify the privileges using GRANT.
http://dev.mysql.com/doc/refman/5.1/en/grant.html (click here for a list of MySQL privileges)
If you have phpMyAdmin running, the interface will give you a complete set of privileges to check/uncheck :)
For a basic web application, you'll only need SELECT, INSERT, UPDATE and DELETE :)
If you think there was a security issue with your application, check this page to know more.

Amending the CodeIgniter Active Record Query command?

I am developing a Codeigniter (2.0.2) Application, which will utilise a Master database for all write operations (INSERT/UPDATE/DELETE) and a read replica for all read operations (SELECT).
Now I know I can access two different database objects within the code to route the individual requests to the specific database server, but i'm thinking there has a better way, automated way. I'll be using MySQL and Active Record, and also want to build in Memcache checking - although it won't be used immediately, I'd like the option there for the future, built in at this stage.
I'm thinking if its possible to add a hook/library of some kind to intercept the $this->db->query so that the following happens:
1) SQL Query received
2) Check if SELECT query
2a) If SELECT, see if Memcache is active, if so encode SQL and check Memcache for response.
2b) If no memcache response, or Memcache is not active, execute query as normal through READ MySQL server.
3) Query was NOT select, so execute query as normal through the WRITE MySQL server.
4) Return response.
I'm sure that looking at this, it should be quite simple to do, but no matter how I look at it i'm just not seeing a potential answer - but there's got to be one! Can anyone help/assist?
In addition, I also want the ability to be able to log all write SQL commands for troubleshooting, presumably the best way is to introduce 3a) Write SQL command to plain text file ... into the above scheme. I don't believe MySQL actually logs the non-SELECT queries in anyway ... does it?
That type of behavior is a little bit beyond the normal scope of CI. Unfortunately, your best bet is to manually extend the database drivers, specifically override the function simple_query or _execute (simple_query is a wrapper around _execute which simply ensures initialization). That is really the only place where you can guarantee that you can catch all of the queries and branch the logic accordingly. (You may also want to override close as that is the cleanup script)
(Personally, I would have a the SELECT DB load a secondary DB into itself and just call $write_db->simple_query conditionally, that seems like it would be the least trouble).

MySQL Triggers: How to know which script called it?

I have a mysql trigger that logs every time a specific table is updated.
Is there a way to also log WHICH PHP SCRIPT triggered it? (without modifying each php script of course, that would defeat my purpose)
Also, is there a way to log what was the SQL statement right before the UPDATE that triggered it?
Thanks
Nathan
Short answers: no and no. Sorry.
What are you trying to achieve? Perhaps there's another way....
no, but you can get some more specific direction.
first, if you're using persitent connections, turn them off. this will make your logs easier to use.
second, since it sounds like you have multiple code bases accessing the same database, create a different user for each code base with exactly the same rights and make each code base log in with a different user. now when you look at the log, you can see which application is doing what.
third, if you have the query log on, then the UPDATE immediately preceding the trigger will be the UPDATE that caused the trigger.
fourth, if your apps use any sort of encapsulation for the mysql connection, it should be trivial to modify it to write the call stack at the time a query is sent to the database to a file.
I've read through a few of the answers and the comments. I had one idea that would be usefuls only if your queries are passing through a single point. For example, if you have a database class that all queries are executed through.
If that is the case, you could possibly add a comment to the query itself. The comment would include the function call trace, and would be added to the query as an SQL comment.
Next, you would turn query logging on and be able to see where each query is getting called from in the log file.
If your queries do not pass through a single point, you may be out of luck.
One final suggestion would be to take a look at MySQL Proxy. I have not used it much but it is designed to do intermediate processing of queries. However, I still think you would need to modify your PHP scripts to pass additional information.

Live update notification on database changes MYSQL PHP

I was wondering how to trigger a notification if a new record is inserted into a database, using PHP and MySQL.
You can create a trigger than runs when an update happens. It's possible to run/notify an external process using a UDF (user defined function). There aren't any builtin methods of doing so, so it's a case of loading a UDF plugin that'll do it for you.
Google for 'mysql udf sys_exec' or 'mysql udf ipc'.
The simplest thing is probably to poll the DB every few seconds and see if new records have been inserted. Due to query caching in the DB this shouldn't effect DB performance substantially.
MySQL does now have triggers and stored procedures, but I don't believe they have any way of notifying an external process, so as far as I know it's not possible. You'd have to poll the database every second or so to look for new records.
Even if it were, this assumes that your PHP process is long-lived, such that it can afford to hang around for a record to appear. Given that most PHP is used for web sites where the code runs and then exits as quickly as possible it's unclear whether that's compatible with what you have.
If all your database changes are made by PHP I would create a wrapper function for mysql_query and if the query type was INSERT, REPLACE, UPDATE or DELETE I would call a function to send the respective email.
EDIT: I forgot to mention but you could also do something like the following:
if (mysql_affected_rows($this->connection) > 0)
{
// mail(...)
}
One day I ask in MySQL forum if event like in Firebird or Interbase exist in MySQL and I see that someone answer Yes (I'm really not sure)
check this : http://forums.mysql.com/read.php?84,3629,175177#msg-175177
This can be done relatively easily using stored procedures and triggers. I have created a 'Live View' screen which has a scrolling display which is updated with new events from my events table. It can be a bit fiddly but once its running its quick.

Categories