Wednesday, 18 November 2009

Simple insert into mysql from html form via php example

*** Disclaimer if you think the internet is there to do all the work for you, then this post is not for you, go and enjoy a chat with your neighbour  ***

Just been spending a bit more time learning php and on the future recipe section for my site. I wanted a clean and simple INSERT INTO example which I can use as a basis for future development.

In the php book I am reading I have tons of examples and on the web, there are tons of examples - but!! A lot of them have lots of other bits and pieces cluttering them up. In good time, as I learn more I am sure it will begin to make sense. But, I think a lot of people who write tutorials forget who they are writing for. Putitng in ISSET() might be second nature for yourself, but if you do not explain why you are putting it there, then it is just confusion.

Also, Yes sometimes the most simple solutions are not the right solution, but for someone learning, stripping back to the essentials can be most beneficial so they can see clearly what is going on. Remember making mistakes is one of the best ways of learning.

Anyway, end of rant and onto my insert.

I have a php file for adding recipes to my database. It currently looks something like this and is tentatively named add.php

require_once 'funcLists.php';

<form action="transRecipe.php" method="POST">

<h1>Add Recipes</h1>

<p>Recipe Title
  <input type="text" size=50 name="recipeTitle" maxlength="255"  value="">

<p>Recipe Type
  <?php listRecipesTypes(); ?>   
<p>Quick Description<br>
    <textarea name="recipeQuick" rows="6" cols="63"></textarea>

<p>Select Ingredients</p>
    <?php listIngredients() ?>   

<input type="submit" type="submit" value="Add Recipe">   


I also have a second php file called transRecipes.php , which contains my INSERT INTO code and that looks like this.


require_once '../conn.php';

        $sql = "INSERT INTO recipe (rType,title,quick)
        echo $sql;
         echo "<br><br>";
        if (!mysql_query($sql))
          die('Error: ' . mysql_error());
        echo "Here is my bottom";


And here is a list of the important condsiderations
  1. In the form action part , there is the reference to the transRecipe.php file , which you need for it to work
  2. The $POST[...] parts in transRecipe refer to the names of the input controls on the Add.php file
  3. The echo parts are there to help me debug and allow us to concentrate on getting the SQL right in the INSERT statement

No comments:

Post a Comment


Related Posts with Thumbnails