Back to Programming Articles

INSERT INTO database
by flup 02 May 2003

In this tuturial a lot of mySQL and PHP will become clear to you.
This tutorial was posted on http://www.webmeesteres.nl and is very good for the novice (like me, i started yesterday with it, and im now getting the clue of mySQL and PHP together)

___________________________________________________

Start:
In this articel, i'll explain how to add text into a database.
The articel is wroten for newbies, and I think you know how to create a table in a database, though, i'm still explaining that part a bit.

The Tutorial:
To put text in a database, first of al you need a database and a tabel, we assume you already have a database, so you have to create your tabel

SQL Query: (how to run queries)
CREATE TABLE table (
naam VARCHAR(35) NOT NULL, 
email VARCHAR(50) NOT NULL, 
titel VARCHAR(30) NOT NULL, 
info TEXT NOT NULL 
);

This table is called: table (woow, how did i get this ;P)
And the fields are called: naam, email, title, info (dutch)

Naam is a regular field to enter your name and may contain various characters (varchar) with 35 chars (35)
For email and titel is the same, but with info, it could be anything, this has been marked with TEXT, text hasn't got any preset length.
This code is easy to add in a database, just copy and paste the code in PHPmyAdmin

ok, second, we are going to make a form wich is called insertcode.php but that could be anything.

PHP Code:
<?php
Add text
<br>
<
form action="addcode.php" method="post">
Naam:<br><input type="text" name="naam" size="20" maxlength="20"><br>
E-mail:<br><input type="text" name="email" size="30"><br>
Titel:
<
input type="text" name="titel" size="30"><br>
Info:<br><textarea rows="7" name="info" cols="39">
</
textarea><br>
<
input type="submit" name="submit" value="Add"></form>
Ok, now you've got your table we are heading to the next part of this tutorial, because, with only a form you cant add anything.
PHP Code:
<?php

if($submit) {

mysql_connect("localhost","user","paswoord");
mysql_select_db("databasenaam");

$insert "INSERT INTO tabel (naam,email,titel,info) 
VALUES ('','
$naam','$email','$titel','$info')";
$query mysql_query($insert)or die(mysql_error());

?>
To explain this part, we've to talk a bit weird, but that explains best:

If: Add
Do: Connect Database, Add content of form to database

Just a notice:

Naam:
Code:
<input type="text" name="naam" size="20" maxlength="20">
In this piece of code, it says the name of naam is naam. The content of naam will be put in the table naam.
Is doesn't mather how your form is called, only that everything is put in the right table.
PHP Code:
$query mysql_query($insert)or die(mysql_error());

In this code, it makes a mysql_query, called $insert, if it can't doe this query it will report an error.

I hope you know now a bit of the working of mySQL
Good Luck

vblts.ru supports vBulletin®, 2022-2024