Slow query on remote database - php

I have:
A linux server with PHP 5.3.2 and Apache 2.0
A windows Server with SQL SERVER
I connect my linux server with database with unixODBC 2.3.1 and FREETDS 0.9.1
The connection is okay but the queries are slow.
Here is my code that generate the image below:
$this->adodb->LogSQL(true); // turn on logging
$query = "select c.name, t.name, c.length from syscolumns c join systypes t on t.xusertype = c.xusertype
join sysobjects o on o.id=c.id where o.name = 'CONDOMINIO'";
$res = $this->adodb->Execute($query);
$this->adodb->LogSQL(false); // turn off logging
$perf = NewPerfMonitor($this->adodb);
echo $perf->SuspiciousSQL();
echo $perf->ExpensiveSQL();
Image http://www.vigoonline.net/slow.png
As you can see, the first query has an average time of 4.68 seconds, which is way too slow.
If I execute the same query like this:
$this->adodb->_query($query);
Then the time to execute the query takes less than a second what is great. Has anyone else experienced the same thing?
The query called with "Execute" is used for the own class for bringing the "MetaColumns" information from the table
The table "CONDOMINIO" only has 21 rows.
If the server database is in the same machine with the application script, then the response is fast!

I resolved this myself.
Here is what I did:
Go to the file /adodb/drivers/adodb-odbc.inc.php and to the class ADODB_odbc
Here try to find:
var $curmode = SQL_CUR_USE_DRIVER
and change it to:
var $curmode = SQL_CUR_USE_IF_NEEDED;
This will make the connection use SQL_CUR_USE_ODBC when needed and "Voila" DB access speed to SQL server is really fast!

Related

mssql_connect will not connect different DB on same SQL Server

$conn_161 = "192.168.0.161"; //local serwer adress
$user_161 = "ME";
$pass_161 = "what_is_the_password?";
$connect_161 = mssql_connect($conn_161,$user_161,$pass_161);
mssql_select_db ( 'DUKENUKEN3D' , $connect_161 );
//as requested - 1st DB connection and 1st query
$q_duke = "select * from DUKE /*DB1*/";
$r_duke = mssql_query($q_wartownik,$connect_161); //result
$connect_different_db = mssql_connect($conn_161,$user_161,$pass_161);
mssql_select_db ( 'BIGMAN' , $connect_different_db );
//second db and query
$q_bigman = "select * from BIGPEOPLE /*DB2*/";
$r_bigman = mssql_query($q_bigman,$connect_different_db ); //result
Error:
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'DUKE'.
Yes I know mssql_select_db is old, but I need to use it in this project. As you see I try to connect to same server but select 2 different DB at the same time, and run queries in the same php page (to connect data from 2 different DB). It seems it is not valiable? I even tried to run mssql_select_db just before doing the query to second DB, and then changing it back to first DB.
I understand this is limitation of the library (I will run all queries from LAST selected DB).
Is there a workaroud? Because all I got is to create page inside invisible iframe and there run php page with different db connection - far from good solution.
I would expect that this will work the same as it would if you were running this in a SQL environment directly (e.g. you can try it in SSMS or from the command line).
You can specify the database name when you reference the table in the query: e.g.
select * from db1.dbo.DUKE
This is standard SQL Server behaviour whenever you want to refer to an object which is outside the context of the current database.

Trouble using psql meta-commands in php for \copy export csv

I'm trying to export a csv file from a linux machine to a local PC via a PHP script on a browser.
I've done a good bit of research, but I can't find what I'm looking for (maybe it doesn't exist).
My script connects to the database via php and uses localhost as do my other php scripts that just display data from the database but don't export the data.
Here is my futile attempt:
$user = 'postgres';
$password = 'XXXXX';
$db = 'ltg';
$host = 'localhost';
$conn=pg_connect('dbname ='.$db.' user = '.$user.' password = '.$password.' host = '.$host) or die ("Could not connect: ");
//query for copying/exporting to csv
echo "system(\copy (select lat, lon from ltg_data order by time desc limit 1000) To '~/Downloads/export.csv' CSV HEADER);"
There are two issues, at least, that I'm confused about. The connection to the db works fine for accessing/display data from db. Do I need to use something other than "localhost" to export data?
Second, running the \copy command is problematic. I somehow need to run a psql meta-command to export the data, and I really don't know how to do that via php.
Thanks very much for your time.
The problem is that system runs a shell command (not sure why you're echoing it?), so it doesn't go through $conn at all. And of course there is no shell command called \copy.
If you want you can send a \copy ... to psql with something like system("echo '\copy ....' | psql"), but you'll have to be careful with escaping the parameters etc.
Since your database is on localhost and you're already connecting with the postgres user, you could just use COPY instead of \copy, and send the command via $conn.
Here is documentation about COPY.

Php adodb CacheExecute com_exception arguments wrong type

I'm trying to get ADODB caching to work. I have a php script where i define the DB connection.
global $conn;
$conn = new COM ("ADODB.Connection");
$connStr = "PROVIDER-SQLOLEDB;SERVER=;UID=;PWD=;DATABASE=);
$conn->open($connStr);
I left the unnecessary details out of the picture.
Then in some other script i import the connection.php, and then try to make a normal query.
$query = "SELECT * from table where some_id = 21540 and other_id = BOGUS_INFO"
$rs = $GLOBALS['conn']->CacheExecute(60,$query);
This returns Uncaught exception 'com_exception'.. ADODB.Connection Arguments are of the wrong type,are out of acceptable range, or are in conflict with another.
I'm baffled because the next line of code works flawlessly.
$rs = $GLOBALS['conn']->execute($query); //OK!
Any ideeas?
I also tried CacheGetOne but i get the same error.
Could it be from the way i defined this thing below? (it's literally like that in my code)
$GLOBALS['ADODB_CACHE_DIR']=$_SERVER['DOCUMENT_ROOT'].'/../cache/adodb';
Well after alot of hassle, i kinda found an answer by choosing another way of doing things. I downloaded the latest ADODB build. Inserted it in my project, and modified files accordingly:
The connection.php changed to:
require('PATH/adodb.inc.php');
require('PATH/adodb-csvlib.inc.php');//read somewhere that i need this for the caching executes
$GLOBALS['ADODB_CACHE_DIR'] = $_SERVER['DOCUMENT_ROOT'].'/cache/adodb';
global $ADODB_CACHE_DIR; //don't know which one adodb usese really to identify cache directory so for safety - both
$ADODB_CACHE_DIR = $_SERVER['DOCUMENT_ROOT'].'/cache/adodb';
$conn = NewADOConnection('mssqlnative');//i tried first with mssql simple but script terminated execution on execute() attempt.. no error.. no nothing.. no output .. strange
$conn->Connect($myServer, $myUser, $myPass, $myDb);
After that i had to fiddle a bit with the code because,
$rs = $conn->CacheExecute(time,query)
returns Adodbrecordset_array_mssqlnative Object, and not an array, and, in my code i used to display and manipulate values as
while (!$rs->EOF) {
$rs['row']->value;
$rs->MoveNext();
}
and now they should be
$rs->fields['row'];
Another tricky thing was getting the fields array to be associated to the names of the columns in my query, but after a short search i discovered
$GLOBALS['conn']->SetFetchMode(ADODB_FETCH_ASSOC);
and voila! Everything works, even the caching.
It took script execution times with this bare optimisation from 1 sec to 0.1 or even 0.005 sometimes.

Different SQL result with same query in PHP and MySQL

After a quick search, I haven't find solution of my problem so I post a new one.
So I have to create view in a MySQL database from a Web interface (using PHP).
I use a PEAR framework for the connection with MySQL(5.0.26)
I have the SQL request :
CREATE VIEW test AS SELECT cswc.code_de_la_copie, cswc.service_de_reference, cswc.libelle_de_la_copie, cswc.direction_de_securite_logique
FROM pressi_copiesServiceWithCibles cswc LEFT OUTER JOIN pressi_servicesReferenceWithCibles srwc ON cswc.service_de_reference = srwc.code_du_service
WHERE cswc.cible is null
AND (srwc.cible LIKE '%£DOMAIN£%' OR srwc.cible LIKE '%$DOMAIN$%');
When I execute this request directly on mon local MySQL Database, I obtain a result with 470 lines.
However, when I execute this request in my PHP code, I have a different result (I have 386 line), and I don't know why !
$values['request'] = "SELECT cswc.code_de_la_copie, cswc.service_de_reference, cswc.libelle_de_la_copie, cswc.direction_de_securite_logique
FROM pressi_copiesServiceWithCibles cswc LEFT OUTER JOIN pressi_servicesReferenceWithCibles srwc ON cswc.service_de_reference = srwc.code_du_service
WHERE cswc.cible is null
AND (srwc.cible LIKE '%£DOMAIN£%' OR srwc.cible LIKE '%$DOMAIN$%');";
$baseView = "test";
$sqlView = 'CREATE VIEW '.$baseView.' AS '.$values['request'];
$res =& $this->mdb2->query($sqlView);
if (PEAR::isError($res)) {
return false;
}
Moreover, I have already create 6 views before this one without any problem (same result in PHP and in MySQL)
Thank you for your help
Note that your connection to the database also has a CHARSET and a COLLATION for any string values you include in your query. Although your query looks the same to you in both situations, it must not from the MySQL servers point of view.
Maybe the client CHARSET (and/or COLLATION) differ when you connect via PHP from when you connect via MySQL console.
See the MySQL manual for more information on the client charset and collation.
For comparison, you can use this query:
SHOW VARIABLES LIKE 'character_set%';
SHOW VARIABLES LIKE 'collation%';

JOIN not working with PHP + ODBC + Microsoft Access

I am trying to write a PHP script that plugs into an existing Access Database. If I would be starting from scratch, I would have used MySQL for the job, but because there is an existing MS Access application I am stuck with the database as it is.
As of right now, I am trying to get the following PHP Code to work.
$conn=odbc_connect('buju','','');
if (!$conn)
{
exit("Connection Failed: " . $conn);
}
$sql="SELECT *
FROM Teilnehmer
INNER JOIN TeilnWerte ON Teilnehmer.LfdNr = TeilnWerte.Teilnehmer
WHERE Teilnehmer.Klasse = '$_POST[klasse]'";
$rs=odbc_exec($conn,$sql);
echo "\nErrorCode:\n".odbc_error($conn);
echo "\nErrorMessage:\n".odbc_errormsg($conn);
I am pretty sure, that the problem is in the SQL Query, since it all works fine if I only do
SELECT * FROM Teilnehmer WHERE Klasse = '$_POST[klasse]'
without trying to join the second table.
I am using odbc and the Microsoft Access Driver. The Error Code that I get is 07001. The Error Message is
[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
I have also tried
SELECT *
FROM Teilnehmer, TeilnWerte
WHERE Teilnehmer.LfdNr = TeilnWerte.Teilnehmer
AND Teilnehmer.Klasse = '$_POST[klasse]'
which did not work either.
Is there anything that I am doing wrong? Are there certain SQL commands that don't work
Since echo $sql gives you ...
SELECT *
FROM
Teilnehmer
INNER JOIN TeilnWerte
ON Teilnehmer.LfdNr = TeilnWerte.Teilnehmer
WHERE Teilnehmer.Klasse = '06A'
Test that same statement as a new query in Access. Create a query in the query designer, switch to SQL View, paste in the statement and see what happens when you run it.
Most often the cause of "Too few parameters" is a misspelled item (object name, function or SQL keyword). Since the db engine can't find that item, it assumes the item is a parameter. Access will pop up a parameter dialog asking you to supply a parameter value, and that dialog also contains the parameter's name. So it tells you which is the misspelled item.

Categories