I have two tables in MySQL, and each table has its own datetime field.
I want to copy the datetime of table A to overwrite the datetime of table B.
I use PHP.
$result = mysql_query("select *
from A
where id = $key");
$row = mysql_fetch_array($result);
print $row[2]."\n"; // $row[2] is the datetime field
mysql_query("update B
set date_cal = $row[2]
where id = $key") // try to overwrite datetime in table B
$row[2] has the string representation of datetime field.
But the overwrite operation does not take effect. How to do to overwrite datetime field of table B using php?
If I insist using $row[2] to assign the new datetime field rather running mysql_query again, how to do?
I believe you'll need to wrap the date in quotes in your update query.
mysql_query("update B set date_cal=$row[2] where id=$key")
Should be
mysql_query("update B set date_cal='$row[2]' where id=$key")
On another note, I'd suggest that you don't access your fields by index when you're doing a SELECT * query. If you add another field to your database, $row[2] could end up referring to something else. If you instead call $row = mysql_fetch_assoc($result);, you can refer to it by field name, eg
mysql_query("update B set date_cal='{$row['date_field]}' where id=$key")
If I understand that correctly, you can do the same from within your query:
update B
set date_cal = (select date_cal from A where id = {$key})
where id = $key
Related
I am trying to copy a column of data (which is numeric) to a different column (VARCHAR) in the same table. Seems straight forward to just run an update query and set the varchar column to whatever the $_POST column will be. The problem is numeric columns will contain 5 trailing zeros. I need to reformat it to be an INT type in the copy as well. Here is a copy of the original query in PHP:
try{
$q = "UPDATE table1 SET text1 = " . $_POST["htmlinputfield"] .
" WHERE account_id = :aid AND fieldapplication_id = :fid";
$stmt = $this->app->db->prepare($q);
$stmt->execute(array(":fid"=>$this->app->fid,":aid"=>$this->app->aid));
} catch(exception $e){
$this->app->logErroredQuery($e,$q);
return $e->getMessage();
}
I tried changing the datatype using php in an if statement then sticking into the query. Couldn't get that to work either. Here is what that looked like:
$htmlfield = $_POST["htmlinputfield"];
if(is_numeric($htmlfield)){
(int)$htmlfield;
}else{
(string)$htmlfield;
}
try{
$q = "UPDATE table1 SET text1 = :htmlfield
WHERE account_id = :aid AND fieldapplication_id = :fid";
$stmt = $this->app->db->prepare($q);
$stmt->execute(array(":fid"=>$this->app->fid,
":aid"=>$this->app->aid,
":htmlfield"=>$htmlfield));
} catch(exception $e){
$this->app->logErroredQuery($e,$q);
return $e->getMessage();
}
This resulted in changing all of the results to be the name of the column instead of a copy of the data. The original query works fir everything but numeric situations.
I imagine that this might be a CAST situation but my SQL abilities are not very good. The end result would be that whatever the database column that is being selected in the $_POST will be formatted to an int or a varchar. Any help would be much appreciated.
The first query with $q = "UPDATE table1 SET text1 = " . $_POST["htmlinputfield"] is the general way this needs to be done. You will need to insert the column name directly into the SQL string, but it's not safe to blindly use a value from $_POST like that. You should verify that $_POST["htmlinputfield"] is a valid column name before you use it in the query. You can use a whitelist method and check it against an array of acceptable column names in your PHP code.
The second way with $q = "UPDATE table1 SET text1 = :htmlfield can't work, because the column name is an identifier, and you can't bind identifiers, only values.
This part:
$htmlfield = $_POST["htmlinputfield"];
if(is_numeric($htmlfield)){
(int)$htmlfield;
}else{
(string)$htmlfield;
}
does not really make sense, because $_POST["htmlinputfield"] is the column name if I understood you correctly, and using is_numeric() in PHP isn't going to tell you what the data type of that column is, it's just going to check if the column name is numeric.
I think one way to solve this is to check if the value is numeric in your update query and remove the decimal places if so, otherwise take it as is. So first validate the posted column name as I mentioned above. After you've done that, you can safely use it in the query like this:
"UPDATE table1 SET text1 = CASE
WHEN `$column_name` REGEXP '^[0-9]+(\.[0-9]+)?$'
THEN FLOOR(`$column_name`)
ELSE `$column_name`
END
WHERE account_id = :aid AND fieldapplication_id = :fid"
There are different ways to check if a value is numeric, and different ways to convert the value to int, but I think the general idea will still be something like this.
Try the following query in your last example:
UPDATE table1 SET text1 = CAST(:htmlfield AS UNSIGNED) WHERE account_id = :aid AND fieldapplication_id = :fid
When we update a MySQL record with php, we can check if it has effect using:
$mysqli->affected_rows;
But how do I check which column has been modified?
Example, in my table have the columns: id / name / age
In a record we have the data: 1 / Woton / 18
If I send an: UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'
Only the age field has changed. How can I determine this?
You cannot directly get the updated columns from the query result.
It can be get from some php query. Firstly we will have to select the row from database which we are going to update in a array variable. Than run the update query for the same row.
Lastly get the same row from database from select query in the new array variable.
Finally we get two arrays.
We can get the updated column with the array_diff_assoc php function.
See the below code for the same.
$sql = "SELECT * from mytable where id=1 limit 1";
$prev = mysqli_fetch_assoc(mysqli_query($conn, $sql));
//Get the column data in the array. Before update.
$sql = "UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'";
$conn->query($sql);
// Update data
$sql = "SELECT * from mytable where id=1 limit 1";
$updated = mysqli_fetch_assoc(mysqli_query($conn, $sql));
// Again run the select command to get updated data.
$UpdatedColumns=array_diff_assoc($updated,$prev);
In a different note: If QueryLog has been enabled in the DB then you (or your script in PHP or Python or any) can easily see/read which part of the content has been updated and even you can monitor the DB.
The good news is, even you can target which table, which query etc.
Well i built my website to write dates to database column in the following format:
2014/04/01
Now i've come to realize this is not helpful when i want to sort by date or manipulate date so i decided to change all date to to timestamps.
i applied the following fix :
$sql = mysql_query("SELECT * FROM TABLE")or(die(mysql_Error()));
while($info = mysql_fetch_array($sql)){
$newdate = strtotime($info['date']);
mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = $info[id]")or(die(mysql_error()));
}
the problem is all the date columns are empty now, What am i doing wrong ?
There's what looks like a syntax error on this line:
mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = $info[id]")
or(die(mysql_error()));
Try changing it to:
mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = {$info['id']}")
or (die(mysql_error()));
The reason is that when interpolating array indices into a string, you must surround them with {} or PHP will just try to convert $info to a string and insert [id] after it, which I'm guessing you didn't intend.
I would also suggest checking the return value for strtotime. If it can't parse a date it returns false which I'm guessing you don't want inserted back into your database.
I'm trying to update my first row in my database. I use the Limit 1 to only update the first row but nothing is happening. There are definitely matching rows but nothing changes in the database.
Here is the code:
foreach ($player_fromsite as $match_player_in_game) {
//$querytwo = 'INSERT INTO `'.$tablename.'` '.' (`'.$match_player_in_game.'`) '.'VALUES'.'("' . 'yes' . '")';
$querytwo = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
$querythree = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
for($a=0;$a<11;$a++){
if($match_player_in_game == $home_players[$a]){
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
}else{
mysql_query($querythree) or die(mysql_error());
}
}
}
Is the query correct?
In MySQL use IS NULL to compare with NULL.
For example: "UPDATE table SET field = 'yes' WHERE field IS NULL"
NULL isn't a string, so you shouldn't be using = 'NULL', unless you actually set it to that string value. Use IS NULL instead.
You need to define "first row". First row based on an autoincrementing id value? First based on a timestamp date? You need to specify this as MySQL has no concept of "first row".
For example, if you do something like this in MySQL:
SELECT * FROM table LIMIT 1
You are not guaranteed to get the same record back each time.
Most likely you will need to specify an ORDER BY condition on a key column, as without it, you have no guarantee of which row your LIMIT 1 will apply to. I really can't think of a case where one might use LIMIT without an ORDER BY clause, as the two really go hand in hand.
So your query should look like:
UPDATE table
SET field = 'yes'
WHERE field IS NULL
ORDER BY some_key_field ASC
LIMIT 1
Note that even this query would not update the same row every time. It would update the first record (as specified by ORDER BY) that has a NULL value for the specified field. So if you ran this query 10 times, it would change 10 different records (assuming there are that many records with NULL values).
I have a table called tblActivities. There are two fields ID and Attendees.
ID Attendees
1 Jon Jhonson
2 Ive Iveson
Which PHP function or MySQL statement do I need to use to get to this result:
ID Attendees
1 Jon Jhonson, Ive Iveson, Adam Adamer
2 Ive Iveson
In other words, how can I add new data to existing data in my database?
You need something like:
UPDATE tblActivities
SET Attendees = CONCAT(Attendees, "Ive Iveson, Adam Adamer")
WHERE id = 1;
But maybe you should change the database layout. It is preferable to have only one value in one field. You could find more information under http://en.wikipedia.org/wiki/Database_normalization.
use mysql's update statement. If you want to exeute through php then
first get the existing value using select statement,
SELECT Attendees from <table-name> WHERE ID = 1
you will get attendees existing value, put it in a php variable, now concatenate your value..
and then update,
UPDATE <table_name>
SET Attendees=<new-value>
WHERE ID=1
you would have to use the php's mysql functions to run the above queries
I think you're better off restructuring. Make a table:
ID (primary key)
ACTIVITY_ID (foreign key to activity table)
ATTENDEE (foreign key to USERS table)
Then select everything from that event and concat in PHP.
$q = mysql_query( 'SELECT ATTENDEE FROM tblActivities '.
'WHERE ACTIVITY_ID = $activity_id' );
$attendees = array();
while( $row = mysql_fetch_assoc( $q ) )
{
$attendees[] = $row['attendee'];
}
$attendees =implode( ' ', $attendees );