mysql php : switching between mysql databases is slow - php

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.

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

mysql Show tables returns all +1 with TABLES "number of rows" as first value

When i recently wanted to list all tables in a database in php i made the simple MySQL query:
$tables_query = mysql_query('show tables');
while ($test = mysql_fetch_array($tables_query)) {
echo "Table: {$test[0]}<br />";
}
The first result is
TABLES 105
address_book
I don't have a table called "TABLES 105" but the mysql_num_rows also shows, that there is 105 results, even that my database only contains 104 table
If i try to request "show tables" directly on the MySql server, it works fine and i get 104 rows as result. It also worked before and i can't seem to find anything about this, so im hoping someone can help me in here.
It also affect when i call directly to the mysql server. I got access with an other user login for an other database, on the same server and here is no issues at all.
Its questionable how that 105 got there in the first place, most likely this is caused by that mysql_num_rows function that you mentioned as fetch_array actually fetches the rows, but here's one on MySQLi, stop using MySQL anymore:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'username', 'password', $db);
$tables_query = mysqli_query($con, "SHOW TABLES FROM {$db}");
while($table = mysqli_fetch_assoc($tables_query)) {
echo $table["Tables_in_{$db}"], '<br/>';
}
An alternative way of course is to delve into information_schema:
$db = 'test'; // database name
$con = mysqli_connect('localhost', 'root', '', $db);
$tables_query = mysqli_query($con, "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$db}'");
while($table = mysqli_fetch_array($tables_query)) {
echo $table['TABLE_NAME'], '<br/>';
}

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.

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 delete multiple rows from MYSQL table using PHP

I'm trying to learn php and ran into a problem. I'd appreciate any help.
I have a database that looks like:
ID USER AGE
1 name1 18
2 name2 19
3 name3 20
etc etc
I want to delete multiple records. This is the code I am using for that:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("photo",$dbhandle)
or die("Could not select examples");
//execute
echo "CONNECTED";
echo "</br>";
//Action
$delete_query = ("DELETE FROM _users WHERE age in(17,18,19)");
$result = mysql_query($delete_query);
echo 'Deleted';
mysql_close($dbhandle);
?>
When I am deleting by querying the age column, it deletes multiple rows okay.
However, when I do this:
$delete_query = ("DELETE FROM _users WHERE USER in(name1,name2,name3)");
Nothing happens. Is it because those are strings? How can I fix it?
Thanks!
The query is incorrect:
DELETE FROM _users WHERE USER in ('name1','name2','name3');
strings must be quoted, otherwise MySQL will see them as field names (or keywords). You have no error handling in your script, or you'd have seen the error messages. Always write a query as follows:
$result = mysql_query(...) or die(mysql_error());
this'll show you exactly WHY the query failed (or just continue on if there's nothing wrong).
DELETE FROM _users WHERE USER in(name1,name2,name3)
MySQL thinks that name1, name2, and name3 are columns. Quote them.
use single quote '
$delete_query = ("DELETE FROM _users WHERE `USER` in('name1','name2','name3')");
You need to encase the strings in quotes: WHERE USER in('name1', 'name2', 'name3')
Users is a string, you need to quote the values:
$delete_query = ("DELETE FROM _users WHERE USER in('name1','name2','name3')");
Yes, it's because they are strings. Strings need to be quoted properly, otherwise MySQL won't see them as strings. Use
$delete_query = ("DELETE FROM _users WHERE USER in('name1','name2','name3')");

Categories