How to generate mysql fields using php

Welcome to another quick tutorial.
In this tutorial I’m going to show you how to make a php program that can generate mysql fields.

To make this real quick, fire up wampserver and let’s get started!

Procedure

First you have to include your database configuration file on the file that you’re going to work with:

<?php
require_once('randomconfig.php');
?>

In case you don’t know, a database configuration file contains all the stuff needed to connect to your mysql database or any database that php supports. Go check out the basics at w3schools.com if you don’t have any idea what I’m talking about.

After that, go ahead and create the form that will serve as the interface where we are going to add our fields:

<form name="frm_fieldgen" action="genfield1.php" method="post">
    <label for="fieldname">Field:</label>
    <input type="text" id="fieldname" name="fieldname">
    <input type="submit" value="generate field">
</form>

Finally, let’s query the database to add another field into the table that we specified:

<?php
if(!empty($_POST)){

     $field = $_POST['fieldname'];
     $create_field = $db->query("ALTER TABLE tbl_roles ADD $field INT(1) NOT NULL");
}
?>

Of course, you can actually tweak the code above to make something like phpmyadmin. The popular database management application for wampserver users.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s