connection between two different Database - php

i have two kind of database in different server. And the script below is to make DB connection:
//DB 1
define("DBNAME","xx.xxx.xx.xxx:D:\DATABASE\OCS DATA.FDB");
define("DBUSER","USER");
define("DBPASS","USER");
$dbh = ibase_connect(DBNAME,DBUSER,DBPASS) or die(_ERROR15.": ".ibase_errmsg());
//DB 2
$dbc=mysql_connect(_SRV, _ACCID, _PWD) or die(_ERROR15.": ".mysql_error());
mysql_select_db("qdbase") or die(_ERROR17.": ".mysql_error());
beside that,i have some query for insert data into another DB:
//if structure of the both tables are same then...
$sql = "insert into database1.member select * from database2.member";
//if structure of both tables are not same then
$sql = "Insert into database1.member select columnname1,columnname2 ".
"from database2.member";
whether this query can be use for the condition like above, which have two different type of DB? if it so, which part that must be changed?
while ($ibase_row = ibase_fetch_assoc($rResult)){
$ins = array();
foreach ($ibase_row as $col => $val){
$ins[$col] = mysql_real_escape_string($val);
}
$mysql_insert = "INSERT INTO qdbase.table SET ".implode(',', $ins);
$res = mysql_query($mysql_insert, $dbc) or die();
}

There is a chance that your database systems support "dblink" feature.
If this is available you would link the mysql to Firebird or vice versa and run the script from one of them.

Related

How do I transfer newly added rows in an SQL Server table to an identical MySQL table using PHP?

Basically, I have two identical tables in SQL Server and MySQL. I want to use PHP in such a way that I'll only have to manually insert new values in one of them. I want to make a PHP code where the newly inserted values in the SQL Server table will also be inserted in its identical counterpart in MySQL with the press of a button.
For example, I have a table named "Customers" in both SQL Server and MySQL with the rows "ID (auto incremented)", Name, and Address. I insert new values into those columns in SQL Server. How do I make it so that I'll only have to press a button made in PHP so that I won't have to do the whole "insert into" process again in MySQL?
Any ideas are much appreciated!
According to new information given in the comments, I'm changing my answer and adjusting the code.
Code example:
<?php
$serverName = "server"; //serverName\instanceName
$connectionInfo_mssql = array("Database"=>"DB", "UID"=>"username", "PWD"=>"password","CharacterSet"=>"UTF-8");
$conn_mssql = sqlsrv_connect($serverName, $connectionInfo_bi);
$conn_mysql = new mysqli("server", "username", "password", "db");
//SELECT FROM MS SQL DB
$mssql_array = array();
$ms_sql = "SELECT column_names FROM db_table";
$mssql_query = sqlsrv_query($conn_mssql , $ms_sql);
while($row = sqlsrv_fetch_array($mssql_query) {
$mssql_array[] = array('name' => $row['name'],
'adress' => $row['adress']);
}
foreach($mssql_array as $key => $value) {
//SELECT FROM MySQL DB
$my_sql = "SELECT column_names FROM db_table WHERE name = '".$value['name']."' AND adress = '".$value['adress']."'";
$mysql_query = mysqli_query($conn_mysql , $my_sql);
$num_rows = mysqli_num_rows($mysql_query);
if ($num_rows == 0) {
//Insert in MySQL DB
$sql = "INSERT INTO db_table (db_columns) VALUES (variables_from_array)";
$sql_query = mysqli_query($conn_mysql, $sql);
} else {
//There is a record in DB, and maybe you want to update it. If not, then lose this else part.
}
}
echo 'Table Customers from MS SQL DB and table Customers from MySQL DB are now synced!';
?>

How to update / insert data in MySQL table via PHP

I am new in PHP .. I need help to make a PHP code to update data in MySQL if data exists and if don't already exists then insert data in MySQL.. I have made the PHP code to do this but it's inserting data when data already exists.. in MySQL.. Please help
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('gamingtracker',$con);
$query = "SELECT * FROM servers WHERE sgame='$game_insert'";
$result = mysql_query($query, $con);
While($row = mysql_fetch_array($result)) {
$id = #$row['id'];
$sname = #$row['sname'];
$sgame = #$row['sgame'];
$minplayers = #$row['minplayers'];
$maxplayers = #$row['maxplayers'];
$ip = #$row['ip'];
$port = #$row['port'];
$map = #$row['map'];
}
$sname1= html_entity_decode("{$server['s']['name']}");
if(#$sname=="{$server['s']['name']}"
AND #$sgame=="{$server['s']['game']}"
AND #$minplayers=="{$server['s']['players']}"
AND #$maxplayers=="{$server['s']['playersmax']}"
AND #$ip=="{$server['b']['ip']}"
AND #$port=="{$server['b']['c_port']}"
AND #$map=="{$server['s']['map']}" )
{
$query1 = "UPDATE servers
SET sname='$sname1', sgame='{$server['s']['game']}', minplayers='{$server['s']['players']}', maxplayers='{$server['s']['playersmax']}', ip='{$server['b']['ip']}', port='{$server['b']['port']}', map='{$server['s']['map']}'
WHERE ip='{$server['b']['ip']}', port='{$server['b']['port']}', sgame='{$server['s']['game']}'";
$result1 = mysql_query($query1, $con);
}
else {
$query1 = "INSERT INTO servers (id,sname,sgame,maxplayers,minplayers,ip,port,map) VALUES ('','$sname1','{$server['s']['game']}','{$server['s']['players']}','{$server['s']['playersmax']}','{$server['b']['ip']}','{$server['b']['c_port']}','{$server['s']['map']}')";
$result1 = mysql_query($query1, $con);
}
So you only want one entry per unique combination of ip, port, and sgame? The most straightforward way would be to let mysql handle this.
First, create a unique index on the table for those fields. Run the following in mysql:
CREATE UNIQUE INDEX ip_port_sgame ON servers (ip, port, sgame);
Then, instead of running an INSERT query, use REPLACE. So just change this one line in your php:
UPDATE servers
to
REPLACE INTO servers

Inserting data in 2 table on the same form [duplicate]

Assuming that I have two tables, names and phones,
and I want to insert data from some input to the tables, in one query. How can it be done?
You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
http://dev.mysql.com/doc/refman/5.1/en/commit.html
MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.
WITH names_inserted AS (
INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
INSERT INTO phones (id_name, phone) (
SELECT names_inserted.id, '123-123-123' as phone
) RETURNING *
) SELECT * FROM names_inserted
LEFT JOIN phones_inserted
ON
phones_inserted.id_name=names_inserted.id
This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...
P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
my way is simple...handle one query at time,
procedural programming
works just perfect
//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
//save second mysqli_query
$insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')";
$save2 = mysqli_query($conn, $insertQuery2);
//check if second save is successfully
if (isset($save2)){
//save third mysqli_query
$insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
$save3 = mysqli_query($conn, $insertQuery3);
//redirect if all insert queries are successful.
header("location:login.php");
}
}else{
echo "Oopsy! An Error Occured.";
}
Multiple SQL statements must be executed with the mysqli_multi_query() function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

using php to compare mysql columns to SQL Server

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

How to convert a string to variable through a loop and save it in MySQL Database

I have this problem. This is my PHP code to take one MySQL table and Insert the data into another MySQL table:
<?php
$connect = mysql_connect("host","user","password");
if (!$connect){
die("Failed to connect to the database: ".mysql_error());
}
$kies_bd = mysql_select_db("eraenz_db1",$connect);
if (!$kies_bd){
die("failed to choose from BD: ".mysql_error());
}
$query = "SELECT ListNumber FROM residential";
$result1 = mysql_query($query);
if (mysql_num_rows($result1) >10){
$difference = mysql_num_rows($result1) - 10;
$myQuery = "SELECT * FROM residential ORDER BY id LIMIT 10, $difference";
$result2 = mysql_query($myQuery);
while ($line = mysql_fetch_array($result2)){
mysql_query("INSERT INTO lisitngs
(listnumber, mandatetype, listdate,expirydate, updatedate,virtualtoururl,status,propertyright,agnt_id, erfsize,erf_no, housesize,outbuildingsize, bathroomoptions,closedusergroup,facingoptions,features,kitchenoptions,flatlet,parking,carport,price,numofbath,numofbed, numofgarages, numofkitchens, numofreception,numofstudies,numofdomesticbath,numofdomesticbed,numofoutsidetoil,off_id,ownershiptype, parkingdesc, pooloptions,pool,sellingreason,sfeatureoptions,roofoptions,roomoptions,walloptions,windowoptions, styleoptions,securityoptions,tempcontrol,streetname,streetnumber, suburb, propertycategory,propertytype,ss_name,agentcontactname,province,city, postalcode,email,listingstatus,feedtype, rates, levies)
values ({$line['ListNumber']}','{$line['MandateType']}','{$line['ListDate']}','{$line['ExpiryDate']}','{$line['UpdateDate']}','{$line['VisualTourURL']}','{$line['Status']}','{$line['PropertyCategory']}','{$line['AgentI']}','{$line['SizeOfErf']}','{$line['StandNumber']}','{$line['SizeOfHouse']}','{$line['SizeOfOutBuildings']}','{$line['BathroomOptions']}','{$line['ClosedUserGroup']}','{$line['FacingDescrip']}','{$line['Features']}','{$line['KitchenOptions']}','{$line['Flatlet']}','{$line['Parking']}','{$line['NumOfCarports']}','{$line['ListPrice']}','{$line['NumOfBathrooms']}','{$line['NumOfBedrooms']}','{$line['NumOfGarages']}','{$line['NumOfKitchens']}','{$line['NumReceptionRooms']}','{$line['NumStudies']}','{$line['NumOfDomBathrooms']}','{$line['NumOfDomBedrooms']}','{$line['NumOfOutSideToilets']}','{$line['OfficeId']}','{$line['OwnershipType']}','{$line['ParkingDesc']}','{$line['PoolOptions']}','{$line['Pool']}','{$line['ReasonForSelling']}','{$line['SpecialFeatures']}','{$line['RoofOptions']}','{$line['RoomOptions']}','{$line['WallFinishes']}','{$line['Windows']}','{$line['StyleOptions']}','{$line['SecurityOptions']}','{$line['TempControl']}','{$line['StreetName']}','{$line['StreetNumber']}','{$line['Suburb']}','{$line['PropertyCategory']}','{$line['TypeOfProperty']}','{$line['UnitName']}','{$line['AgentContactName']}','{$line['Province']}','{$line['City']}','{$line['PostalCode']}','{$line['SellerEmail']}','{$line['Status']}','{$line['FeedType']}','{$line['MunRatesTaxes']}','{$line['MonthlyLevy']}')");
mysql_query("INSERT INTO clients
(clnt_title,clnt_name,clnt_surname,clnt_street_name,clnt_street_no,clnt_complex_name,clnt_unit_no,clnt_suburb,clnt_city,clnt_cell,clnt_email,agnt_id,)
values ({$line['SellerTitle']}','{$line['SellerFirstName']}','{$line['SellerSurname']}','{$line['StreetName']}','{$line['StreetNumber']}','{$line['UnitName']}','{$line['UnitNumber']}','{$line['Suburb']}','{$line['City']}','{$line['SellerMobileNumber']}','{$line['SellerEmail']}','{$line['AgentID']}')");
mysql_query("DELETE FROM residential WHERE ListNumber={$line['ListNumber']}");
echo "{$line['ListNumber']} was deleted <br/>";
}
}
mysql_close($connect);
?>
Now not all of these columns are compatible with their counter part column where it is supposed to be inserted into.
My question to you is, how do I save these incompatible strings into a variable and then insert them into the Database Table?
Use Prepared Statements. PHP will convert the type automatically for you, and you're protected against Injection Attacks.
Actually, you should be using Prepared Statements everywhere in your code... building SQL from strings is a bad habit.

Categories