I have a enum column in my table and I am trying to get out the values I have set in the table in a drop down. So first I have written this query to get the column_type and column_name
"SELECT `COLUMN_NAME`,`DATA_TYPE`,`COLUMN_TYPE` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='devsbh' AND `TABLE_NAME`='modules' AND `COLUMN_NAME` NOT IN ('created_at', 'updated_at')"
then I do this to get out the enum values like so
<?php
$regex = "/'(.*?)'/";
preg_match_all( $regex , $modules->COLUMN_TYPE , $enum_array );
$enum_fields = $enum_array[1];
?>
and I display like so
PS:Using laravel's blade template engine.
{!! Form::select($modules->COLUMN_NAME,$enum_fields) !!}
Everything is correct up until here. When I try to store it tries too save as for Y => 0 and for N => 1. How can I get the key => value same as enum value?
the values of $enum_fields as per the console is [0]=>Y , [1]=>N.
You can use the array_combine method to make the key and the value of the array same like so
<?php
$regex = "/'(.*?)'/";
preg_match_all( $regex , $modules->COLUMN_TYPE , $enum_array );
$keyValueSame = array_combine($enum_array[1],$enum_array[1]);
?>
now the key and value of the $keyValueSame array will have the same value.
the values of $keyValueSame as per the console is [Y]=>Y , [N]=>N.
You are probably better off just hard coding the enumerations into your codebase.
Assuming you are using MySQL, the idea behind enumerations is really to restrict the values in the column to a specific set - basically saying "if the value is not one of these strings, don't allow it.".
Enumerations are not designed to be changed often (if at all) - in fact, you may find issues if you do try to alter them it - it can take some database gymnastics to alter them especially if you have lots of records.
If your "lookup" data will change, and you need it to be database stored, make the column a foreign key to another table containing your lookup fields.
If you are stuck with the enumerations, just hard code the list in your dropdown.
Related
I want to change the column name with a descriptive name, like in my table I have a field name "job_title",
I want to replace this heading with "what is your job title", and job_description with "Describe your job description"
For accomplishing this task I can use Aliasing but I want to change the column names dynamically instead of hard code.
I have described these questions in the comments section of the individual field of the table and I am trying to fetch these comments from the database and display comments of the field as the column heading but couldn't accomplish it.
This is my PHP code:
$sql_getcolumns="select * interview_col_comments where table_name ='interview'";
$result = $mysqli->query($sql_getcolumns);
echo "<table>";
echo "<tr>";
while($row = mysqli_fetch_array($result))
{
echo "<th>".$row[0]."</th>";
}
echo "";
I also tried to find a way in the PhpMyAdmin interface if I labeled column names and retrieve labels using a query in PHP
but didn't find this option in the SQL interface.
Is there another Approach using PHP, or SQL Which I can use to give columns of the table descriptive names?
One approach can be make an array in php like below.
<?php $comment=[
'job_title' => "what is your job title",'job_description'=>"Describe your job description"];
echo "<th>".$comment[$row[0]]."</th>";
?>'
Another approach can be make a another table with column description in mysql and replace on run time.
id|column_id|description
1|job_title|"what is your job title"
2|job_description|"Describe your job description"
What you are looking for is called "localization".
There are many ways to do that.
I usually ALSO prefer to keep this information tightly wired to the database I'm working with, so what I did is:
I used the Database Column's Comment field to provide meta-information.
For example, a columns comment can look like this:
#required #de=Vertragsnummer #en=Contract_Number #search
Now, using the following query, I can retrieve the comments, and build a ColumnMetadataObject out of the information using some regex / string operations.
SELECT
c.`TABLE_NAME`,
c.`COLUMN_NAME`,
c.`COLUMN_COMMENT`,
t.`TABLE_COMMENT`
FROM
information_schema.columns c left join
information_schema.TABLES t ON
c.TABLE_NAME = t.TABLE_NAME and
c.TABLE_SCHEMA = t.TABLE_SCHEMA
where
c.`table_schema` = 'MyDatabase'
After parsing the information and providing the required Meta-Data-Objects, My header output just looks like this:
<?=$db->getColumnMetdata('contractNumber')->getHeader($_SESSION["user_language"]));?>
Code in between can vary in complexity. My ColumnMetadata also contains other information like required, searchable, length, possible foreign keys, and much more. That part would be up to you - just for localize headers, an associative Array would work as well. something like :
["de"] => {
"table1.contractNumber" => "Vertragsnummer"
"table1.Id" => "Id"
}
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'm working on a web application using MySQL and PHP 5.3.8. We have a mechanism to translate a simplified query instruction into a complete query string, including joins.
Since I cannot know what (normalized) tables there will be joined and what their fields are called, there may be duplicate field names. When executing PDOStatement::fetch(PDO::FETCH_ASSOC), I get an associated array of field names:
$test = $this->DBConnection->prepare("SELECT `events`.`Title`, `persons`.`Title` FROM `events` JOIN `persons` ON `events`.`HostID` = `persons`.`ID`;");
$test->execute();
$test->fetch();
But I have no way of distinguishing repeating field names, such as "title". Worse, duplicates overwrite each other:
array('Title' => 'Frodo Baggins');
In the bad old days, I ran mysql_fetch_field() on each field to get the table for each field. Please, tell me there is a better way than prefixing the fields (SELECT events.Title AS eventsTitle;).
Your help is greatly appreciated!
Give them aliases in the query so they won't be duplicates:
SELECT events.Title AS eTitle, persons.Title AS pTitle FROM ...
Then the row will be:
array('eTitle' => 'Hobbit Meeting', 'pTitle' => 'Frodo Baggins');
The alternative is to fetch the result as an indexed array rather than associative:
$test->fetch(PDO::FETCH_NUM);
Then you'll get:
array('Hobbit Meeting', 'Frodo Baggins');
and you can access them as $row[0] and $row[1].
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.
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.