how to add prefix in auto generated field value in database table? - php

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.

Related

How to make a multiple update on mysql with string replace with value of another column

Hello i'm new in mysql and i have to run a multiple update on my table.
I have 700 records in the table and i have to update them all this way:
table example :
store_id: 1
store_email: storename#gmail.com
for single update i use
UPDATE stores SET email = '1#gmail.com' WHERE id = 1;
i need to update all the emails and replace their name with their id, so it would be like this:
storename#gmail.com --> 1#gmail.com
storename#gmail.com --> 2#gmail.com
storename#gmail.com --> 3#gmail.com
those numers have to be the ID for each store.
Hope you can understand
Thanks for help.
P.S. i need to run it on magento 2
you can use CONCAT() and RIGHT() function for manipulating strings like this:
UPDATE stores SET email = CONCAT(id, RIGHT(email, 9));
The RIGHT('string', n) function extracts n characters (storemail = 9 chars in your case) from a string (starting from right).
Since you are adding id to String column gmail, you can use contact() fucntion like below :
UPDATE stors SET email=CONCAT(id, "#gmail.com") where id=2;

How to add a possble value to a MySQL SET type in php, without know the current values

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.

Insert into mysql table if nrecord not existed without using unique

I want to insert new record in database if not already present. I know I can do it if I make that column unique but cant do this as there are several redundant records already present . So i wish any new record I insert should only be inserted if not already present.
Sample table for reference
id name
1 a
2 b
3 c
Before inserting do a select query:
Select id from tablename where name = 'a' limit 1;
Then check, if the result has rows. If it does not have rows execute the insert statement.
INSERT IGNORE INTO... You can find more info on already accepted answer on another question.
I will use pseudo-code to explain .
Use a select query with a WHERE that gonna select only value/values that is/are equal to the value/values of the input type .
You will have to store the values in variables , one variable for the input type and one variable to store the value for the select query.
Before that don't forget to store variables because if you do a search it will read the value but not gonna store it and the second reason is it's gonna help you for the if and else if .
Also i will recommend you to see POST method and REQUEST method and logic operators ( ex: && , || , etc ... )
You should use a if and a else if .
The if could be:
if variable1 = variable 2
echo "Data already exist" ;
end of the if
the else if could be :
Insert query
end of the else
You should echo the value that you get from the select query just to be sure for your test.

Select a text field from mysql in php

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.

mysql if word match statement

how do i save the data, if
1) the word match Pros, it will be saved to t_pros column
2) the word that not match Pros, it will be saved to t_others column
i heard i can use mysql CASE statement, but dont know how to use it?
table pro:
id t_pros t_others
------------------------
1 Pros 1x
2 Pros 2x
3 voucher
<input type="text" id="t_pros">
$db->query("INSERT INTO pro(t_pros,t_others) VALUES($t_pros, $t_pros)");
So in each row only one of the two columns ever has a value?
In that case, how about:
$column = (preg_match('/^Pros/i', $_POST['t_pros'])) ? 't_pros' : 't_others';
$t_pros = mysql_real_escape_string($_POST['t_pros']);
$db->query("INSERT INTO pro($column) VALUES ($t_pros)");
That is, pick which column based on whether the value begins with 'Pros' or not (just as you indicated), and then just insert into that column, using MySQL's default value (normally NULL) for the other.
First, your input field needs the attribute name="t_pros".
Secondly, this code is open to SQL Injection - read up on it.
The query might look like this:
INSERT INTO pro(t_pros,t_others) VALUES(IF($t_pros = 'Pros', 'Pros', NULL), IF($t_pros = 'Pros', NULL, $t_pros))"
But again, this is not safe. Use mysql_real_escape_string around all variables in your SQL query, or use prepared statements.
if ($t_pros == 'Pros')
$t_pros_col = $t_pros;
else
$t_others_col = $t_pros;
$db->query("INSERT INTO pro(t_pros,t_others) VALUES($t_pros_col, $t_others_col)");

Categories