Can I add some PHP code into an SQL query? - php

I am currently running a script that pulls back transaction data (one line for each transaction) from a database with the following SQL script, which is being run in MySQL Workbench.
SELECT
id,
merchant_id,
affiliate_id,
date,
sale_amount,
commission,
ip
FROM transactions.transaction201505
One of the columns in the table t.transactions is IP address. Is there a way to embed this PHP script (or a function to this effect) within an SQL script:
php function geoip_country_name_by_addr http://php.net/manual/en/function.geoip-country-code-by-name.php
I have seen many examples of adding MySQL to PHP but would like to essentially add in Country/ City of sale to my data the other way around, so that the result could look like the sample below, which could be run off a tool such as MySQL Workbench. I don't have access to run PHP scripts on this database, and therefore need a solution with SQL.
Thanks in advance for any help you can offer on this.
Jamie

No, this is not directly possible. You could write a UDF (user define function) in an exteranl module (e.g. a .DLL, .so or .dylib) but using PHP in such a module is probably not possible either (because PHP is a scripting language and you would need to compile your UDF into binary code). However, MySQL has a number of built-in functions (https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html). Even though not what you want here.

Related

is there a tool or any quick way to extract db tables automatically from my php codes?

I recently started to re-engineer a PHP-mysql project which was created about 7 years ago. I have only php and html codes and no mysql database or any document which shows the database structures.
Is there any tool which help me extract the tables of my database using php files? in the php files i have insert queries and select queries and also update.
I think of a tool (such a crawler) which takes my php files as input and create some sql create table queries as output.
I'm afraid there is no such tool. There's no guarantee that your PHP code even makes reference to every table or every column. You might see code like this:
mysqli_query("INSERT INTO mytable VALUES ('1234', 'abc', NULL, DEFAULT)");
What are the column names? What are their data types? Is the first column an integer, or is it just the developer's habit to put numbers inside string delimiters? What's the default value referenced by the fourth column? How could an automated tool infer these things by scanning this code?
Many details such as triggers, constraints, and indexes, are not referenced at all by PHP code, but they're necessary to make the application work.
If the database has any stored procedures, the PHP code wouldn't have any knowledge of the logic inside the procedure.
mysqli_query("CALL myprocedure(1234, 'north')");
The same problem exists for the query in VIEW definitions.
Reverse engineering this project is going to be a time-consuming forensic task, plus a lot of guesswork.
It really illustrates the importance of including the current schema dump with the source code of a project.

Postgresql COPY bulk data from within PHP script - ideally using ADODB

I have custom software which includes a function to copy data between tables on postgresql servers. It does this 1 row at a time, which is fine when the servers are close together, but as I've started deploying servers where the latency is > 300ms this does not work well at all.
I believe the solution is to use the "COPY" statement, but I am having difficulty implementing it. I am using the ADODB php library
When I attempt a copy from a file I get the error "must be superuser to COPY to or from a file". The problem is that I don't know how to copy "from STDIN" where stdin is not actually piped to the PHP script. Is there any way to provide the stdin input as part of the sql command using ADODB, or is there an equivalent command which will allow me to do a batch insert without waiting for each individual insert ?
Postgresql extension dblink() allows you to copy data from one server's database to another. You need to know the ip address of the server and the port the database is running on. Here are some links with more info:
http://www.leeladharan.com/postgresql-cross-database-queries-using-dblink
https://www.postgresql.org/docs/9.3/static/dblink.html
I solved the problem by using an insert command which had all the inserts in a single statement using "union all" - ie
$sql="INSERT INTO tablename (name,payload)
select 'hello', 'world' union all
select 'this', 'is a test' union all
select 'and it', 'works'";
$q=$conn->Execute($sql);
One limitation of this solution was that strings need to be enquoted while integers for example, must not be. I thus needed to write some additional code to make sure some fields were enquoted but not others.
To find out which columns needed to be enquoted I used
$coltypes=$todb->GetAll("select column_name,data_type
from information_schema.columns
where table_name='".$totable."'");

Displaying results of many sql queries without writing PHP code?

Sorry if this question might sound stupid to you guys, but am total newbie to programming, apart from knowing SQL, the thing is i have been given a MYSQL database containing various information about kids diseases and a web interface written in php to create reports from the database that can be accessed via the interface. there are almost 25 different variables that need to be computed in the report, i have written sql queries to compute all these values, but i don't know anything about PHP, if i have all these queries isn't there a way for me to combine all these sql queries to be display results on a webpage and come up with this report without writing PHP code?
Thanks for your
again very sorry if this is too basic.
As mr_jp suggests, phpmysqladmin provides a simple front end for running queries, but also changing the data and modifying the schema. Although you can restrict named users to only have SELECT privilege, they'll still need to know SQL to run the queries.
It's not that hard to build a front end to take a set of parameters, substitute them into a SELECT statement and send the output to a formatted table. There are lots of datagrid tools (e.g. phplens, phpgrid, have a google for 'mysql datagrid' for more) which will handle the formatting of a MySQL resultset (or just download it as CSV - your browser should be able to transfer the data into your spreadsheet program automatically).
There are a couple of report generators for PHP - but the last time I looked at this in any depth, I wasn't overly impressed.
Your web host would probably have phpmyadmin installed. Try getting access from the web host.
You can enter your queries there and export the results as html, csv, excel and others.
You could write Python. Or Ruby. Or something you know. ;-)
But you need something to output your queried data.
If you just want to check the results by yourself without having the needs to publish that directly, you might use some MySQL query browser or administrator like phpMyAdmin or the MySQL Workbench. Those tools allow you to query the database but display the returned data only as raw tables. If you need some styling or your own layout, you'll have to use an own application or edit the exported data manually (e.g. using a CSV export and re-open it using some spreadsheet application like Excel or Calc).
The combination PHP + MySQL is a very popular one and it's highly recommended that you use them together.
The code that you will need to write in order to display that information using PHP is pretty straightforward and not very hard. If you do know some basic programming concepts, you can learn to do that in a matter of hours. PHP is well known for its extremely accessible learning curve. There are thousands of code samples online that you can look at to see how this is done.

ODBC: when is the best time to create my database?

I have a windows program which generates PGP forms which will be filled in later.
Those PHP forms will populate a database. It looks very much like MySql, but I can't be certain, so let's call it ODBC.
And, yes, it does have to be a windows program.
There will also be PHP forms which query the database - examine which tables and fields it contains and then generates forms which can be used to search the database (e.g, it finds a table with fields "employee_name", etc and generates a form which lets you search based on employee name.
Let's call that design time and run time.
At design time, some manager or IT guy or similar gets to define the nature of the database and at runtime 1) a worker fills in the form daily and 2) management can extract reports.
Here's my question: given that the database is defined at "design time" (and populated at run time), where and how is best to do so?
1 I could use an ODBC interface from the windows program, but I am having difficulty finding something good to work with Delphi. Things like ADO and firebird tend to expect you to already have a database and allow you to manipulate it, but I can find no code example of how to create a database and some tables, so ...
2 I could used DOS commands from Delphi in my windows program. I just tried and got a response to MySql --version, but am not sure if MySql etc are more interactive. That is, can I use a script file or a very long stacked command with semicolons and returns separating? e.g 'CREATE DATABASE db; CREATE TABLE t1;'
3) Since the best way to work with databases seems to be PHP, perhaps my windows program could spit out a PHP page which would, when run in a browser, create the database.
I have tried to make this as uncomplicated as I can, but please feel free to ask questions. It may be that there are several valid ways, but there is probably one 'better' solution in terms of ease of implementation or maintenance.
Better scratch option 3. What if the user later wants to come back and have the windows program change the input form? It needs to update the database too.
Creating a database is usually a database administrator task. Unless it is a local database, maybe an embedded one, the user would need to know where and how create the database on the remote server, and she can have no clue about it. Where to store the database files? Which disks are available? And there could be many more parameters to set (memoery buffers size, etc.), users to be created and so on. And also you need very elevate privileges to be able to create a database, not something you give to average users or applications.
Thereby usually you ask the database administrator to create your database/schema, he will give you the credentials you need to connect, and then your application (or its setup) will create and initialize the needed objects (tables, etc.). Creating table (and other object) is usually as simple as running "CREATE TABLE...." statements. Just remember SQL takes one command only, if you need to run several commands you have to send them one after another yourself, although there are Delphi components which are able to split a script in commands and run one after another.

Running a list of MySQL queries without using exec()

I've got a site that requires manual creation of the database tables on install. At the moment they are saved (along with any initial data) in a collection of .sql files.
I've tried to auto-create using exec() with CLI MySQL and while it works on a few platforms it's fairly flakey and I don't really like doing it this way, plus it is hard to debug errors and is far from bulletproof (especially if the MySQL executable isn't in the system path).
Is there a better way of doing this? The MySQL query() command only allows one sql statement per query (which is the sticking point).
MySQLi I've heard may solve some of these issues but I am fairly invested in the original MySQL library but would be willing to switch provided it's stable, compatible and is commonly supported on a standard server build and is an improvement in general.
Failing this I'd probably be willing to do some sort of creation from a PHP array/data structure - which is arguably cleaner as it would be able to update tables to match the schema in situ. I am assuming this may be a problem that has already been solved, so any links to any example implementation with pro's/con's would be useful!
Thanks in advance for any insight.
Apparently you can pass 65536 as client flag when connecting to the datebase to allow multi queries, e.g. making use of ; in one SQL string.
You could also just read in the contents of the SQL files, explode by ; if necessary and run the queries inside a transaction to make sure all queries execute properly.
Another option would be to have a look at Phing and dbdeploy to manage databases.
If you're using this to migrate data between systems, consider using the LOAD DATA INFILE syntax (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) after having used SELECT ... INTO OUTFILE (http://dev.mysql.com/doc/refman/5.1/en/select.html)
You can run the schema creation/update commands via the standard mysql_* PHP functions. And if the query() command as you call it will allow only one statement, just call it many times.
I really don't get why do you require everything to be in the same call.
You should check for errors after each statement and take corrective actions if it fails (unless you are using InnoDB, in which case you can wrap all statements in a transaction and rollback if it fails.)

Categories