简体   繁体   中英

Cron php update/insert one sql table from another

I am not that good in php so I would appreciate your help.

I need to update or insert certain data from one mysql table to another mysql table same server!

Bought tables have same column and what I want is to update certain rows with prechosen mid! Table:

|ID| |mid| |value1| |value2|

I did the part where php for update or insert to check if it exists but what I need it to do is to repeat the step pos each given

So what I need it to repeat this script for each mid I list to be done

mid1 = 66
mid2 = 78
mid3 = 24


$con = mysql_connect("localhost","User","Pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db(baza, $con);

$result = mysql_query("SELECT * FROM table WHERE mid='???' ");

while($row = mysql_fetch_array($result))
{
$mid=$row['mid'];
$name=$row['value1'];
$alias=$row['value2'];
}

mysql_close($con);
?> 
<?php
$con2 = mysql_connect("localhost","user2","pass2");
if (!$con2)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db(baza2, $con2);


$query = "SELECT * FROM table WHERE mid='$mid' ";
$resulta = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($resulta) )
{

mysql_query("UPDATE table SET mid='$mid', name='$name', alias='$alias'");
mysql_close($con2);
echo "1 record added1";
}
else
{
$sql="INSERT INTO table (mid, name, alias)
VALUES
('$mid','$name','$alias')";

if (!mysql_query($sql,$con2))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con2);
}

Thank you in advance!

If the 2 databases are on the same server, you can set-up your account to have access to both databases. If so, you can simple select the database in your queries on this way:

mysql_query("SELECT * FROM my_database.my_table WHERE ..");

Your code will be..

$mid_array = array(66, 78, 24);
$con = mysql_connect("localhost","user","pass");
if(!$con) {
    die('could not connect: '.mysql_error());
}
mysql_select_db(baza, $con);

foreach($mid_array AS $mid) {
    $result = mysql_query("SELECT * FROM table WHERE mid = '".$mid."'";
    while($row = mysql_fetch_array($result)) {
       mysql_query("INSERT INTO baza2.table (mid, name, alias) VALUES ('".$row['mid']."', '".$row['name']."', '".$row['alias']."') ON DUPLICATE KEY UPDATE name = '".$row['name']."', alias = '".$row['alias']."'");
    }
}
mysql_close($con);

You don't need a different query to check if the record with mid = .. already exists. You can simply handle this with the mysql ON DUPLICATE KEY UPDATE statement which will do this for you in only 1 query!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM