pg_close must to wait query end - php

I'm making a function that register a big CSV data file so i am searching the ways that can send asynchronous query to postgre sql server and receive query result later.
I tried to use pg_send_query to send SQL(that take time to query) like bellow.
SQL
$sql = SELECT * FROM BATCH_WORK_TBL WHERE COPR_ID='99999999test';
PHP script
//-----------------------------------------------
// DB Conntect
//-----------------------------------------------
$conn = pg_connect('user=username dbname=databasename');
//-----------------------------------------------
// Send asynchronous query
//-----------------------------------------------
$sql = " SELECT * FROM BATCH_WORK_TBL WHERE COPR_ID='99999999test' ";
if (!pg_connection_busy( $conn )) {
$res = pg_send_query($conn , $sql ); // pg_send_query return result(true/flase) without wait results
}
pg_close($conn); // pg_close wait until it query return result
however, when i close connection,pg_close() wait for a long time until query return query result so finally my php script take a long time run.
Any body if has experience on asynchronous query on posgres sql with php, could you pls help me in this case?

That cannot work. Something has to keep the database connection open so that the query result can be received.
You can either keep the connection open, do some other work and come back later to check on the connection, or you write a co-process that does that waiting for you (and has the database connection).

Related

Mysqli_result availability

Can you still use a mysqli_result object after you have closed the mysqli connection that produced it? For instance, I am creating a PHP object with a method that opens a mysqli connection, performs a query, stores the result into a parameter, then closes the connection. Will this work or should I fetch_all() the result into an array and then close the connection?
I can find nothing in the documentation or elsewhere online that answers this question. Perhaps that is because it is mind-boggingly obvious to everyone else but it is not to me.
Yes. By default, mysqli runs queries with the option MYSQLI_STORE_RESULT, which means it copies the result set to the client (into the memory of the PHP driver). Therefore when you "fetch" from a mysqli result, you're really just looping over the result set that has already been completely fetched from the MySQL Server. And if you close the connection, the driver keeps that data.
Here's a quick code example to demonstrate:
$con = new mysqli(...);
sleep(10);
/* go run SHOW PROCESSLIST in a MySQL shell to see the connection */
$sql = "SELECT SLEEP(10) FROM test.foo ";
$result = $con->query($sql);
/* observe the query running in SHOW PROCESSLIST */
$con->close();
sleep(10);
/* now go look at SHOW PROCESSLIST to verify the connection is gone */
print_r($result->fetch_all());
/* Hey! I got the data anyway */

execute mysql query and display results while reading

I have a mysql database and i want to execute a query and while this query is being executed the data should be displayed in page.
so for example if i have 1,000 result row from the query result i want to display each row while the query is being executed instead of waiting till the query finishes executing then displaying them at once.
here is my php code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Database Name
mysql_select_db("dbname", $con);
$test_query = mysql_query("SELECT * FROM V_Posts where _PID > 100 and _PID < 10000");
while($CHECK_PCID_R = mysql_fetch_array($test_query))
{
echo $CHECK_PCID_R['_PID'] . "<br />";
}
?>
I tried
echo $CHECK_PCID_R['_PID'] . "<br />";
flush();
But it didn't work :(
One query will produce one dataset and you'll have all the data at once. If your query is slow any latency in displaying the data will be small compared to the delay in receiving it. Using flush() might force the server to send parts of the page, but you're really just tinkering at the edges.
If you want to break this down you'll have to run multiple queries, which will arguably be much slower since you'll be running the same query repeatedly. This will load the database server unnecessarily, and will achieve only a minor cosmetic effect.
If you use an AJAX call to retrieve your data you can display a 'loading' message while you wait. You could use multiple AJAX calls to display the data bit by bit - this is even worse than using multiple queries in the PHP script.

Why I am getting the Error "Commands out of sync; you can't run this command now"

The Documentation of the Error Mentioned in the Title Says
If you get Commands out of sync; you can't run this command now in
your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and
try to execute a new query before you have called mysql_free_result().
It can also happen if you try to execute two queries that return data
without calling mysql_use_result() or mysql_store_result() in between.
From here: http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html
But In First Query I am not fetching any data from mysql database, I am just inserting. And In second Query I am getting the data from database.
Here is My code
$connection = mysqli_connect("localhost","username","password","tbl_msgs");
if(mysqli_connect_errno($connection))
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$query = "INSERT INTO users (total_comments, total_views)
VALUES ({$total_comments}, {$total_views});";
$query .= "INSERT INTO msgs (notifications) VALUES ({$notifications})";
mysqli_multi_query($connection,$query);
Upto this Step every thing is fine. But When I execute the following query It gives the Error
$select_query = "SELECT * FROM msgs WHERE msg_id = {$msg_id}";
$result_set = mysqli_query($connection,$select_query);
if(!$result_set) {
die(mysqli_error($connection));
}
Here it gives the Error Commands out of sync; you can't run this command now. I can't understand this situation
Note: There is any Problem in the Query, I have executed the same query directly to PHPMyAdmin and it works fine.
There are result set pending from the query:
mysqli_multi_query($connection,$query);
You need to use/store result before you can proceed with next query after:
Since you look like you don't really care about the first result set, do this after the multi query..
do
{
$result = mysqli_store_result($connection);
mysqli_free_result($result);
}while(mysqli_next_result());
Another alternative is to close the connection and starts it again..
mysqli_close($connection);
$connection = mysqli_connect("localhost","username","password","tbl_msgs");
It all depends on your requirements.

mysql server has gone away in result of storing API response in php

i am experiencing mysql server has gone away in response of storing API result in mysql database through php code is follow,
$api_response = sendmsg($group_detail['cell_no'], $SMS); //function to execute API
//update sms sent record
$sql = "INSERT INTO sms_sent_record (record_id, api_response)
VALUES (NULL, '$api_response')";
$result = mysql_query($sql) or die('Error, updating sms & group count
in sms_sent_count failed : ' . mysql_error());
i have tried many other options such as storing api response in array and then store it in mysql table, but in any way it throws the same error. The other code in function after this error will not executed by server.
i think it is due to delay in api response and timeout problem in mysql.
Is there any way to avoid this error and storing result in proper way.
Does it work if you omit the sendmsg and do:
$api_response = 'test';//sendmsg($group_detail['cell_no'], $SMS); //function to execute API
If so, does sendmsg() use some sort of mysql connection at any time?
If it does, you may want to store the link from when you connected to the database the first time and reuse it.
$link=mysql_connect();
..
..
mysql_query($sql,$link);
There are lots of reasons for the gone away message but I suspect your problem is that you open the connection to your DB before the API call (to send an SMS ?) and the API call causes the server to terminal your connection before the INSERT is run
Try moving your open db connection to just before the INSERT statement :
$api_response = sendmsg($group_detail['cell_no'], $SMS); //function to execute API
// open connection here
$sql = "INSERT INTO sms_sent_record (record_id, api_response)
VALUES (NULL, '$api_response')";
$result = mysql_query($sql) or die('Error, updating sms & group count
in sms_sent_count failed : ' . mysql_error());
Check your value set for wait_timeout this is
The number of seconds the server waits for activity on a
noninteractive connection before closing it.
If you have this value set very low the server will timeout your connection between opening your connection and running your query.

How to hide SQL queries from web browsers (PHP)

I'm new to this forum and have a dilemma with my MySQL/PHP site. Now I've created a function that will pass a SQL query to it and execute it. What I didn't account for was the fact my SQL query being passed to the function is showing up in the "view source" of all browsers; which is BIG security concern because hackers can see the query. Here is a snippet of the function:
// connect to MySQL
$connection = mysql_connect($host,$username,$password) or die("Couldn't connect to MySQL". mysql_error());
// selects the database
$db = #mysql_select_db($db_name,$connection) or die("Couldn't select database");
function statement ($query)
{
global $connection, $db;
$sql = $query;
$results = mysql_query($sql, $connection) or die(mysql_error());
return $results;
}
Here's how its called:
$cat_results = statement("select * from $category");
Is there a way to hide the query passed from the browser using the function I have? If not any recommendations on a better approach to this function?
Really appreciate any thoughts on this!!
Andre
First of all PHP isn't viewable by the client, it is always executed by the server. Second of all at no point can the client execute SQL on your server. This is the basis of SQL Injection. If you are building a query with JavaScript and then sending it a php script to be executed then you have a very serious vulnerability on your hands.
it is not recommended to pass the query string all the way to the browser/client. you should only pass the query outcome to the client.
Unless you disable PHP on your server, or something breaks, your users won't ever see your PHP code.
PHP code should never show up in the html source. When things are working properly it should all be processed by the server and only the results sent to the client. Maybe you've missed a <? or ?> tag somewhere that's preventing it from being seen as php?

Categories