Query on two databases on two servers not connecting - php

I have followed a lot of examples on this issue but I just cannot seem to get this to work.
I can query the databases individually with success, but not the two in the same query.
I've tried aliasing, referring to the servers in the query... putting `` around the names etc. Nothing works.
So this is my code
Connection strings:
/// LOCAL DATABASE
$databaseprefix = "w-";
$mysqlHost = 'localhost';
$mysqlUser = 'web123-USER1';
$mysqlPass = 'SOMEPASSWORD';
$mysqlDB = $databaseprefix . 'DATABASE1';
$conn = mysql_connect($mysqlHost,$mysqlUser,$mysqlPass,true) or die('Could not connect to SQL Server on '.$mysqlHost.' '. mysql_error());
///select remote database to work with
$localDB = mysql_select_db($mysqlDB, $conn) or die("x1 Couldn't open database $mysqlDB");
///////////// GET THE DATABASE WE WANT TO EDIT
$remoteHost = $_SESSION['localfolder'];
$remoteUser = $_SESSION['databaseuser'];
$remotePass = $_SESSION['databasepassword'];
$remoteDB = $_SESSION['database'];
$remoteconn = mysql_connect($remoteHost,$remoteUser,$remotePass,true) or die('Could not connect to SQL Server on '.$remoteHost.' '. mysql_error());
$clientDB = mysql_select_db($remoteDB, $remoteconn) or die("x2 Couldn't open database $remoteDB");
Ok then I have this
$query_string = "select
`$remoteHost`.`$remoteDB`.`pages`.`page_title`,
`$mysqlHost`.`$mysqlDB`.`c_users`.`name`
from `$remoteHost`.`$remoteDB`.`pages`
left join `$mysqlHost`.`$mysqlDB`.`c_users`
on `$remoteHost`.`$remoteDB`.`pages`.`created_by` = `$mysqlHost`.`$mysqlDB`.`c_users`.`user_id`";
echo $query_string;
//// Query the DB's
$query = mysql_query($query_string);
echo mysql_num_rows($query);
while($row = mysql_fetch_assoc($query)) {
echo $row['name'] . ' | ' . $row['page_title'];
}
The output from the Query is something like this
select `remoteaddress.co.uk`.`remote-DB`.`pages`.`page_title`,
`localhost`.`w-DATABASE1`.`c_users`.`name`
from `remoteaddress.co.uk`.`remote-DB`.`pages`
left join `localhost`.`w-DATABASE1`.`c_users` on
`remoteaddress.co.uk`.`remote-DB`.`pages`.`created_by` = `localhost`.`w-DATABASE1`.`c_users`.`user_id`
Both join fields are INT datatypes on the join and the same collation. I am not sure why this would fail. Any help would be appreciated.

That's because your local connection can't connect to remote host directly ...
You can use 2 queries, one for each server instead
$query = mysql_query($query_string, $conn);
$query = mysql_query($query_string, $remoteconn);

Related

INNER JOIN SQL Query not working with PHP

I have created two tables in my database and normally my php file is able to get table data from mysql.
But when I add INNER JOIN or anything like that, it does not work anymore. No output is seen but also no error message (so the code have to be correct, I think).
Here's my php code:
<?php
$db_name = "mydatabase";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
$query = mysqli_query($conn,"SELECT * FROM firsttable INNER JOIN secondtable ON firsttable.secondtable_id = secondtable.secondtable_id");
while($row = mysqli_fetch_array($query))
{
$flag[] = $row;
}
print(json_encode($flag));
mysqli_close($conn);
?>
Try to debug like
1.if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
2.$query = mysqli_query($conn,"SELECT * FROM firsttable INNER JOIN secondtable ON firsttable.secondtable_id = secondtable.secondtable_id");
if (!$query) {
die('Invalid query: ' . mysql_error());
}
It seems there is no error in your program ! Make sure the database connection is established or not
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
The mysql query seems to be correct .. better you post your database structure ! and check the column name
firsttable.secondtable_id = secondtable.secondtable_id
in your code both are secondtable_id, is that correct column name ?

php/mysql: get data from one table, convert and insert in another table

Ok I will try to explain, (I am Portuguese lol).
I have a Database where I have the fallowing MySQL:
Database: ad
Table: notebooks
Fields: ID, tag, so, lastlogon, lastlogh
My ldap query gets data from ldap server (active directory) and stores it in my MySQL database (ad/notebooks).
I get tag which is tag number is unique.
I get so which is the OS installed in the notebook.
I get lastlogh which is the last logon time stamp, and it is unique too.
ID field is auto increment and key but I can set the tag filed to be key.
I have a config_notebooks.php where I set all the variables to connect to ldap and MySQL servers.
<?php
/*------------------------------------------------------------------------*/
//setting your variables
/*------------------------------------------------------------------------*/
//ldap host
$host = "ldap://HEICPT1VIA01.HEIWAY.NET";
//ldap user
$user = "domain\user";
//ldap password
$pswd = "pssw";
//ldap base structure
$dn = "OU=NotebookM2,OU=WorkstationsM2,OU=PT1,DC=heiway,DC=net";;
//attributs to search and get
$attrs = array("cn","operatingsystem","lastlogon");
//sql host
$sqlhost="localhost";
//sql user
$sqluser="root";
//sql password
$sqlpswd="";
//sql database
$database="ad";
//sql table
$table="notebooks";
?>
Now the query script
<?php
/*------------------------------------------------------------------------*/
//Query script
/*------------------------------------------------------------------------*/
include 'config_notebooks.php';
$filter = $_POST['filter']."=".$_POST['keyword']."*";
//connect to db
$con = mysql_connect("$sqlhost","$sqluser","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//connect to active directory
$ad = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ad, $user, $pswd)
or die ("Could not bind");
$search = ldap_search($ad, $dn, $filter, $attrs)
or die ("ldap search failed");
$entries = ldap_get_entries($ad, $search);
$sel = mysql_select_db("ad", $con);
if (!$sel)
{
die('Could not select DB: ' . mysql_error());
}
for ($i=0; $i<$entries["count"]; $i++)
{
$tag = $entries[$i]["cn"][0];
$so = $entries[$i]["operatingsystem"][0];
$lastl = $entries[$i]["lastlogon"][0];
mysql_query("
INSERT INTO
$table (tag, so, lastlogh)
VALUES
('$tag', '$so', '$lastl')
ON DUPLICATE KEY UPDATE
tag='$tag',
so='$so',
lastlogon='$lastl'
");
}
mysql_close($con);
ldap_unbind($ad);
if ($entries["count"] > 0)
header("Location: notebooks_list.php")
?>
In this query the last logon timestamp is coded like 130276262860634000
So I can export everything to excel and decode it, but I found a code that does that, so it saves time.
I created a new field in the database (lastlogon) and I need to fetch the data from lastlogh field, decode with the new script and store it in the lastlogon field.
This is the script that I found:
<?php
function adConvert ($ad) {
$seconds_ad = $ad / (10000000);
//86400 -- seconds in 1 day
$unix = ((1970-1601) * 365 - 3 + round((1970-1601)/4) ) * 86400;
$timestamp = $seconds_ad - $unix;
$normalDate = date("F d, Y", $timestamp);
return $normalDate;
}
//example: echo adConvert($ad);
?>
Using Mysql API
$res = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_assoc($res)) {
$logon_ts = adConvert($row['lastlogh']);
mysql_query("UPDATE $table SET lastlogon = '$logon_ts' WHERE tag='$row[tag]'");
}
I hope this solves your problem.
Note: Mysql API is deprecated as of PHP 5.5.0. So, It's highly recommended to use Mysqli API for newer developments.
man.. use the distinct for resolve u problem http://www.w3schools.com/sql/sql_distinct.asp

How to Combine 3 database tables form 3 different databases into Database 4

I am trying to create a separate search site (site4 using database4) that is updated every hour from 3 different websites each having their own database. I want to combine the data from database1, database2, and database3 into database4.
I also want to remove the duplicates during the combining, so I was told to use the MySQL UNION function.
On the same server I have 4 individual websites with each site having their own MySQL database:
site1 --> database1, 1 table, 16 fields
site2 --> database2, 1 table, 16 fields
site3 --> database3, 1 table, 16 fields
site4 --> database4, 1 table, 16 fields (currently empty)
All 4 databases have an identical structure where as each database has only 1 table with 16 fields.
In all 4 databases, the table names are the same (Post_Data) and all 16 fields are identical. The index field (field 11) is named Post_Date.
With some forum help I was able to write the following PHP code, but it does not work and I do not get errors.
Can you see what is wrong in the code below and what needs to be done to fix it?
Thanks in advance.
<?php
// Website 1
$host1 = 'site1.com';
$database1 = 'data_1';
$username1 = 'user_1';
$password1 = 'pass_1';
$TableName1 = 'Post_Data';
// Website 2
$host2 = 'site2.com';
$database2 = 'data_2';
$username2 = 'user_2';
$password2 = 'pass_2';
$TableName2 = 'Post_Data';
// Website 3
$host3 = 'site3.com';
$database3 = 'data_3';
$username3 = 'user_3';
$password3 = 'pass_3';
$TableName3 = 'Post_Data';
// Website 4 - Search Database
$host4 = 'site4.com';
$database4 = 'data_4';
$username4 = 'user_4';
$password4 = 'pass_4';
$TableName4 = 'Post_Data';
// Connect to all 4 Databases
$connection1 = mysql_connect($host1, $username1, $password1) or die ('Cannot connect to the database because: ' . mysql_error());
$connection2 = mysql_connect($host2, $username2, $password2, true) or die ('Cannot connect to the database because: ' . mysql_error());
$connection3 = mysql_connect($host3, $username3, $password3, true) or die ('Cannot connect to the database because: ' . mysql_error());
$connection4 = mysql_connect($host3, $username4, $password4, true) or die ('Cannot connect to the database because: ' . mysql_error());
// Combine all 3 Databases into the Search Database #4
mysql_select_db ($database1,$connection1);
mysql_select_db ($database2,$connection2);
mysql_select_db ($database3,$connection3);
mysql_select_db ($database4,$connection4);
mysql_query("USE $database4");
mysql_query("CREATE TABLE temp AS
SELECT * FROM $database1.$TableName1
UNION
SELECT * FROM $database2.$TableName2
UNION
SELECT * FROM $database3.$TableName3
");
mysql_query("CREATE INDEX ix_post_date ON temp.Post_Date");
mysql_query("RENAME TABLE Post_Data TO backup, temp TO Post_Data");
// Close databases connections
mysql_close($connection1);
mysql_close($connection2);
mysql_close($connection3);
mysql_close($connection4);
// Finished
$date_time = date('m-d-Y H:i:s');
echo '<h1>Finished - '.$date_time.'</h1>';
?>
You create 4 different connections to the database, but the mysql_query is going to run against one connection.
The query will need to know which database to connect to. You can see How do you connect to multiple MySQL databases on a single webpage? for a good example
You should be able to see that your create table query fails by displaying the error:
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}

trying to count entries in a database

I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,

Converting results from a PHP MSSQL query from Latin1_General_CI_AI to a readable string

I am querying a CRM2008 database on an MS server from an apache server.
I am trying to get the contactid from a view I have created on the DB.
I return the result fine, but it's not ?encoded? the way I want it.
How can I convert the results from my query into something readable (by me and my code).
<?php
ini_set('mssql.charset', 'UTF-8');
//connect
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select
$selected = mssql_select_db($DB)
or die("Couldn't open database $myDB");
$query = " select contactid from V_UserDetails where emailaddress1 =
'me#you.com' ";
$result = mssql_query($query);
//grab it
while ($row = mssql_fetch_array($result))
{
$user_custid = ($row['contactid']);
}
echo "<b>customer ID:</b> " . $user_custid . "<br />";
outputs:
customer ID: &<DŽ���h���"
rather than the required:
customer ID: 234554345jhg54j34hg54jhg43jh5g34jhg5jhg3jhg34jg
The field is a UniqueIdentifier. In the select query I changed it to
$query = " select CONVERT(VARCHAR(36), contactid) from V_UserDetails where emailaddress1 =
'me#you.com' ";
And this pulls it from the DB as expected! Sorted!
$data=iconv("UTF-8", "ISO-8859-9", $data);
ISO-8859-9// change

Categories