php mysql user info update - php

if ($email != $CURUSER["email"]) {
if (!validemail($email))
bark( _("Klaida! Panašu, kad klaidingai įvedei email adresą!") );
$r = do_mysql_query("SELECT id FROM users WHERE email=" . sqlesc($email)) or sqlerr();
if (mysql_num_rows($r) > 0)
bark( sprintf( _("Toks emailas adresas %s jau naudojamas!"), $email) );
####
$date = date("Y-m-d");
$modcomment_email = "{$date} - E-mail pakeistas, pakeitė: {$CURUSER['username']}";
$modcomment_email = mysql_real_escape_string($modcomment_email);
do_mysql_query("UPDATE users SET modcomment = '$modcomment_email' where id = ".$CURUSER['id']) or sqlerr(__FILE__, __LINE__);
#####
$changedemail = 1;
}
After this script executed row updated, but old data deleted. How update row, but keep old data ?

You're using an UPDATE command. This does, as you've observed, modify the row(s) that match your WHERE clause.
If you'd like to keep the list of previous $modcomment_emails then you'll need to use an INSERT into some table and then make sure you're selecting the most recent record out when you do your SELECT to output the data. You could add a column to keep the date of the insert as something to ORDER BY.

If you need to keep the old data, you would have to move a copy into an archive table, by issuing the "update" command it overwrites anything that was there. Example
if I have a table where username is "Bugfinder" and now, I change the username to "Bug" there will be no reference to Bugfinder because it was overwritten. If I wanted to keep that, I would need to have copied the line into an archive table maybe a long with the date/time of change, so I could look back historically for changes.

Yes - if you want to insert new row use INSERT if want to update use UPDATE. Also solution is to create history table when you would drop needed old date with the time when change happend

Related

To delete() or forceDelete(). A better way to determine

I have a database with 95 tables. A users tables exists for the system users. Many other tables (45 out of the 95) have a "created_by" that refers to the user who created/added the row, through users.id.
Now. If I wanted to delete a user, I just cannot go and do $user->delete(), I need to keep the user around (soft-delete it) in case this user has created rows on other tables. But what if this user didn't add any content, then I should just go ahead and $user->forceDelete() it.
My question is: is there a good way to go about doing this? To check whether a user should be deleted or Force-deleted when we have this big number of tables.
I figured I could just loop though the tables and check if the id of the user (to be deleted) exists, if found then it's ->delete(), else it's ->forceDelete(). Here is the code:
// Get all tables
$allTables = \DB::connection()->getDoctrineSchemaManager()->listTableNames();
$tablesWithCreatedBy = [];
foreach($allTables as $tableName){
$tableColumns = \DB::getSchemaBuilder()->getColumnListing($tableName);
if(in_array('created_by', $tableColumns)){
$tablesWithCreatedBy[] = $tableName;
}
}
foreach($tablesWithCreatedBy as $tableName){
$result = \DB::select(" SELECT created_by FROM `$tableName`
WHERE `created_by` = {$this->user->id} LIMIT 0, 1 ");
if(isset($result[0])){
$this->user->delete();
break;
}
}
// If wasn't trashed from the code above, then force delete the user!
if(!$this->user->trashed()){
$this->user->forceDelete();
}
I feel there must be a better way to do it! Is there?
You've to add records_count to users table that will be incremented every time when user adds content to other tables, so after that change solution will be simple as:
$result = ($this->user->records_count > 0)
? $this->user->delete()
: $this->user->forceDelete();
Or write Laravel Console Command and run it at background that will walk through db and do cleanup operations.

how to use a specific UPDATE query if existing row is empty mysql

I have searched far and wide for a specific case were i could get this answer but what i have seems to me like it should work. but it doesn't.
I basically want to concatenate data into a row in my database. Put simply if there is no existing data it injects the filenames variable into the row.
If there is existing data in the row i need to append a "," to the start so that i can break the filenames out later with php on my page.
Here's what i have that doesn't seem to work.
$query = "UPDATE plan
SET plan_files = if(plan_files is null,concat(plan_files,
'{$filenames}'),concat(plan_files, ',{$filenames}'))
WHERE plan_id='{$planid}'";
try this
$query = "update plan SET plan_files = (case when plan_files IS NULL then '".$filenames."' else concat(plan_files , ',".$filenames."') end ) where plan_id =". $planid;
Please make sure that $filenames is string and $planid is int.
You can do like this :
"UPDATE `plan` SET
plan_files=CASE
WHEN (plan_files='') THEN '".$filenames."'
ELSE concat(name,',".$filenames."')
END
WHERE plan_id='".$planid."'"

PHP - Update each row in MySQL table from a web form

I populate a web form with rows of data. Some of the fields I need to be updatable so I put the value into a text field. MySQL query is:
SELECT * FROM results WHERE EventID = %s AND CompNo = %s", GetSQLValueString($colname_rsResults, "int"),GetSQLValueString($colname2_rsResults, "int"));
EventID and CompNo are passed in the URL.
Let's say the result is 50 rows. I want to be able to update the Name field (eg, make correction to the spelling), click a button and have the code update the database with any new values. It doesn't matter that most of the values will not change as this is a very infrequent operation.
I used to be able to do this in ASP but I can't seem to do in PHP.
This is the code I am using and I think it is completely wrong!!
if ((isset($_POST["JM_update"])) && ($_POST["JM_update"] == "form1")) {
$i = 0;
$j = $totalRows_rsResults;
while($i < $j)
$resultID=$_GET['ResultID'];
$vDelete=$_GET['Del'];
if ($vDelete == 1) {
$delSQL = sprintf("DELETE FROM Results WHERE ResultID=$resultID");
mysql_query($delSQL,$connFeisResults);
} else {
$name=$_GET['Name'];
$qual=$_GET['Qual'];
$updateSQL = sprintf("UPDATE results SET Name = ".$name{$i}.", Qual = ".$qual[$i]." WHERE ResultID=$resultID");
mysql_query($updateSQL, $connFeisResults);
$i++;
}
}
There is also a checkbox at the end of each row to check if I need that record deleted. That doesn't work either!!
I am using Dreamweaver CS6 and trying to adapt the update behaviours etc.
Any thoughts? Many thanks in advance.
It looks like you're missing an opening brace after your while statement.
--UPDATED
Also, check your sprintf statements -- they look wrong, and they look like they're writing the raw '$resultID' to the SQL String, instead of the value within it.
See how to do it here: http://www.talkphp.com/general/1062-securing-your-mysql-queries-sprintf.html

Transform MySQL table and rows

I have one problem here, and I don't even have clue what to Google and how to solve this.
I am making PHP application to export and import data from one MySQL table into another. And I have problem with these tables.
In source table it looks like this:
And my destination table has ID, and pr0, pr1, pr2 as rows. So it looks like this:
Now the problem is the following: If I just copy ( insert every value of 1st table as new row in second) It will have like 20.000 rows, instead of 1000 for example.
Even if I copy every record as new row in second database, is there any way I can fuse rows ? Basically I need to check if value exists in last row with that ID_, if it exist in that row and column (pr2 for example) then insert new row with it, but if last row with same ID_ does not have value in pr2 column, just update that row with value in pr2 column.
I need idea how to do it in PHP or MySQL.
So you got a few Problems:
1) copy the table from SQL to PHP, pay attention to memory usage, run your script with the PHP command Memory_usage(). it will show you that importing SQL Data can be expensive. Look this up. another thing is that PHP DOESNT realese memory on setting new values to array. it will be usefull later on.
2)i didnt understand if the values are unique at the source or should be unique at the destination table.. So i will assume that all the source need to be on the destination as is.
I will also assume that pr = pr0 and quant=pr1.
3) you have missmatch names.. that can also be an issue. would take care of that..also.
4) will use My_sql, as the SQL connector..and $db is connected..
SCRIPT:
<?PHP
$select_sql = "SELECT * FROM Table_source";
$data_source = array();
while($array_data= mysql_fetch_array($select_sql)) {
$data_source[] = $array_data;
$insert_data=array();
}
$bulk =2000;
foreach($data_source as $data){
if(isset($start_query) == false)
{
$start_query = 'REPLACE INTO DEST_TABLE ('ID_','pr0','pr1','pr2')';
}
$insert_data[]=implode(',',$data).',0)';// will set 0 to the
if(count($insert_data) >=$bulk){
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = array();
} //CHECK THE SYNTAX IM NOT SURE OF ALL OF IT MOSTLY THE SQL PART>> SEE THAT THE QUERY IS OK
}
if(count($insert_data) >=$bulk) // IF THERE ARE ANY EXTRA PIECES..
{
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = null;
}
?>
ITs off the top off my head but check this idea and tell me if this work, the bugs night be in small things i forgot with the QUERY structure, print this and PASTE to PHPmyADMIN or you DB query and see its all good, but this concept will sqve a lot of problems..

PHP Mysql Update issue

I'm having an issue that I can't quite figure out. I have a bit of code that allows a user to pick, let's say, which type of fruit is their favourite. If they've previously selected 'apples' as their favourite and want to change it to 'oranges' - the script performs well.
But if they select 'apples' when they've already selected 'apples' the MYSQL Update call breaks down and returns an error. It's like it won't write over itself with the same data, that the new value has to be unique. I'm at a loss.... Here's the update bit:
// UPDATE THEIR FRUIT SELECTION...
$q = "UPDATE account SET fav_fruit='" . $row['fruit'] . "' WHERE act_id=$act_id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
echo 'success!';
} else {
echo 'oops!';
}
Again, this works so long as the new selection and what's in the database aren't the same. If they are: I get the oops! error.
Why would you need to update a field to contain a value it already contains?
Regardless, this can be fixed by altering the table structure. You need to remove the unique flag from the fav_fruit column.

Categories