using php to compare mysql columns to SQL Server - php

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!

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
);
}

Related

how to connect two mysql databases in two servers

i want to connect two mysql databases one is located in localhost and other one is located in a server
here is what i have done so far and i am not getting either error or data
<?php
$con=mysql_connect('120.247.201.8:3306','root','root');
$con1=mysql_connect('localhost','root','');
//mysql_connect('localhost','root','');
if(!$con){
die('Try Again');
}
if(!$con1){
die('Try Again');
}
mysql_select_db("iot",$con1);
mysql_select_db("lora_gateway",$con);
$result =mysql_query("SELECT lora_gateway.`server_log`.`created_at`, lora_gateway.`server_log`.`temperature`FROM iot.`device` inner JOIN `lora_gateway`.`server_log` on `lora_gateway`.`server_log`.`gateway_Id` = `iot`.`device`.`gatewayId` where iot.`device`.`deviceId`='23' ORDER BY lora_gateway.`server_log`.`created_at` desc");
$num= mysql_num_rows($result);
print_r($num);
?>
This is a solution for multiple servers, connections and DBs.
Two or more MySQL 5 db servers
Two or more locations (local and/or anything else)
Two or more different databases
Two or more tables and fields
Tested and Works fine :-)
//Define your database connections and select your database want to use. In this example I use two connections and two DBs. But you can use more than two.
<?php
//MySQL Server 1
$dbhost1 = "127.0.0.1";
$dbuser1 = "dbuser1";
$dbpassword1 = "dbpass1";
$db1 = "database1";
$connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
mysql_select_db($db1,$connection1);
//MySQL Server 2
$dbhost2 = "xxx.xxx.xxx.xxx";
$dbuser2 = "dbuser2";
$dbpassword2 = "dbpass2";
$db2 = "database2";
$connection2 = mysql_connect($dbhost2,$dbuser2,$dbpassword2) or die (mysql_error());
mysql_select_db($db2,$connection2);
//The SQL statement
$sql =" SELECT database1.tablename1.fieldname1 AS field1, database2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tablename2";
//Execute query and collect results in $results
$results = mysql_query($sql);
//Print result until end of records
while($rows = mysql_fetch_array($results)){
print $rows["field1"]." | ".$rows["field2"]."<br>";
}
?>
First of all, try to accustom yourself to using PDO or at least the mysqli_ functions. It's the future. :)
mysql_query's second parameter, the connection link, is optional. If omitted, it uses the last connection opened with mysql_connect. (See php.net Documentation)
Ergo, always use $con or $con1 as 2nd parameter in order to use the correct connection.
Then, provided that your queries are correct, it should work as expected.
what about to add connection to mysql_query() ?
$result = mysql_query("SELECT lora_gateway.`server_log`.... desc", $con);

Update database table with PHP

I am trying to update for some products their category in database. I want to find products that have in their name a specific word and after that I want to update the category for this products.
I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id.
I wrote a little PHP code but it make only selection part. What is wrong?
<?php
$username = "user_name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("1812233_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}."<br>";
}
$sql = "UPDATE 'sho_term_relationships'
SET 'term_taxonomy_id' = '123'
WHERE 'object_id' = $row";
//close the connection
mysql_close($dbhandle);
My new cod for script now is:
$username = "_shoping";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
$id[] = $row['id'];
/*echo "ID2:".$id."<br>";*/
}
foreach ($id as $value) {
echo "value:".$value."<br>";
}
/*$id = $row['id'];*/
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id =".$value;
mysql_query($sql);
//close the connection
mysql_close($dbhandle);
now it make an update but only for one row, how to make for all rows? From select query I get 4 result
Try this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id = ".$row{'id'};
And make sure to run the query mysql_query($sql)
Also, I think you might want to add this query inside the while loop
You are using single quotes instead of backticks (which are in this case not necessary). Change your update query to this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = $row";
Also, you are missing some pieces of your code; nothing will be called on that query. It's not being executed at all.
Also you have some other problems here, mainly due to the high risk of sql injection. First of all stop using mysql_ functions, they are deprecated. You should prepare your variables. Here's a demonstration of the key parts of your script in mysqli_ format.
This should also solve most of your issues (there may be a few more if I don't full understand your original question).
You would call your database like this (and check for errors)
$dbhandle = new mysqli($hostname, $username, $password);
if ($dhandle->connect_error) {
die("Connection failed: " . $dbhandle->connect_error);
}
Then you would select your data like this (assuming that term might not be the same every time, and might be coming from a post variable named search).
Edit: For example, if you have an HTML form that is getting this variable like so:
<input type="select" name="search_term" />
you name the variable like this:
$search = $_POST['search_term'];
and then you set it up for your query for the like operator
$search_term = '%'.$search.'%';
$result = $dbhandle->prepare("SELECT `id`
FROM `sho_posts`
WHERE CONVERT(`post_title` USING utf8)
LIKE ? ");
$result->bind_param("s",$search_term);
$result->execute();
$result->bind_result($id);
And then you can get your data through the while loop like so
while ($result->fetch()) {
... stuff you want to do here...
}
$result->close();
Then you would use this in your update query (which would take a similar syntax), and you can just get the information from $id which was created with the bind_result above:
$sql = $dbhandle->("UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = ?");
$sql->bind_param("s",$id);
$sql->execute();
$sql->close();
It may take a little bit to get used to this, but I find it easier to parse, and also is much more secure

PHP script to select MySQL data fields and return JSON

So I am trying to download JSON into an iOS application and I don't really know a lot about PHP.
Currently I'm using a generic php scrip as a delegate that connects the the MySQL database and returns JSON results.
<?php
$host = "localhost"; //database host server
$db = "***"; //database name
$user = "root"; //database user
$pass = "root"; //password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db("***", $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM table";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The issue with this is that I don't want to encode the entire table in JSON I just want to return a few select data fields from the particular table so I don't download unnecessary data.
I know that you do this in the SELECT query but something is wrong with my syntax for this.
I had been trying with:
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
but that doesnt seem to be working.
Also, In that table there are two separate data fields that are used to build a URL for an image, and Im not sure how to combine the two here so that they are returned in the JSON as one field.
For example: I Have a base string
"http://wwww.mysite.com/"
and i would like the add the two data Fields to that string so that when it returns the JSON objects they have those fields already concatenated so that the app can just use that URL:
"http://wwww.mysite.com/[data field1]/[datafield2]"
The query you should be trying looks like
$query = "SELECT col1,col2 FROM table";// no need of asterisk if you mention col names
Now if you need to combine two columns there itself in the query, try something like
$query = "SELECT CONCAT('mysite.com/',col1,'/',col2) FROM table";
"/" is the separator between two columns.
The query to fetch individual cols is
select col1,col2,col3 from table_name
No need to provide * like you did
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
^........here * is causing the problem.

Insert new rows from local table to remote table

I want to insert new rows from local table to remote table, i have made a php script for it but it is not working.
Remote and local - database, table and fields are same.
I am doing this way
//connection
$remote_hostname='xxx.xxx.xxx.xxx:3306';
$hostname='localhost';
$username = 'username';
$password = 'password';
$remote_connection = mysql_connect($remote_hostname, $username, $password);
$connection = mysql_connect($hostname, $username, $password);
$tablename="pc_games";
$database = 'games';
// some row count here $remoterows
$local_query = "SELECT * FROM $tablename LIMIT 100 OFFSET $remoterows";
$local_result = mysql_query($local_query, $connection) or trigger_error(mysql_error());
while($list=mysql_fetch_array($local_result))
{
$remote_update=mysql_query("INSERT INTO $tablename SELECT * from $tablename");
$remote_update_result = mysql_query($remote_update, $remote_connection) or trigger_error(mysql_error());
}
This is not working and showing error Duplicate entry '1' for key 'PRIMARY', but there is no duplicate entry.
If i do it this way it works, new rows get inserted into remote database.
while($list=mysql_fetch_array($local_result))
{
$id=$list['id'];
$pflink=$list['pflink'];
$image=$list['image'];
$pagelink=$list['pagelink'];
$title=$list['title'];
// and so on...
$remote_update=mysql_query("INSERT INTO $tablename SET id='$id', image='$image', pagelink='$pagelink', title='$title'......");
$remote_update_result = mysql_query($remote_update, $remote_connection) or trigger_error(mysql_error());
}
I have a many colums in database and also many database, i want to do it the first way, as i want to re use these codes for another database with just changing $database and $tablename
in require file for another database.
Please see and suggest any possible way to do it.
You cannot span a local and remote query in one request:
$remote_update=mysql_query("INSERT INTO $tablename SELECT * from $tablename");
This is supposed to get data from the local select and insert it into the remote database?
The query operates on 1 database, and 1 database only. You are trying to fetch data from a table and insert it on the same table. And of course, this gives a Duplicate entry '1' for key 'PRIMARY'
despite the question is so old, you can check "CLONE" supported from MYSQL 8.0.17: https://dev.mysql.com/doc/refman/8.0/en/clone-plugin-remote.html
This allow copy from localDB to remoteDB so easy.

mysql php : switching between mysql databases is slow

In my php script which connects to mysql, I have to query 2 databases in the same script to get different information. More specifically Faxarchives in one database and Faxusers in the other.
In my code I query faxusers and then foreach user, I query Faxarchives to get the user history.
I might do something like:
function getUserarchive( $userid) {
$out= "";
$dbname = 'Faxarchive';
$db = mysql_select_db($dbname);
$sql = "select sent, received from faxarchivetable where userid = '" . $userid . "'";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['sent'] . " " . $row['received'];
}//end while
}//end if query
return ($out);
}//end function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'Faxusers';
$db = mysql_select_db($dbname);
$sql="select distinct userid from faxuserstable";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['userid'] . ":" . getuserarchive($row['userid']);
}//end while
}//end if query
I'm guessing the switching between databases for each user is causing the slowness. Anyways how i can improve the speed of the processing?
thanks in advance.
You have several problems. First, your function, getUserarchive, pulls back all rows all the time. Looks like you forgot to restrict your SQL to only a specific userid. That's a big cause of your speed issues.
Another option would be to pass in all userids you are interested in. Rewrite the SQL as SELECT sent, received FROM faxarchivetable WHERE userid IN (...), which means you'd have one select to pull back all info from your faxarchivetable, instead of one per each userid.
Finally, if both databases are on the same MySQL server, you could just do a single select to pull in all the information:
SELECT Faxusers.faxuserstable.userid, sent, received FROM Faxusers.faxuserstable JOIN Faxarchive.faxarchivetable ON Faxusers.faxuserstable.userid = Faxarchive.faxarchivetable.userid
Are you aware that you can query tables in separate databases by qualifying the tablename?
For example, I think you can get all your information in a single SQL query like this:
SELECT sent, received
FROM Faxarchive.faxarchivetable
WHERE userid IN ( SELECT DISTINCT userid FROM Faxusers.faxuserstable );
Oh, this is the same point ChrisInEdmonton makes. I didn't notice his answer.

Categories