PHP script slow on server, but fast in local - php

First I want to say that my english is very poor, but I'm going to try.
I've tried to run a PHP script on my PC with wamp server and it works ok, but when I upload, for some reason, it spends so much time to complete the execution on the host, and almost always ends with a Service Temporarily Unavailable error (the host close the connection).
I've used some die() to see where is the problem and I found it's a for loop where I'm making a big string (I'm only concatenating to make a big INSERT for executing it after the loop). And this loop works in local... I can't understand why is not working on the host.
//insertar valores en bbdd
$sql = "Insert into valor values ";
$primer = 1;
$tiempo_inicio = microtime(true);
for($i = 0 ; $i <= count($array2) - 1 ; $i++)
{
//insertar glucosa
if(!$array2[$i][1] == "")
{
if (!$primer) $sql .= ", ";
else $primer = 0;
$sql .= "('" . $this->paciente . "', '" . $array2[$i][0] . "', 'Glucosa', " . $array2[$i][1] . ")";
$this->Comprobar_Aumentar_Avisos($array2[$i][0], $array2[$i][1]);
}
//insertar raciones
if(!$array2[$i][2] == "")
{
if (!$primer) $sql .= ", ";
else $primer = 0;
$sql .= "('" . $this->paciente . "', '" . $array2[$i][0] . "', 'Raciones', " . $array2[$i][2] . ")";
}
//insertar insulina
if(!$array2[$i][3] == "")
{
if (!$primer) $sql .= ", ";
else $primer = 0;
$sql .= "('" . $this->paciente . "', '" . $array2[$i][0] . "', 'Insulina', " . $array2[$i][3] . ")";
}
}
$tiempo_total = microtime(true) - $tiempo_inicio;
die($tiempo_total);
if ($sql != "Insert into valor values ") {
$AccessBD = new TAccessBD;
$AccessBD->usuario = $this->paciente;
$AccessBD->Inicialitzar_BD();
$AccessBD->query = $sql;
$res = $AccessBD->Ejecutar_SQL();
$AccessBD->Finalitzar_BD();
unset($AccessBD);
}

The problem was that in the loop I was accessing too many times the database in this function: $this->Comprobar_Aumentar_Avisos($array2[$i][0], $array2[$i][1]);
When accessing in local I have no problem, because of local database, but on the server, with the database in other external host too, it was very slow.
So I solved it reducing the number of accesses to database to the minimum I can and now it's working fine.
Thank you very much for the help!

Related

Convert "INSERT" MySQL query to Postgresql query

I`m stuck for some time to fix this trouble. I followed this article https://www.sitepoint.com/creating-a-scrud-system-using-jquery-json-and-datatables/
to create SCRUD System. But I stuck when I need to add a new record to PostgreSQL.
The working MySQL part of the code is:
$db_server = 'localhost';
$db_username = 'root';
$db_password = '123456';
$db_name = 'test';
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
$query = "INSERT INTO it_companies SET ";
if (isset($_GET['rank'])) { $query .= "rank = '" . mysqli_real_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "company_name = '" . mysqli_real_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "industries = '" . mysqli_real_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "revenue = '" . mysqli_real_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "fiscal_year = '" . mysqli_real_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "employees = '" . mysqli_real_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "market_cap = '" . mysqli_real_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "headquarters = '" . mysqli_real_escape_string($db_connection, $_GET['headquarters']) . "'"; }
$query = mysqli_query($db_connection, $query);
I managed to write this and it fails to work for PostgreSQL:
$conn_string = "dbname=test user=postgres password=123456";
$query = "INSERT INTO it_companies VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . pg_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['headquarters']) . "');"; }
$query = pg_query($db_connection, $query);
The message I gets from the system is: "Add request failed: parsererror"
The Edit and remove functions are working well.
I follow to build this clause from the PGSQL site example:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Any what I`m doing wrong? Thanks!
UPDATE
The echo of the query and the error was the id column. In Mysql code there was no problem with the ID colum. Why when i use pgsql it does?:
INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters)
VALUES ('1', 'asd', 'asd', '1', '2000', '2', '3', 'asdf');
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "it_companies_pkey" DETAIL: Key (company_id)=(2) already exists. in C:\WEB\Apache24\htdocs\datatableeditor\data.php on line 121
{"result":"error","message":"query error"
,"data":[]}
UPDATE2
The working code with one bug:
$query = "INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters) VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . $_GET['rank'] . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . $_GET['company_name'] . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . $_GET['industries'] . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . $_GET['revenue'] . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . $_GET['fiscal_year'] . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . $_GET['employees'] . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . $_GET['market_cap'] . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . $_GET['headquarters'] . "') RETURNING company_id;"; }
echo $query;
After this query, the message "Add request failed: parsererror" is still there. But after a manual refresh of the page, the new data is saved. Any idea why this message apears and not loading the data automatically?
UPDATE 3 - Success
I forgot to remove echo $query; from the code causing the error message.
All works now. Thanks for the help to all! :)
You need a little more work in your query string building.
You only add the open parenthesis ( if rank is present
You only add the closing parenthesis ) if headquarters is present.
Also you need specify what field column get which value, otherwise you end with headquarter name into the fiscal_year field. If columns are not specified the values are add it on the same order as define on the table.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
And as other have comment check the $query to see what you have.

how to apply array_diff with php and sql

Hi im unable to apply array_diff() for when user edits the stockroom detail to replace with the new result.
Here is the edit function where i call out all the variables via sql.
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
Here is the array_diff() function. There may be unnecessary calling and/or lack of coding..not too sure. This set of codings result in no output. The server basically crashes. Any help on this?
//oldsr is existing stockroom data
//newsr is new stockroom data through edit function
//resultsr is the end result
<?php
$StockroomGetAllDetails = array();
$arr2 = einv_getStockrmDetailFromCode($stockroomCode);
$codearr = explode(",", $arr2['einv_stockrm_code']);
$oldsr = array($codearr);
$newsr = array($codearr);
$resultsr = array_diff($newsr, $oldsr);
if(!count(array_diff($oldsr, $newsr)) && !count(array_diff($newsr, $oldsr))) {
// Arrays are equal
} else {
// Array values are different
echo $resultsr;
}
?>
This code is for redirect.
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
This set of codes able to display the new datas added and removed accordingly :)
$oldCat = $Stockroom["einv_stockrm_cat"];
$oldCatArr = explode(",",$oldCat);
$newCatArr = explode(",",$cat);
//Debugging
//print_r($oldCatArr);
//print_r($newCatArr);
$resultCatAdd = array_diff($newCatArr, $oldCatArr);
$resultCatRemove = array_diff($oldCatArr, $newCatArr);
//Debugging
print_r($resultCatAdd);
print_r($resultCatRemove);

Using Semaphores in PHP

I'm having this problem where my database entries are not writing to my table in the correct order. I figured it was because they were entering asynchronously. Therefore, I tried to put them in a function that would synchronize the queries. I came up with the following:
function synchronizedInsert($userID, $pid, $pic, $xCoord, $newLine, $drawingColor)
{
$semRes = sem_get(123321, 1, 0666, 1);
if(sem_acquire($semRes))
{
$sql = "INSERT INTO cbmarker.annot_test (userid, project_id, image, date, coords, newLine, color)
VALUES (" . $userID . "," . $pid . ",'". $pic . "', NOW()," . $xCoord . "," . $newLine . ",'" . $drawingColor . "')";
$result = mysql_query($sql);
sem_release($semRes);
}
}
When I don't use semaphores and have only the query in my function
function synchronizedInsert($userID, $pid, $pic, $xCoord, $newLine, $drawingColor)
{
$sql = "INSERT INTO cbmarker.annot_test (userid, project_id, image, date, coords, newLine, color)
VALUES (" . $userID . "," . $pid . ",'". $pic . "', NOW()," . $xCoord . "," . $newLine . ",'" . $drawingColor . "')";
$result = mysql_query($sql);
}
then the funcion works but the I'm back to the problem of the entries entering in the wrong order. When I add the semaphores, the entries don't enter my table and my console gives me the error "GET ... 500 (Internal Sever Error)". Am I using the semaphores incorrectly or is there something I'm missing. Any help would be appreciated. Thanks.

SQL loop with $i and $_POST Values

I am trying to loop through a number of results from a form, but can't get it quite right.
for ($i=1;$i<$total;i++)
{
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}','{$_POST['$iH']}', '{$_POST['$iA']}'");
}
I want $_POST['$iH'] to be the same as $_POST['1H'],$_POST['2H'], $_POST['3H'] etc.
Like so:
for ($i = 1; $i < $total; $i++) { // <--- You had a typo here
$sql = "INSERT INTO MYSQL(value1,value2,value3) ";
$sql .= "VALUES('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
mysql_query($sql);
}
But, two big problems.
Multiple queries
Boy, what a waste! Dispatch one instead:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
SQL injection
It continues to baffle me how, in 2011, people are still not getting this.
If you're going to insist upon using the ancient mysql API (not even the OO version?!) rather than PDO, get into the habit of sanitising your inputs:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}'," .
"'" . mysql_escape_string($_POST[$i . 'H']) . "'," .
"'" . mysql_escape_string($_POST[$i . 'A']) . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
OK, so without multi-query support in your API it's unlikely to cause you significant grief here, but it can do in authentication routines. Just get used to scripting properly in this regard.
You really need to escape your post variables with mysql_real_escape_string()... you are seriously looking for trouble like that.
In answer to your question, I think you need to do something like this:
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}', '" . $_POST[$i . 'H'] . "', '" . $_POST[$i.'A']. "'");
with the letters rubbing up against your variable, the php engine will assume they are part of the variable name; that variable name does not exist, so you will get some strange results.
You need to escape your quotes because your variable is being passed as a literal:
for ($i=1; $i<$total; $i++)
{
mysql_query('INSERT INTO MYSQL(value1,value2,value3) VALUES("' . $i . '","' . $_POST[$i . 'H'] . '", "' . $_POST[$i . 'A'] . '")');
}

how to assign and concat using multiple delimiters in an array?

i apologize if the question is wrong. i am a still a newbie and a learner however i would appreciate if someone correct me if i am somewhere wrong.
here in the Class method i am using for Inserting the data into the database
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES(" . implode(",",$value) . ")";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES(". $value . ")";
}
}
now here i am determining if the $col and $value is an array if yes then process it.
however i have a problem here since the VALUES in the Insert statement needs to be represnted in the single or double quote format it will not process the query and hence print the error
for example the below code would print the error
$query = "INSERT INTO users(username,email) VALUES(test,test#test.com)";
and the correct format will be
$query = "INSERT INTO users(username,email) VALUES('test','test#test.com')";
now in the col value i would like to add the single quotes to every value in the array for example the $value array which is like this.
$value = array('test','test#test.com');
should give back the value
'test','test#test.com'
instead of
test,test#test.com
how do i achieve it?
$query = "INSERT INTO $table ('" . implode("','",$col) . "')
VALUES ('" . implode("','",$value) . "')";
Make sure that neither $col nor $value is empty.
Right code:
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES('" . implode("','",$value) . "')";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES('". $value . "')";
}
}
CHANGE:
VALUES(" . implode(",",$value) . ")
TO
VALUES('" . implode("','",$value) . "')
(Your output:)
VALUES(demo,demo2)
(New Output:)
VALUES('demo','demo2')
you could do this?
$value = array("'test'","'test#test.com'");
You can use array_map() method:
function addQuotes($str)
{
return "'".$str."'";
}
$value = array_map("addQuotes", $value);
or follow a Oswald's answer recommendations.

Categories