简体   繁体   中英

Is it possible to create a php array with data from both mssql and mysql?

Pretty much as per the title really - I've got a script which is, at the moment, pulling data from MySQL that was initially in MSSQL (another script pulls the information from the MSSQL databaseand populates a holding table in MySQL)

This works fine up to a point, however I'm now getting to the stage where I could really be doing with pulling some information directly from the MSSQL database and some from the MySQL database.

Is there any way of getting PHP to query both MySQL and MSSQL and return the information in a single array?

eg if all my information about 10 shops sales for apples is held in MySQL and my information about oranges is held in MSSQL, can I run so that one array shows how many apples and oranges each shop has sold over the last month?

Thanks

Yes, but you won't get anything for free. You will need to code it yourself. For example:

$all_data = array();

query mysql
while(fetching mysql rows) {
  $all_data[] = the mysql row;
}

query mssql
while(fetching mssql rows) {
  $all_data[] = the mssql row;
}

Then it's just a matter of going through the array to get your data. There's multiple ways of structuring your data so you will need to build an array which fits with your needs.

There's some useful tools in the PHP library for working with arrays. My favorites are array_map , array_filter and usort . Couple this with anonymous functions and you have a strong foundation for building your own filtering and sorting.

Nothing is stopping you from initiating two connections, running a query on each connection and then fuse the results together.

Of course, you can't perform joins as the two servers can't talk to each other to give you the end result; it's all up to you :)

Also, the total query execution time will be the time of both queries added together, unless you use the shiny new mysqli feature of running asynchronous queries.

Firstly, establish a connection to both mssql and mysql. Fetch the result of mssql and mysql. Then use array_combine to merge the two arrays to get a single array.

One solution you could consider would be to use distributed queries . You can set up a linked server from SQL Server to MySQL and use OPENQUERY() or similar methods to query both servers together. By doing that, you can join MySQL and MSSQL tables directly in one query (executed on MSSQL), or even UPDATE MySQL tables from MSSQL.

However, linked servers can be awkward to configure and performance is not always predictable, so you would have to test this carefully to see if it a) performs well enough for you and b) is less effort to maintain than your own PHP code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM