PHP MySQL

Making connection to database

<?php
$con=mysql_connect(“server”,”username”,”password”);
if(!con)
    {
        die(‘Could not connect: ‘. mysql_error());
    }
mysql_select_db(“database_name”, $con);
?>

Displaying record from table

<?php
$query=mysql_query(“SELECT * from tablename”);
while($row=mysql_fetch_array($query))
    {
    echo $row[‘field_name_1’];
    echo $row[‘field_name_2’];
    }
mysql_close($con);
?>

Inserting record into table

<!–php script & HTML form in one page: file name: filename.php–>

<?php
if(isset($_GET[‘action’])&&$_GET[‘action’]==”add”)
    {
        $field_name_1=$_POST[‘field_name_1’];
        mysql_query(“Insert into table_name (field_name_1) values(‘$field_name_1’)”) or die(mysql_error());
    }
?>

<!–HTML form –>
<html>
<body>
    <form  name=”form_name” method=”post”  action=”filename.php?action=add”>
        field_name_1 <input type=”text” name=”field_name_1″ />
        <input name=”submit” type=”submit” value=”submit”>
    </form>
</html>
</body>

Listing fields from tables in HTML form drop down

<form  name=”add_task” method=”post”  action=”add_categories.php?action=add”>
  Categories
  <select name=”categories”>
    <?php
        $query=mysql_query(“SELECT * from tb_categories”);
        while($row=mysql_fetch_array($query))
        {  ?>
    <option value=”<?php echo $row[‘category_id’]; ?>”><?php echo $row[‘category_name’]; ?></option>
    <?php } ?>
  </select>
  <input name=”submit” type=”submit” value=”submit”>
</form>
Note: Change category_id to category_name if you want to pass name instead of id.
MYSQL PHP tutorials