I have two tables called clients, they are exactly the same but within two different db's. Now the master always needs to update with the secondary one. And all data should always be the same, the script runs once per day. What would be the best to accomplish this.
I had the following solution but I think maybe theres a better way to do this
$sql = "SELECT * FROM client";
$res = mysql_query($conn,$sql);
while($row = mysql_fetch_object($res)){
$sql = "SELECT count(*) FROM clients WHERE id={$row->id}";
$res1 = mysql_query($connSecond,$sql);
if(mysql_num_rows($res1) > 0){
//Update second table
}else{
//Insert into second table
}
}
and then I need a solution to delete all old data in second table thats not in master.
Any advise help would be appreaciated
This is by no means an answer to your php code, but you should take a look # Mysql Triggers, you should be able to create triggers (on updates / inserts / deletes) and have a trigger (like a stored proceedure) update your table.
Going off the description you give, I would create a trigger that would check for changes to the 2ndary table, then write that change to the primary table, and delete that initial entry (if so required) form the 2ndary table.
Triggers are run per conditions that you define.
Hopefully this gives you insight into 'another' way of doing this task.
More references on triggers for mysql:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx
You can use mysql INSERT ... SELECT like this (but first truncate the target table):
TRUNCATE TABLE database2.client;
INSERT INTO database2.client SELECT * FROM database1.client;
It will be way faster than doing it by PHP.
And to your notice:
As long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work. Though the mysql_select_db function selects one database, the mysql statement may reference another if you use complete reference like databasename.tablename
Not exactly answering your question, but how about just using 1 table, instead of 2? You could use a fedarated table to access the other (if it's on a different mysql instance) or reference the table directly (like shamittomar's suggestion)
If both are on the same MySQL instance, you could easily use a view:
CREATE VIEW database2.client SELECT * FROM database1.client;
And that's it! No synchronizing, no cron jobs, no voodoo :)
Related
i have a table that must by update every month, due i upload text file on server and save it in temporary table, the bellow code show it:
$result_emp = "LOAD DATA LOCAL INFILE'".$myFile_emp."' INTO TABLE infemptemp COLUMNS TERMINATED BY ','";
then after update successfully and insert new data in "infemptem" table, i should compare the data of main table's "infemp" that have old data by "infemptemp" that have new data, for do this Scenario i write bellow code:
$viwe_emp =mysqli_query($conn,"select * from infempsame where 1");
$NumRows_emp=mysqli_num_rows($viwe_emp);
//echo $NumRows_vam;
$i=0;
while(($row=$viwe_emp->fetch_assoc())!=NULL)
{
$prsid1=$row['PrsID'];
$AccID1=$row['AccID'];
$numid1=$row['NumID'];
$sql2="select * from infempsame where prsID='".$prsid1."';";
if (mysqli_query($conn,$sql2))
{
$sql2_update="UPDATE `infemp` SET AccID='".$AccID1."',NumID='".$numid1."' WHERE prsID='".$prsid1."';";
if(mysqli_query($conn,$sql2_update))
{
$i+=1;
}
}// end if (mysqli_query($conn,$sql2))
}// end while insert new fields of infvam
by attention to the code and have 3500 record in "infempsame " table on my database, when i want update "infemp" table, the time out on browser occur.
I think if write above code by procedure, my problem solved.
Is it true? How do i can write procedure and call or use it?
Best Regards.
A stored procedure would be overkill. There is a better way hidden away but it get's only a very brief mention in the manual
You can also perform UPDATE operations covering multiple tables.
However, you cannot use ORDER BY or LIMIT with a multiple-table
UPDATE. The table_references clause lists the tables involved in the
join. Its syntax is described in Section 13.2.9.2, “JOIN Syntax”. Here
is an example:
UPDATE items,month SET items.price=month.price WHERE
items.id=month.id;
Thus you can write a simple query to get rid of the PHP script like this.
UPDATE infemp, infemptemp
SET infemp.AccID=infemptemp.AccID,
infemp.NumID=infemptemp.numID
WHERE infemp.prsID=infemptemp.prsID;
if you have an index on the prsID column this should complete very quickly.
I have two servers hosting two different sites with two separate databases. However, some of the data needs to be shared - so there's a CRON that runs to copy that data from the first site to the second site. These two sites used to run on the same server, but now we have separated them so I'm attempting to amend the PHP to be able to handle this.
Here is the code where I'm encountering the problem:
$sql = "SELECT * FROM site1.events";
$events = mysql_query($sql, $site1db);
$sql = "INSERT INTO site2.events SELECT * FROM $events";
$doIt = mysql_query($sql, $site2db);
Now I know that the SELECT * FROM site1.events is successful, but it cannot insert into the second site and I'm not seeing any sort of error. I've never written PHP before (this is a legacy task) so if it's something that's been covered before - do point me in the right direction.
Please note that site2.events is truncated before these commands so no compare is necessary.
You will have to do a row by row compare and copy. What you are attempting to do right now cannot work. You could use INSERT IGNORE INTO site2.events (SELECT * FROM site1.events) if the databases run on the same server and the database user can access both databases. The downside of this, the primary keys would have to be identical or you will miss data.
A better alternative would be to simply have site1 do a callback containing all info for that event to site2 at the moment a new event is added.
I trying to add +1 in a column after select but its not working, what I want is, when I make a search, the scripts adds +1 in a column to track how much searches I did.
Heres how it is now
$QUERY = "SELECT company FROM test WHERE number = '$number[0]' LIMIT 1";
And I want to add this
UPDATE users SET consultas=consultas+1 WHERE username = '$username'
If I add another $QUERY line the script breaks, any ideas ?
By nature, SELECT queries are for returning information from the database, not updating the database. To this end, triggers aren't even available for SELECT queries to react to the action. As such, if you want to increment a value, this must be done in a separate query, as an UPDATE query or possibly an INSERT ... ON DUPLICATE KEY UPDATE query if that better suits your needs.
You should execute those as two separate queries. Also, be very careful to ensure your data is properly escaped because it looks like you've forgotten to do that.
Be sure to check the result code of each as an error may occur at any time. If you use PDO there's a fairly robust error handling pattern you can follow.
I want to get the last affected table name (after insert).
I tried with mysql_insert_id() but i got only id.
I want table name also.
Can anyone give me the idea for my problem
It's a strech... But if :
you are running mysql 5.6.3 +
you still have access to the insert query (let's say it's $query)
you are sure it's an insert query (because, hey, you know you want last_insert_*, don't you?)
You can try:
$row = mysql_fetch_assoc(mysql_query("explain $query"));
$table = $row['table'];
From mysql 5.6.3+ you can combine explain with a insert into query.
This should return only 1 row, I think.
I dont have mysql 5.6.3+ myself to test it.
You can override mysql_query function as defined in this post, save you last call table name in global var or session and pray for last called insert finish last.
// THIS JUST SAMPLE... use code from link below ^
function custom_mysql_query($query){
if(strstr('INSERT',$query)){
/*GET YOUR TABLE NAME WITH REGEX*/
}
basic_mysql_query($query);
}
This is very very very bad solution for me. But in theory will work.
You mention in your comment that you're using a common function to apply the changes in, preventing you from 'knowing' what the last table is you inserted in.
If that's the case: your logic is flawed.
MySQL is not gonna tell you what the last table is it did an INSERT in. You will have to write a hook in your function where you last know what table you're gonna update. No matter what function you use, you must specifiy a table name at some point, before executing the insert. You store the table name at that point.
You can do that in many ways, depending on your needs:
store it in a mysql table (last_updated_table with only 1 column,
for example)
store it in a variable (if you only need it in the
same request)
store it in a session (I wouldn't opt for this)
You can use the information_schema database if you have one :
SELECT TABLE_SCHEMA, TABLE_NAME, UPDATE_TIME
FROM TABLES
ORDER BY UPDATE_TIME DESC
LIMIT 0,1
Use this after your query, and you'll get the affected table.
I'm using MySQL v.5.0.77 and I was wondering if it is possible to count the number of tables in a database. I have done a lot of research and am unable to find a way to do this that is not depreciated.
For each user that signs up I had generated a table in a database for them. And now I am trying to get a live count of those tables, if that makes sense. Is this a logical way of storing user information? I am unable to programmatically create entire databases on my server.
You can do a query to information_schema.tables
SELECT COUNT(*) FROM information_schema.TABLES
WHERE TABLE_SCHEMA='$database_name';
You could do it like this:
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='YOUR_DB_NAME_HERE'
http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
For each user that signs up I had generated a table in a database for them. And now I am trying to get a live count of those tables, if that makes sense. Is this a logical way of storing user information?
If you're creating a separate table for each and every user then probably not. There are better ways to store the data and relationships, which can be more complicated to learn but will provide far more flexibility, abilities, and scalability later on.
I think you're probably trying to reproduce the functionality of the database in your programming e.g. getting a list of users would require you to run a query on every single user table.
I recommend you take a look at database design and database normalization (try to focus on the concept of how best to store data first without getting bogged down in the specifics).
I don't know if this is slower than ajreal's answer but I've been using :
$sql = "SHOW TABLES";
$res = mysql_query($sql);
$num_tables = mysql_num_rows($res);
Open Terminal, and type use myDB, then show tables;
It will gives you total tables name and last line as total tables count 47 rows in set (0.00 sec)
Or type below query
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='myDB'