0

I have two databases, one online (mysql) and one in my office (SQL Server) which I would like to compare and update where a value is different.

I am using php to connect to the SQL Server database and run a query to retrieve the information, then connecting to the Mysql database running a query. Then I need to compare the two queries and update where necessary.

Is there somewhere I can look for tips on how to do this, I am sketchy on PHP and struggling really.

This is as far as I have got-:

<?php
$Server = "**server**";
$User = "**user**";
$Pass = "**password**";
$DB = "**DB**";

//connection to the database
$dbhandle = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server"); 

//select a database to work with
$selected = mssql_select_db($DB, $dbhandle)
or die("Couldn't open database $DB"); 

//declare the SQL statement that will query the database
$query = "SELECT p.id, p.code, ps.onhand";
$query .= "FROM products p with(nolock)";
$query .= "INNER JOIN productstockonhanditems ps with(nolock)";
$query .= "ON ps.ProductID = p.ID";
$query .= "WHERE ps.StockLocationID = 1"; 

//execute the SQL query and return records
$get_offlineproduct2 = mssql_query($query);

mysql_connect("**Host**", "**username**", "**password**") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error()); 
$get_onlineproducts = mysql_query(SELECT w.ob_sku, w.quantity
FROM product_option_value AS w
ORDER BY ob_sku) 
or die(mysql_error());

//close the connection
mssql_close($dbhandle);

?>

I am looking to compare the value p.code to w.ob_sku and whenever they match copy the value of ps.onhand to w.quantity so the online database has the correct quantities from the office database.

My question I guess is how close am I to getting this right? Also am I doing this the right way, I don't want to get so far and realise that i am just wasting my time...

Thanks!

4

1 回答 1

0

You do not need to fetch any record from MySQL, since you actually want to update it.

I would do something like this:

$query = 'SELECT p.code, ps.onhand FROM (...)';

// execute the SQL query and return a result set
// mssql_query() actually returns a resource
// that you must iterate with (e.g.) mssql_fetch_array()
$mssqlResult = mssql_query($query); 

// connect to the MySQL database
mysql_connect("**Host**", "**username**", "**password**") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());

while ( $mssqlRow = mssql_fetch_array($mssqlResult) ) {
    $mssqlCode = $mssqlRow['code'];
    $mssqlOnHand = $mssqlRow['onhand'];
    mysql_query(
        "UPDATE product_option_value SET quantity = $mssqlOnHand WHERE ob_sku = $mssqlCode"
       // extra quotes may be required around $mssqlCode depending on the column type
    );
}
于 2013-05-02T15:39:46.307 回答