I would like to know how I can update a value stored in an array, in crate.io
I have a blog table - blog_tbl
A column, with data type array - tags
A id column
Inside the tags column I have - ["tag1","tag2","tag3"]
I would to know how I would go about changing 'tag1' to 'tag99'
I tried
update blog_tbl set tags['tag1'] = 'tag99' where id = '1';
Also how would I add one the the end? so making it -
["tag1","tag2","tag3","tag4"]
many thanks
Unfortunately it's not possible currently. Array elements can only be selected using the subscript notation (e.g. select tags[1] from blog_tbl;) but not updated. Maybe add a GH issue requesting that feature.
You can use the pattern found here: https://crate.io/docs/reference/sql/occ.html#optimistic-update
However, that requires you to perform the modification on client side. Pseudo code:
updated = False
while not updated:
cursor.execute('SELECT array_field, "_version" FROM table WHERE id=1')
row = cursor.fetchone()
current_array_field = row[array_field]
current_array_field.append('newtag')
cursor.execute('UPDATE array_field = current_array_field WHERE id=1 AND "_version" = row[version]')
if cursor.rowcount > 0:
updated = True
This will make your update semi safe for concurrent updates of the same field.
Related
I'm using PHP in order to create a website where managers have access and review forms that employees have submitted. In the reviewing PHP file, I have created two buttons which basically approve or disapprove the form. After they click on one of the buttons, they are being redirected to another PHP file which actually inserts into the MySQL Database a change in a column I named 'processed'. It changes 0 which is unprocessed to 1, which is processed. The table I am referring to has columns such as formid, fullname, department and other job related stuff, as well as the 'processed' column which allows the managers to see if there is a pending form to be reviewed.
My problem is that I have no idea how to actually allow MySQL to find the proper row and change only the cell with the name 'processed' from 0 to 1 without having to insert every cell again. Here's what I have tried till now:
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "INSERT INTO carforms (processed) where aboveid='$id' and processed='0' and teamformid=$teamformid
VALUES ('0')";
}
else if (isset($_POST['disapproved'])) {
//todo
}
How do I tell SQL to only find the specific row I want and change only one column which is processed?
Also, do I always have to type every column name when I use the INSERT INTO command?
Thanks in advance.
Use the Below code it'll work for you.
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "UPDATE `carforms` SET processed = '1' WHERE `aboveid` = '".$id."' AND `teamformid` = '".$teamformid."'";
}
Try:
"UPDATE carforms SET processed = 1 WHERE aboveid = $id AND teamformid = $teamformid"
From what I have interpreted from your question, it seems like you need to use the MySQL UPDATE command. This will update any existing rows.
For example, let's say you have a table called 'forms', consisting of a Primary Key 'form_id' and a field named 'processed'.
If we want to change the value of 'processed' to '1', we would run...
UPDATE forms SET processed = 1 WHERE form_id = [whatever number the form is];
Obviously this only works where the form (with a form_id) exists already
There is no "INSERT...WHERE" in SQL.
To change an existing record there are 2 options, REPLACE or UPDATE. The former will create the record if it does not already exist and has similar syntax to INSERT. UPDATE uses the WHERE clause to identify the record(s) to be changed.
Using REPLACE is tricky. It needs to work out whether it should INSERT a new record or UPDATE an existing one - it does this by checking if the data values presented already exist in a unique index on the table - if you don't have any unique indexes then it will never update a record. Even if you have unique indexes just now, the structure of these may change over time as your application evolves, hence I would recommend NOT using REPLACE for OLTP.
In your question you write:
where aboveid='$id' and processed='0' and teamformid=$teamformid
(it would have been helpful if you had published the relevant part of the schema)
'id' usually describes a unique identifier. So there shouldn't be multiple records with the same id, and therefore the remainder of the WHERE clause is redundant (but does provide an avenue for SQL injection - not a good thing).
If the relevant record in carforms is uniquely identifed by a value for 'id' then your code should be something like:
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
But there's another problem here. There are 3 possible states for a record:
not yet processed
declined
approved
But you've only told us about 2 possible states. Assuming the initial state is null, then the code should be:
$action=0;
if (isset($_POST['approved'])) {
$action=1;
}
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
if ($id &&
(isset($_POST['disapproved']) || isset($_POST['approved']))
) {
// apply the SQL to the database
} else {
// handle the unexpected outcome.
}
I have a table where one column has 0 for a value. The problem is that my page that fetches this data show's the 0.
I'd like to remove the 0 value, but only if it's a single 0. And not remove the 0 if it's in a word or a numeric number like 10, 1990, 2006, and etc.
I'd like to see if you guys can offer a SQL Query that would do that?
I was thinking of using the following query, but I think it will remove any 0 within a word or numeric data.
update phpbb_tree set member_born = replace(member_born, '0', '')
Hopefully you guys can suggest another method? Thanks in advance...
After discussed at the comments you have said that you want to not show 0 values when you fetching the data. The solution is simple and should be like this.
lets supposed that you have make your query and fetch the data with a $row variable.
if($row['born_year'] == '0'){
$born_year = "";
} else {
$born_year = $row['born_year'];
}
Another solution is by filtering the query from the begging
select * from table where born_year !='0';
update
if you want to remove all the 0 values from your tables you can do it in this way. Consider making a backup before.
update table set column='' where column='0';
if the value is int change column='0' to column=0
I'm working with a table in which information is stored in a table in JSON format. The JSON value field looks like:
select * from k2_extra_fields where id = 2 and published = 1;
id | value
2,[{"name":"Apples","value":1,"target":null,"alias":"","required":0,"showNull":1},{"name":"Pears","value":2,"target":null,"alias":"","required":0,"showNull":1},{"name":"Mangos","value":3,"target":null,"alias":"","required":0,"showNull":1},{"name":"Guava","value":4,"target":null,"alias":"Fruit","required":0,"showNull":1},{"name":"Pineapple","value":5,"target":null,"alias":"Fruit","required":0,"showNull":1}]
Or values in a simple line by line view (minus the ID):
[
{"name":"Apples","value":1,"target":null,"alias":"","required":0,"showNull":1},
{"name":"Pears","value":2,"target":null,"alias":"","required":0,"showNull":1},
{"name":"Mangos","value":3,"target":null,"alias":"","required":0,"showNull":1},
{"name":"Guava","value":4,"target":null,"alias":"Fruit","required":0,"showNull":1},
{"name":"Pineapple","value":5,"target":null,"alias":"Fruit","required":0,"showNull":1}
]
The query that leads me here returns the value of 3. 3 = Mangos. How do I take the '3' value and match it up with the stored names/values so that I end up with the output, Mangos?
It should be possible with build in mysql functionality, but very hard and 'not clever' idea to do. If you really need to compute this problem within mysql, you would need to actually add new funtionality to your mysql. Look up on UDF plugins: http://dev.mysql.com/doc/refman/5.1/en/udf-compiling.html
usersim interested how do i select a text field form my mysql database, i have a table named users with a text field called "profile_fields" where addition user info is stored. How do i access it in php and make delete it? I want to delete unvalidate people.
PHP code
<?php
//Working connection made before assigned as $connection
$time = time();
$query_unactive_users = "DELETE FROM needed WHERE profile_fields['valid_until'] < $time"; //deletes user if the current time value is higher then the expiring date to validate
mysqli_query($connection , $query_unactive_users);
mysqli_close($connection);
?>
In phpmyadmin the field shows (choosen from a random user row):
a:1:{s:11:"valid_until";i:1370695666;}
Is " ... WHERE profile_fields['valid_until'] ..." the correct way?
Anyway, here's a very fragile solution using your knowledge of the string structure and a bit of SUBSTRING madness:
DELETE FROM needed WHERE SUBSTRING(
profile_fields,
LOCATE('"valid_until";i:', profile_fields) + 16,
LOCATE(';}', profile_fields) - LOCATE('"valid_until";i:', profile_fields) - 16
) < UNIX_TIMESTAMP();
But notice that if you add another "virtual field" after 'valid_until', that will break...
You can't do it in a SQL command in a simple and clean way. However, the string 'a:1:{s:11:"valid_until";i:1370695666;}' is simply a serialized PHP array.
Do this test:
print_r(unserialize('a:1:{s:11:"valid_until";i:1370695666;}'));
The output will be:
Array ( [valid_until] => 1370695666 )
So, if you do the following, you can retrieve your valid_until value:
$arrayProfileData = unserialize('a:1:{s:11:"valid_until";i:1370695666;}');
$validUntil = arrayProfileData['valid_until'];
So, a solution would be to select ALL items in the table, do a foreach loop, unserialize each "profile_fields" field as above, check the timestamp, and store the primary key of each registry to be deleted, in a separate array. At the end of the loop, do a single DELETE operation on all primary keys you stored in the loop. To do that, use implode(',', $arrayPKs).
It's not a very direct route, and depending on the number of registers, it may not be slow, but it's reliable.
Consider rixo's comment: if you can, put the "valid_until" in a separate column. Serializing data can be good for storage of non-regular data, but never use it to store data which you may need to apply SQL filters later.
I have a view that needs updating with a list of id's. So I am storing the values that have been selected to remove from the view in a session variable that then goes into the mySQL query as below. Then when the form is reset the values are also reset out of the array.
But its not working... this is what I've got.
Any help would be appreciated.
if($_POST['flag']=='flag'){
//collect deleted rows
$_SESSION['delete-row'][] = $_POST['idval'];
//Split session array
$idavls = join(',' , $_session['delete-row'];
$sqlDelete = "CREATE OR REPLACE VIEW filtetbl AS SELECT * FROM `".$page['db-name']."`.`leads_tbl` WHERE ".$_SESSION['filter-view']." AND `lead_status` = '1' AND `lead_id` NOT IN (".$idvals.") ORDER BY `lead_added`";
$result = mysql_query($sqlDelete);
if($result){
echo true;
}
else{
echo mysql_error();
}
}
$_session isnt the same as $_SESSION for a start.
Also dont use mysql_query or similar (because it isnt safe) use PDO
This is hard to correct without more information (and there are several errors - probaby cut and paste) so I'll pull apart one by one and you can go from there.
1 - $_SESSION['delete-row'][] = $_POST['idval'];
If 'idval' comes from multiple inputs (i.e. ) then it is already an array, and you should have $_SESSION['delete-row'] = $_POST['idval']; If you are looping in an array of inputs (i.e. trying to append for many posts from then it is correct)
2 - $idavls = join(',' , $_session['delete-row'];
$_SESSION (you said this was a type) and you also need a bracket/bract ar the end
$sqlDelete = "CREATE OR REPLACE VIEW filtetbl AS SELECT * FROM ".$page['db-name'].".leads_tbl WHERE ".$_SESSION['filter-view']." AND lead_status = '1' AND lead_id NOT IN (".$idvals.") ORDER BY lead_added";
Firsly this is very insecure as pointed out by allen213. Even if you don't use PDO to make safe the variable, please cast all the inputs as (int) assuming the IDs are integers, or at least wrap the input in mysql_real_escape_string().
Secondly, the logic in the question doesn't quite make sense. You say you want to remove IDs from the view, but what you are doing is recreating the view with only those IDs in $_SESSION['delete-row'] removed - so this may re-introduce IDs previously removed from the view. You'd actually need to keep $_SESSION['delete-row'] and keep adding to it to ensure the next time the view was created, then all the IDs are removed.
I hope that helps. If not, more code may be required (i.e. the form you are using the send data, anythign else that affects sessions etc.