Alternative connection to database without PHP? - php

Objective: Update prices of products between databases: Shop's server DB has the latest prices and website's DB need to be updated accordingly with any "each 24 hours" script (I'll look this up later).
I'm using Ionos as hosting for the website, and The server is shared, so I can't touch php.ini or add files for php.
I'm trying to connect to a SQL server DB, but since it requires dll libraries to be installed and to modify the php.ini, I can't do that.
I can't either make it from the other side, If I make it from an external server in order to update the prices of the website, they don't allow to make connections out of the context of the server.
So, I know that the solution is to upgrade the hosting's plan and pay more and so on, so I have a virtual server for my own. But before doing that, is there any other way to establish this connection without using php? Is there something else that allows me to create a DB connection?
The fatal errors appears as soon as sqlsrv_connect is read as there is no library to load this function.
$serverName = "x, 0000";
$connectionInfo = array( "Database"=>"x", "UID"=>"x", "PWD"=>"xxx");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
Edit: Comes to my mind... Maybe a solution would be to tell this php file to load php.ini and so on from another server if that's possible?

You could possibly call a JSON endpoint on your DB server (secure the endpoint though (out of scope for my answer)) https://3v4l.org/Gpi28
<?php
// MSSQL server side
$data = [
1 => 'hello',
2 => 'world',
];
// Imagine $data above is the array of rows returned by the db query
header('Content-Type: application/json');
echo json_encode($data);
exit;
// IONOS Side
$json = file_get_contents('http://your-database-server/some/url/or/other');
$data = json_decode(true);
// Now do your updates
// NB This is an INSECURE example, people who know the URL can see this data!

Related

Detecting type of database connection in drupal

How can I detect what type of database I'm connecting to in drupal (using php code)? I am trying to write a module which exposes some database functionality which only works on postgres or sql server. Currently, I'm doing it by trying to detect the database version, since the syntax appears to be different for each database but it doesn't seem very robust. Is there a php function which will report this?
You should use the global variable: $databases and check the driver value.
global $databases;
dpm($databases);
https://drupal.stackexchange.com/questions/48882/how-to-get-database-credentials
I don't fully understand what you're trying at the moment but
db_driver()
returns he currently connected database in Drupal as a string (e.g. "pgsql").
This may be helpfull to you. Use db_set_active() API to set your database before executing the query.
This will help you to keep away from errors
<?php
//set your configurations
$db_url['default'] = 'mysql://drupal:drupal#localhost/drupal';
$db_url['mydb'] = 'mysql://user:pwd#localhost/anotherdb';
$db_url['db3'] = 'mysql://user:pwd#localhost/yetanotherdb';
//set the active database and then process your queries in this case you can always knows which database is connected now.
db_set_active('mydb');
db_query('SELECT * FROM table_in_anotherdb');
Setting multiple databases
<?php
// ... header of the settings.php file
$db_url = array (
"default" => "mysql://user:pass#host/db",
"second" => "pgsql://user:pass#host/db"
);
db_set_active('second');
Ref: https://drupal.org/node/18429

PHP Open Multiple Connections

I would like to run multiple scripts instances of the same script in different browser tabs. And I would like them to have different MySQL connections. Each its unique connection.
I know that mysql_connect has a fourth parameter $new_link which should open a new link, but even that does not open a new connection, usually. Sometimes it does.
I have a XAMPP install on a Widows machine.
The question is: How can I absolutely force PHP/MySQL to open a new connections for each instance of a script? Script runs for about 2mins.
http://localhost/myscript.php
Here are the excerpts of the MySQL code. First load a work assignment from DB and mark it as in progress:
public function loadRange() {
try{
$this->db()->query('START TRANSACTION');
$this->row = $this->db()->getObject("
SELECT * FROM {$this->tableRanges}
WHERE
status = " . self::STATUS_READY_FOR_WORK . "
AND domain_id = {$this->domainId}
ORDER BY sort ASC
LIMIT 1");
if(!$this->row) throw new Exception('Could not load range');
$this->db()->update($this->tableRanges, $this->row->id, array(
'thread_id' => $this->id,
'status' => self::STATUS_WORKING,
'run_name' => $this->runName,
'time_started' => time(),
));
$this->db()->query('COMMIT');
} catch(Exception $e) {
$this->db()->query('ROLLBACK');
throw new Exception($e->getMessage());
}
}
Then the script may or may not INSERT rows in another table based on what it finds.
In the end, when task is finished, the assignment row is UPDATEd again:
$this->db()->update($this->tableRanges, $this->row->id, array(
'status' => self::STATUS_EXECUTED,
'time_finished' => time(),
'count' => $count,
));
In particular, the $this->tableRanges table looks to be locked. Any idea why it is the case? It is an InnoDB table.
I would like to run multiple scripts instances of the same script in different browser tabs. And I would like them to have different MySQL connections. Each its unique connection.
This is actually the case, without any additional effort
The question is: How can I absolutely force PHP/MySQL to open a new connections for each instance of a script.
Answer: do nothing :)
every time you hit http://localhost/myscript.php a new instance is run. Everything about that instance is unique, the web server spawns a new PHP thread, in which all the resources, connections, variables are unique.
Only state management devices such as sessions are shared and that too if you are using different tabs in same browser. If you hit the same URL with different browsers, the state management resources are different too.
To answer your question, like others mentioned before - your connection is different for each instance IF you are using mysql_connect. You could create a persistent connection that does not close when the application exits and reuses it for new connection requests using mysql_pconnect. But in your code it seems you are using the latter and in that case, you are fine.
You can try to set the isolation read level to prevent table stalling while reading for select
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
More information can be found here.
Again I guess it will take a bit of playing around to find which option works the best.

Best approach to see if a MySQL Server is up and running

I have a Master - Slave setup for a web application written in PHP. I have a pool of slaves I use for reading, and a Master that is used for writes (and reads if a write has been sent this request). I would like to incorporate an automated system for removed crashed servers from the read pool. Currently I am using:
foreach($readers as $reader)
{
$fp = #fsockopen($reader['host'],3306,$errno,$errstr,1);
if(!$fp)
{
//Remove from pool
}
unset($fp);
}
My primary question is there a more reliable method. I have had quite a few false positives, and vice versa because it is not actually checking for a MySQL server, but rather just a connection on port 3306. Is there a way to check for a MySQL server without raising an exception, which is the behaviour of the PDO and MySQLi extensions in PHP.
You could just use mysql_connect() and check the result for false, and close the connection right away on success. You can make a dummy account with no privileges for that if you like.
That's really the only reliable way, especially if you want to distinguish a running MySQL server from any other random process listening on port 3306.
You could use mysql_ping() to check if a current DB Connection you have open is still alive
Here is the example posted at http://www.php.net/manual/en/function.mysql-ping.php
<?php
set_time_limit(0);
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db = mysql_select_db('mydb');
/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}
/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysql_free_result($result);
/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>
The best way to check if any service is alive is to actually use it. So for MySQL try to connect and execute some fast query, for web server try to fetch some file, for PHP try to fetch some simple script...
For MySQL master/slave setup, one of the solutions is to actually check the state of replication. You can check how many transactions is the slave behind master and decide to stop using that slave when/while it has old data. (I don't do the replication myself, but I think you need to compare the variables Read_Master_Log_Pos and Relay_Log_Pos)

Problem using php ODBC functions from within a Joomla article

I am new to Joomla and new to php (wish I was so new in age too). I have installed joomla on a local apache webserver. I am trying to use some php code in a joomla article in order to fetch some data from a Sybase ASE 12.5 database. I installed sourcerer and started to try an ODBC connection using a system DSN (which I verified it is working):
{source}
<?php
echo 'This text is placed through <b>PHP</b>!';
echo '<p>';
echo '</p>';
$conn = odbc_connect('myDSN', 'sa', 'myPassword') or die('Could not connect !');
echo 'Connected successfully';
$sql = 'SELECT day, name FROM my_table where month = 1';
odbc_close($conn);
?>
{/source}
The above code doesn't do much, but this is how far I can get without problems. I refresh the joomla page and I see inside the article's text:
...
This text is placed through PHP!
Connected successfully
...
Seems ok, the connection obviously established (I verified this by stopping the sybase service and getting the "Could not connect" message). Then I added one more line, just below the $sql assignment.
$rs = odbc_exec($conn,$sql);
I refresh and ...I see nothing coming from the script (not even the "This text is placed through PHP!").
Obviously, I see nothing if I include code to echo the contents of $rs. I also tried this but in vain.
if (!$rs)
{exit("Error in SQL");}
Once I add the odbc_exec command, the entire script ceases working.
In php.ini I read:
; Windows Extensions
; Note that ODBC support is built in, so no dll is needed for it.
Do you have any idea what is going wrong?
UPDATE
Connecting to a MySQL database using code like this, works like a charm.
To answer your question
Is this the correct way to get data
from another database in to an article
or should I use some plug-in to do
that?
The correct way is to use JDatabase object which you get by JFactory::getDBO() or JDatabase::getInstance(), see Joomla JDatabase documentation.
$db = JDatabase::getInstance( $databasConfigArray );
$db->setQuery('your query');
$data = $db->loadObjectList();
Here is a good tutorial showing how to connect to multiple databases in Joomla, there is even source code for helper class.
Also look at this thread Connecting to 3rd party databse in Joomla!?

Connecting to 3rd party database in Joomla?

I need to connect to another database in Joomla! that's on another server. This is for a plugin and I need to pull some data from a table.
Now what I don't want is to use this database to run Joomla!, I already have Joomla! installed and running on its own database on its server but I want to connect to another database (ON TOP of the current one) to pull some data, then disconnect from that 3rd party database - all while keeping the original Joomla database connection in tact.
You can connect to an external database from your joomla instance without using the current ressource of your joomla DB.
Try this:
<?php
$option = array(); //prevent problems
$option['driver'] = 'mysql';
$option['host'] = 'dbase.host.com';
$option['user'] = 'login';
$option['password'] = 'pwd';
$option['database'] = 'anotherdb';
$db = & JDatabase::getInstance( $option );
?>
For more infromations regarding this, check the Joomla! Documentation
I had same problem before. Fond a good tutorial showing how to connect to multiple database and switch back and forth, it also has sample code. It explains how to connect to multiple (internal and external) databases factory style, without creating multiple connections per request. This means that if you create database instance in controller same connection will be used in the model. Improves performance.
Another good explanation is on Joomla Documentation site [http://docs.joomla.org/How_to_connect_to_an_external_database].
Can you create a generic mysql-php conection inside your plugin code to create a connection ?
like
mysql_connect("remot_server_ip:3306","user","pass");
mysql_select_db("your database");
//code goes here
:
:
:
mysql_close(connection);

Categories