Sunday, 14 June 2009

Working with INSERT statement

After creating a database, now I have to insert all data into table attributes.

First of all, I create a page called test.php.
This page will contains a html form that will passes all variables to insert.php

Embedding a php connection page by code

include'include/conn.php';

Then I simply create form like the picture:



with a CSS file containing :

input
{
background-color: #99ccff;
color: black;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt
}
.button
{
background-color: blue;
font-family: verdana;
border: #000000 1px solid;
font-size: 12px;
color: aqua
}

Input to make a input cell colored with blue and black font. Beside that, a class will be name inside the input button code so that ".button" can change.

Final Step is to create insert.php file that gets the connection page and all variables from test.php

include'include/conn.php';

mysql_select_db('user',$db)or die(mysq_error($db));
$username = "$_POST[username]";
$pass = "$_POST[pass]";
$email = "$_POST[email]";
$fullname = "$_POST[fullname]";
$address1 = "$_POST[address1]";
$address2 = "$_POST[address2]";
$city = "$_POST[city]";
$country = "$_POST[country]";

$insert = 'INSERT INTO user(userName,password,email,fullName,address1,address2,city,country) VALUES ("$username", "$pass", "$email", "$fullname", "$address1", "$address2", "$city", "$country")';

$result = mysql_query($insert,$db)or die(mysql_error($db));
Then open and enclose html tag with table inside to view the result of insert function.

table width="100%"
tr
th>User ID < /th th>User NamePasswordFull NameAddressCityCountry
then input a script below inside open and enclose php tag

$display = 'SELECT * FROM user';

$reDisplay = mysql_query($display,$db)or die(mysql_error($db));

while ($row = mysql_fetch_assoc($reDisplay))
{
echo '';
foreach ($row as $value)
{
echo(''.$value.'');
}
echo '';
}
Finally, I preview the page to insert

test.php



and insert.php



The problem is that all variables are inserted into database 'user' instead of their data values.


I posted my question in a forum of hotrolaptrinh.com



and get a reply :



so the problem is double and single quote (" and ') that I confused in coding.

The code should be changed like:

$username = $_POST['username'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$fullname = $_POST['fullname'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$country = $_POST['country'];

$insert = "INSERT INTO
user(userName,password,email,fullName,address1,address2,city,country)
VALUES
(' ".$username." ',
' ".$pass." ',
' ".$email." ',
' ".$fullname." ',
' ".$address1." ',
' ".$address2." ',
' ".$city." ',
' ".$country." ')";

$result = mysql_query($insert,$db)or die(mysql_error($db));
Now I test the code and get the successful result:



All data are filled inside different table attributes.

No comments:

Post a Comment