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.
Related
I have PHP script that runs every 3 hours that gets the amazon mws orders and save it into my database.
But before I insert an order into my table, I check first if the order exist
SELECT COUNT(*) total FROM orders WHERE transaction_id = "XXXXXXXXX"
But sometimes even if an order exist, the query will return 0. If return 0, I will insert the order into my table and it will end up duplicating the data.
This instance happens to me in my other PHP scripts and I don't understand the issue.
You should use something called as EXISTS for checking whether a row exists or not in your case order.
SELECT EXISTS(SELECT * FROM table1 WHERE ...);
SELECT EXISTS(SELECT * FROM tableName WHERE condition);
If your database uses master-slave mode,you can try to force the master to query.
You can also use the “INSERT IGNORE INTO orders ....” to ignore duplicate.
You may have an error in your MySQL query. I created a test table and write some code to print the result of the query which is working correctly.
You may not be using the quotations properly as this is the error most
of the time when you are working with queries in PHP
Here is the code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practise";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$sql = "SELECT count(*) from test where title='Hello'";
$result = mysqli_query($conn,$sql);
$new =mysqli_fetch_array($result);
echo $new[0];
?>
</body>
</html>
And:
Image of the table where I am executing the query
The output against the MySQL query is:
2
The code works perfectly. If you have any other question, please share your code and I'll be more than happy to help you.
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.
I have two identical tables in my database. I'm trying to ask the user the package number, then when the user clicks a button, it will copy the row matching the user input to another table.
My tables are:
awb - where the original data is.
temp - table to insert the data into.
Here's my code:
$dbhost = "localhost";
$dbuser = "root";
$dbname = "outbound";
mysql_connect($dbhost, $dbuser);
mysql_select_db($dbname) or die(mysql_error());
$packNO = $_GET['packNO'];
// Escape User Input to help prevent SQL Injection
$packNO = mysql_real_escape_string($packNO);
//build query
$query_add="INSERT INTO temp FROM awb WHERE packNO = '$packNO'";
#mysql_query($query_add);
$query = "SELECT * FROM temp";
$qry_result = mysql_query($query) or die(mysql_error());
The code that follows outputs the content of the temp table. But when I print it, I get nothing.
Why is the temp table empty when I print its values?
Try something like this
$query_add="INSERT INTO temp SELECT * FROM awb WHERE packNO = '$packNO'";
Documentation
Similar query, but not using *
$query_add="INSERT INTO temp (packNO, name)
SELECT packNO, name
FROM `awb`
WHERE `packNO` = '$packNO'";
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
);
}
Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source