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.
Related
Hi everybody and sorry for my english.
I have the column "example" that is a SET type.
I have to make a php page where you can add values to that column.
First of all I need to know what is just in "example", to prevent the adding of an existing value by a control. Second of all I need to add the new value.
Here's what I had thinked to do.
//I just made the connection to the db in PDO or MySQLi
$newValue=$_POST['value']; //I take the value to add in the possible values from a form
//Now I have to "extract" all the possible values. Can't think how.
//I think I can store the values into an array
$result=$sql->fetch(); //$sql is the query to extract all the possible values from "example"
//So now i can do a control with a foreach
foreach($result as $control){
if ($newValue == $control){
//error message, break the foreach loop
}
}
//Now, if the code arrives here there isn't erros, so the "$newValue" is different from any other values stored in "example", so I need to add it as a possible value
$sql=$conn->query("ALTER TABLE 'TableName' CHANGE 'example' 'example' SET('$result', '$newValue')"); //<- where $result is the all existing possible values of "example"
In PDO or MySQLi, it's indifferent
Thanks for the help
We can get the column definition with a query from information_schema.columns
Assuming the table is in the current database (and assuming we are cognizant of lower_case_table_names setting in choosing to use mixed case for table names)
SELECT c.column_type
FROM information_schema.columns c
WHERE c.table_schema = DATABASE()
WHERE c.table_name = 'TableName'
AND c.column_name = 'example'
Beware of the limit on the number of elements allowed in a SET definition.
Remove the closing paren from the end, and append ',newval').
Personally, I don't much care for the idea of running an ALTER TABLE as part of the application code. Doing that is going to do an implicit commit in a transaction, and also require an exclusive table / metadata lock while the operation is performed.
If you need a SET type - you should know what values you add. Otherwise, simply use VARCHAR type.
I have a column family in cassandra which records all the events emitted by a particular user over a specified time period.
I'm using a composite column consisting of a UUID1 and a UTF8 string. I'd like to select all the columns after a paticular time.
// Code to create the column family.
use phpcassa\SystemManager;
$sys = new SystemManager('127.0.0.1');
$sys->create_column_family($keyspace, 'UserActivity', array(
"comparator_type" => "CompositeType(LexicalUUIDType, UTF8Type)",
"key_validation_class" => "UTF8Type"
));
In the code below I try to read the data. Initially I tried creating an array with just the event type set at the 1 index, however although this seemed to work I got lots of errors in the log. Now, I'm trying to set a timestamp in the past and base a UUID1 on it. No errors - but no data either.
// Code to read data
$activityFam = new ColumnFamily($this->pool, 'UserActivity');
$activityFam->insert_format = ColumnFamily::ARRAY_FORMAT;
$activityFam->return_format = ColumnFamily::ARRAY_FORMAT;
$fiveMinPrev = $this->dateFactory->getDateTime();
$fiveMinPrev->sub(new \DateInterval("PT5M"));
$uuid = \phpcassa\UUID::uuid1(null, $fiveMinPrev->getTimestamp());
// Get the most recent SESSION event from the users activity log.
$slice = new ColumnSlice(array(0 => $uuid, 1=>self::EVENT_SESSION));
$columns = $activityFam->get($someUserId, $slice);
How do I achieve selecting columns from a specified time onwards?
Thanks,
Bah!
I realised this is exactly the correct approach to take however it seems I wasn't using a timestamp generated by my 'DateFactory' (which allows me to freeze and manipulate time during testing) to base the timestamp on when I actually inserted the record.
Thus producing incorrect results!
we have a auto-generated field in database table and we want to add prefix in auto-generated value Like AVL0001.
So you could do it a couple ways... Is this an auto-index field in the database? If it is an integer type, then you won't be able to include data like you are mentioning above, however, if it is something generated from a script, just concatenate the number and your prefix before insert. You could probably also do this with a trigger on the database. Any additional details would help improve this answer.
$currentdbvalue = 'example';
$prefix = 'AVL0001';
$newvalue = $prefix.$currentdbvalue;
outputs "AVL0001example"
or if you'd like an underscore u can use:
$newvalue = $prefix."_".$currentdbvalue;
which would output "AVL0001_example"
Let id be your table column. You can add AVL ahead of your id by concatenating both in your sql query.
ie In Mysql,
$yourid="1";
INSERT INTO table( id )
VALUES (
CONCAT( "AVL", $yourid, id )
)
Or you can concatenate the AVL with yourid before inserting it into database like,
$yourid="AVL"."1";
In either way you cannot add it into an auto incrementing field. Because its type is INT.
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.
Basically, i have a working form where the user inputs details about their laptop to sell to my shop.
I give them a quote once they have submitted the Specs of the laptop.
At the moment i have got option boxes and checkboxes which each have a value-- for example these. ---
<label for="state">State</label><br>
<select name="state">
<option value="10">Excellent</option>
<option value="5">Good</option>
<option value="0">Poor</option>
</select><br>
The Values of the options they have selected get added up at the end and that gives them the quote - in the above example - "10" means £10 extra for a excellent condition laptop etc.
I use $_POST[state] to get the value of it to add onto the other options for the quote.
But my problem lies when i POST them to a database (so we can check when they come in).
When they get added to the database, obviously it just comes out as the values not the actually name of it like "excellent" or "good". just says "10" or "5".
Is there anyway to put the name of the option into the database instead of the value?
sure... just make sure that's what you want to do. It's usually not considered a good database practice to create denormalized tables like that, but you could do it. When you collect your post data, simply create another variable and assign a value to it based off the state value like so:
$stateText = '';
switch ($state){
case 10:
$stateText = 'Excellent';
break;
case 5:
$stateText = 'Good';
break;
case 0:
$stateText = 'Poor';
break;
default:
// bad value
$stateText = '';
}
...then store this to the database in a new column.
This is just one of many ways to do this.
You can only do it if you have a lookup, be it an array or in another table that stores the keys and values.
You should be carefuly not to store the post data directly into your database without sanitizing it, otherwise you might become subject to sql injection.
Is there anyway to put the name of the option into the database instead of the value?
There is, but it involves doing it explicitly (converting "10" into "Excellent" before inserting the value) rather than just basically tossing $_POST into the database as-is. You can make this very simple if you are building the <option>s with an array in the first place by reading the the array again and swapping the values with the keys.
$values = array(
10 => 'Excellent',
5 => 'Good',
0 => 'Poor',
);
$post_value = $_POST['state'];
$db_value = $values[$post_value];
// further validation: make sure the array key exists or use a default value
// further usage: build your HTML <options> with this array
However:
If you're going to do that, you're much better off storing the values as numbers and converting them to words when you display them (assuming the numbers do have some meaning). This also allows you to localize by providing translations.
Response to comments:
I would recommend a rating system, like 1 through 5, and calculate your price modifications internally - not directly from the user input or from a hardcoded value (in the database). This allows you to tweak the price changes from within your app, rather than from database values that were created at an earlier time, like if you decide an "Excellent" condition warrants an increase of 11 rather than 10 - unless you specifically want the prices "locked in" permanently at the time the product was posted.
Whatever you do, make sure to validate the input - I can't think of any good reason to use direct user input to calculate prices - it should be done internally based on product ids, and any other conditions. HTML source can be modified on-the-fly to post values you didn't expect from the dropdown.
You can't get it via the HTML form. But you can still do a server side that would map the values to the appropriate condition.
You can use a switch statement or an if statement to map them.
if(value == 10){
$condition = 'Excellent';
} else {//....}