Database check: PHP - php

I need to check my database ( containing different profile information like id, code and data) for any change in the information.
I need to run a check if all the details are the same ( no action needed) or if the details are different ( need to update the database with the new information).
I researched to use mysql_num_rows($result)>0 but couldn't figure how exactly to use it, mainly if there are any changes, how will I update the database table with the new information?

here are the steps.
Step 1:
Get the updated values from website
$id
$code
$data
Step 2:
fire a query to to check updates
$query = "select count(*) as total from table where id='$id' and code='$code',data='$data'";
$result=mysql_query($query);
$data=mysql_fetch_assoc($result);
Step 3:
if($data['total']>0){
$update="update table set code='$code',data='$data' where id='$id'";
mysql_query( $update);
}

If you want to compare two table of MYSQL. You can use SQL statement to get the "different" records.
Then you can use PHP to manipulate the records.
I recommend you to use Php PDO mysql driver , it makes life easier !

Related

save data in mysql by stored procedure

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.

php update record based on fetch

[UPDATE: found solution. see my own answer, below]
i'm trying to learn php and i can't figure how to do something that seems extremely basic, i.e. update a record based on fetching criteria. here's the part of my code that successfully fetches the record:
mysql_select_db('top_choice_system');
$query = "SELECT item_name FROM main ORDER BY cw DESC LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "-- item name --" . $row['item_name'];
how do i update the specifically fetched item?
ftr below is the code i successfully use to update a record. however, in the code below, i specify the record myself in the WHERE portion:
$sql = 'UPDATE main
SET column5=28
WHERE ITEM=15';
my point is i can't figure how to make the WHERE match the fetched record. (or, better yet, how to fetch AND update with the simplest, shortest method.) thank you in advance for any help.
rephrasing my question: i'm learning several things from online tutorials, but for some reason i can't find the most basic info about updating a record but NOT based the record's id: for example, you want to update the specific record that matches a specific criteria. (as in the example above, wanting to update whichever record will be at the top of a specific column if that specific column is ordered from top to bottom.)
update main set column5 =
(SELECT item_name FROM main ORDER BY CW DESC)
you can use query like this update and select together your question is not cleared what data you want and which data you want to update so you can search about update select query and make your query as per your requirement....
EUREKA:
$sql = 'UPDATE main
SET testfield="YES" ORDER BY columnX DESC LIMIT 1';
note:the ORDER BY condition did not work with a WHERE line. it worked when i added it to the SET line.
(ftr found code on http://www.phpknowhow.com/mysql/update-statement/)

MySQL update statement not working

I am trying to update a the row in the table 'notes' using the following queries in PHP.
$xyz = mysql_query("Select AVG(x) as AVG_X, AVG(y) as AVG_Y, AVG(z) as AVG_Z FROM `notes_two` where id=".$id);//I am selecting average value of (x,y,x) from another table notes_two
$rowxyz = mysql_fetch_row($xyz);
// Saving the position and z-index of the note:
mysql_query("UPDATE notes SET xyz='".$rowxyz[0]."x".$rowxyz[1]."x".$rowxyz[2]."', actualxyz='".$x."x".$y."x".$z."' WHERE id=".$id);
It is not getting updated.
for starters use sprintf when you are working with loads of variables, or better yet pass them as attributes to mysql. Then just copy your generated sql into phpmyadmin or what other tool your using and sql will provide you with debug info so you can easely see your mistake.
good luck

Newly inserted rows deleted when creating a trigger in MySql

I m trying to fetch the IDs of all last inserted rows. For that i was created a trigger as follows;
CREATE TRIGGER mytable_insert
AFTER INSERT ON mytable
FOR EACH ROW SET #insertIDs = CONCAT_WS(',', #insertIDs, NEW.id)
then in the program section the code is like follows
$sql="INSERT INTO `table` ({columns}) VALUES({values})";
$command=Yii::app()->db->createCommand($sql);
if($command->execute()){
$sql='SELECT #insertIDs AS "Inserted_IDs"';
$command=Yii::app()->db->createCommand($sql);
$rows=$command->queryAll();
var_dump($rows);
}
Here I got some IDs....but the problem is i could not find those rows in the database...Dont know what is the mistake.....help needed....
What is your sql syntax?
SELECT #insertIDs AS "Inserted_IDs"
Where "From" ? (SELECT * FROM T;)
The #insertIDs is a user variable, which is visible in current session; so, you may create the different variables with the same name in other MySQL sessions.
It looks like your code uses more then one session, and therefore showы unexpected result. Check that your code uses one session ( I mean MySQL connection) to execute INSERT and SELECT query.
Also, you can try this code in MySQL command-line console, it must work.

How to sync two database tables with each other in mysql PHP

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

Categories