As a part of a script I'm writing I would like to add a templating system where the variables are derived from a database table like this:
id int auto_increment primary key,
name varchar(200) not null,
value float(6,2) not null
My problems are:
1- I am not able to find a way that makes it user-friendly to display those variables when editing a page & I don't know how many variables there would be so I cannot add all-in-one form.
2- I don't know how the variable should be saved to the database (I'm looking to save a reference of the variable not its value so when it's updated on the table, all pages that uses it will have the new value) ... but using the variable number doesn't seem to be clear on what it holds when someone first looks into the page while editing.
3- Should I use something like preg_replace to replace those variables or is there a better method to do that?
If i understand your question correctly, you are seeking a way to extract column definitions from your database to build a web form regarding to the fields defined in a database table? if this is the case, you can obtain the structure easily with
SHOW COLUMNS
FROM database-table
Even better would be to use the information_schema database (available since MySQL 5.x), because you wont have to parse anything from it:
SELECT *
FROM information_schema.columns
WHERE table_name = "database-table"
Related
i am creating plugin in wordpress for contact us form and in that i am creating fields(textbox,textarea etc...) dynamically based on my requirement. so there is no fixed number of fields. i am storing dynamically created fields in my db table.
in some project i may require to create 3 fields and some project i may require to create 5 fields.. my dynamic form is working fine...
now my problem is DB. how do i create table to store contact us data? bcz sometimes there might be 3 fields and sometime there might be more than or less than 3 fields..
so my question is how do i make my table schema for this scenario...
suggestion will be highly appreciated...
Thanks in advnce
Change table structure is strongly not suggested, it's bad in performance, and may lost data if you drop a column.
So, the original subject 'make db table field dynamic' is possible but not a good plan, we still have alternative plan:
Store dynamic field in one table column
Find a way to combine your dynamic field to a string, either use a separator, or use json_encode works, if the column is long enough (TEXT --> MEDIUMTEXT), you can have unlimit dynamic field.
Create enough column at beginning
Apearently this not as good as upper plan, but it's easier to understand, and search in these column is easier too.
BTW, Have you considered convert these dynamic column to rows ?
You need to store the information taken from the form in one table field using an array. That way it should not matter how many question there are.
Should be quite simple take a look at php arrays.
You can have a single longtext datatype column in your database table and you just need to serialize your form values and store in the single column.
I agree with the others. Dynamically creating database tables is bad. The database schema should hardly ever change once a project is complete.
One solution is:
If you had a contact with multiple addresses, you create a parent/child relationship as follows. Perhaps you can do something similiar with your situation.
Contact
long contactID primary key
name
addressID
Address
long addressID primary key
long contactID foreign key
streetAddress
CityID
CountryID
i don't think so it's a good idea to do like this... but i am suggesting you this because in your case it might be useful
you can do it by ALTER...
so what you can do is "When you are creating new field dynamically at that time only you can create new column in your table like this...
ALTER TABLE table_name ADD $name(Column name) //$name may be your attribute name <input name="">
and same way when you are deleting your field at that time you can drop your table column
ALTER TABLE table_name DROP $name(Column name) //$name may be your attribute name
here i assumed that you have already created table table_name (without any fields)
hope it may help you
I have a mysql table looking like this:
id
some_field1
some_field2
variable_fields
datetime
...
Now I want to store more than 1 value in variable_fields like this:
user_id:5;message_id:10
The reason why I do not create a separate field for every value I want to store is that these values differ throughout the project. So I am storing different values along the project.
At some time variable_fields contains this value:
user_id:5;message_id:10
And at some other time it contains this value:
car_id:56;payment_id:45
This wouldn't be a big problem but I want to be able to search in this field. So something like: variable_fields LIKE '%payment_id:45%'.
This obviously takes time for mysql.. Is there another way of handling this instead of creating a field for every value? So some kind of dynamic field in mysql?
I happy for every kind of help. Thank you in advance!
Best regards,
Freddy
If you'll add a myisam full-text index or employ any other full-text tools on that column (e.g. sphinx, lucene) those searches you described will work much better, however that isn't advisable.
I would suggest either to divide the dynamic meta data into different tables per case, and keep a type_id in the main table, or keep columns for all options that are set to NULL by default. Really depends if there is a simple division or is this really dynamic and changing over time. In case you're diving the data into several tables, a JOIN according to type_id will give the ability to query by those specific fields values. Be sure to create an index in both tables on the mutual id.
I have a scenario in which I am not sure about what to do.
I have a website where a user can update their status. I am allowing the use of hash tags so a possible user post might look like:
Went for a great hike today!! #hiking
Now, I intend to store the post in a table appropriately named "POSTS" which is structured like this:
post_id | user_id | text | date
Now, when a user submits the form which holds the post text I run a script to create an array to get all of the hash tag terms the user used and then store them in an array.
So then I can loop through that array and insert the tags into the aptly named "TAGS" table. Now the structure of this table is this:
tag_id | post_id | user_id | tag
The only problem with this is that I do not know the post_id of the post until after I insert the data into the "POSTS" table (post_id is the primary key and is auto increment).
Now, I was thinking I could just SELECT the last row of data from the "POSTS" table for that user (after I insert the post), and then in turn use the returned post_id for my query that inserts the tag data into the "TAGS" table. This seems like not the best way? My question is:
Is this the best solution or is there a better way to go about this scenario?
I am brand new to Stack Overflow, so don't please down vote me. Comment and tell me what I am doing wrong and I will learn and ask better questions.
Thanks
You can get last insterted ID very simply:
mysql_insert_id() if you don't use PDO or using function lastInsertId() if you do.
Have a new column in both tables - unique_id - which holds a string you generate in code before querying the database. That way you have an id to tie posts and tags together before submission. I use this method all the time for similar applications.
Only issue is uniqueness, but there a variety of ways to generate unique ids (I normally use a mixture of timestamps and hashing).
This sort of depends on which version of mysql you're using and how you want to organize your code.
Option 1. Do exactly what you've said. PHP would contain the code to manage the database and how data is stored into the database. The only drawback that I see in what you've outlined is if there's an issue with dealing with the hashtags, then possibly you would have a post that is inserted to the database, but the hash part did not successfully complete. For certain applications (like a bank account), this may not be acceptable and this is what database transactions are for.
Option 2. Another way to handle this would be to write a mysql stored procedure that does both the insert and handling the hash tags. The stored procedure could also wrap the whole thing in a transaction so that your database is consistent. Note that this requires a version of mysql that supports stored procedures. The bad side of doing this is that you would have to write in mysql, which is different from PHP.
Both mysql and PHP can handle this application logic/datastore logic. It is a matter of how you want to organize the code. I would prefer keeping the layers distinct. Even if you are to do this in PHP, at least have a separate class that deals with the database and not do anything else. When your code gets bigger, having a separate class or module or namespace that manages these types of code really makes them easier to change and to test.
I have a problem how to store some data in mysql.
I have website which when link is pressed pass some data to php file which read this data with get and write in database(mysql). I'm passing campaign_id and unknown number of parameters.
http://domain.com/somefile.php?campaignid=1¶meter1=sometext1¶meter2=sometext2¶meter3=sometext3,....etc..
I don't know actual number of parameters because user make them in some sort of cms. The problem I'm facing is how to store them in database. I was thinking to make it like this below but i'm not sure if it's the right and the most effective way:
Combinations Table
-combination_id (Primary key and auto increment)
-campaign_id
-parameter1
-parameter2
-parameter3
-parameter4
-parameter5
-parameter6
-parameter7
-parameter8
-parameter9
-parameter10
In this example I assume that user will not add/use more than 10 parameters(which I think is lame, but I can't get better solution)
Also if I use this design I assume I need to check in this file where is get them from passing and write to database, if each parameter exist(if it was passed).
You have to normalize your schema.
Assume the following tables:
Entity: id, campaign_id, other fields.
Parameter: id, entityId, parameterValue.
This is a Many-to-One relation.
What About storing all the parameters as json in one table row?
You could try something like this:
combination_id (primary key auto increment)
campaign_id ( indexed / foreign key / can't be unique!)
param_name
param_value
You'd have to create an entry for every parameter you're getting, but you could theoretically add a thousand parameters or more.
Might not be the fastest method though and can be a bit hard to work with.
I think this is the kind of data nosql databases are made for... At least, trying to force it into a sql database always ends up as some kind of kludge. (been there done it...)
as far as I can see, you have three different ways of storing it:
As you proposed. Probably the easiest way to handle it and also probably the most efficient. But, at the moment you get 11 parameters you are in for major problems...
Make a parameter table - parameter_id, - campaign_id parameter (possible parameter name if it matters) - this gives you total flexibility - but everything else, ecept for searching for single values gets more difficult,
Combine the parameters and store them all in a text or varchar field. This is probably even more efficient than 1, except for searching for single parameter values.
And if I may add
Use a database system with an array type, eg postgresql
If you don't know the actual number of parameters that will come through url, there is a best option to store the infinite number of values for a campaign_id.
For that you can create multiple rows in the table. Like,
insert into table_name values(<campaign_id>,<parameter1>,<sometext>)
insert into table_name values(<campaign_id>,<parameter2>,<sometext>)
insert into table_name values(<campaign_id>,<parameter3>,<sometext>)
insert into table_name values(<campaign_id>,<parameter4>,<sometext>)
Assuming the campaign_id is unique in url.
What is the best way to create member profiles in PHP? For instance, some websites read in the address bar: profile.php?id=11233 and then profile.php?id=13563. How is this actually done? As of now, I am saving such types of URL's in MySQL, but where will I write the actual code? Will I have to write the code in profile.php? Or will I have to make separate files for each id? How does it work?
Will I have to write the code in
profile.php?
Yes. Visitors will be visiting profile.php and there will be a default variable set named $_GET['id'] that has the value in the URL, like 11233 or 13563. You can then query the database for the user with that id and display the proper information.
If there is more than one variable, like profile.php?id=123&type=cake, then you will have two variables: $_GET['id'] = 123, $_GET['type'] = 'cake'. It is stored in $_GET because GET is the method used to access the page. Find out more at http://php.net/get
There is also another common method, called POST. This is used when forms are submitted with method=POST. In that case, the information will be stored in the $_POST array.
Yes, in those example URLs, the database id is being sent as a parameter which would be parsed by PHP.
The basic steps would be
get database id (from what's called the $_GET superglobal in this case). Make sure it's an integer, using intval() or (int)
set up your database connection (I use PDO)
build a query, something like select * from profile where id=?.
execute the SQL query
check your results
if you have valid results, print out the information in the profile
The details of how to do each of those steps is the meat of the matter, of course. I'm sure folks around here would be more than happy to answer questions about how to connect to and set up a database, and use the results in PHP.
A simple example database would be set up something like
CREATE TABLE profile(
id int NOT NULL AUTO_INCREMENT,
user_name varchar(32),
bio varchar(1024),
favorite_flavor enum('chocolate','vanilla','fruity'),
image_id int default null,
primary key(id)
);