Jump to content

Insert Data From a Form Into a Database - not working???


wblati

Recommended Posts

I have a piece of code that creates the database named stu_db and a table named student with the fields name, idNumber and mark.

 

Ive already got a form to retrieve the data but when i try to put the code below it wont put the data into the database.

 

any advice?

 

CODE TO SEND THE DATA TO THE DATABASE:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>

 

THIIS IS THE CODE WITH THE FORM AND CREATE DATABASE:

<html>
<head>
   
   <style type=text/css>
input.blue {background-color: #0066FF; font-weight: bold; font-size: 12px; color: white;}
input.violet {background-color: #ccccff; font-size: 14px;}
textarea.violet {background-color: #ccccff; font-size: 14px;}
option.red {background-color: #cc0000; font-weight: bold; font-size: 14px; color: white;}
option.pink {background-color: #ffcccc;}
.style2 {	color: #990000;
font-weight: bold;
font-size: 36px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.style5 {font-family: Arial, Helvetica, sans-serif; font-weight: bold; }
body {
background-color: #FFFFCC;
}
   </style>
   
      <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>
  ONLINE MOVIE BOOKING
</title>
      <Style>
        BODY, P,TD{ font-family: Arial,Verdana,Helvetica, sans-serif; font-size: 10pt }
        A{font-family: Arial,Verdana,Helvetica, sans-serif;}
        B {	font-family : Arial, Helvetica, sans-serif;	font-size : 12px;	font-weight : bold;}
        .style2 {color: #990000;
font-weight: bold;
font-size: 36px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
      </Style>
      </script>
</head>
<body>
<TABLE BORDER=0 align="center" CELLPADDING=5 CELLSPACING=5>
  <TR BGCOLOR="#E0E0E0">
    <TH BGCOLOR="#FFFF80"><A HREF="index.html">HOME</A></TH>
    <TH><A HREF="showall.php">SHOW ALL </A></TH>
    <TH><A HREF="selstu.html">SELECT STUDENT </A></TH>
    <TH><A HREF="addStudent.php">ADD STUDENT </A></TH>
    <TH><A HREF="delstu.html">DELETE STUDENT </A></TH>
    <TH><A HREF="showdeleted.php">SHOW DELETED </A></TH>
    <TH><A HREF="about.html">ABOUT</A></TH>
  </TR>
</TABLE>
<h2 align="center"> </h2>
<h2 align="center"><span class="style2">ADD STUDENT TO DATABASE </span><img src="http://www.sastt.ca/images/student.gif" alt="http://www.sastt.ca/images/student.gif" width="258" height="153"></h2>
<div align="center">
  <table width="470" border="1">
    <tr>
      <td colspan='2' align='center'><div align="left">	  
  
<?php
$con = mysql_connect("localhost","root","20247640");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// Create database
if (mysql_query("CREATE DATABASE stu_db",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }

// Create table
mysql_select_db("stu_db", $con);
$sql = "CREATE TABLE student
(
name varchar(30),
idNumber int( NOT NULL,
mark int
)";

// Execute query
mysql_query($sql,$con);

mysql_close($con);
?>

<?PHP 
// VALIDATIONS TAKEN FROM php file formValidator.php (http://www.phpbuilder.com/columns/weiner20050831.php3?page=2)

// OTHERS CODES TAKEN FROM http://www.php-mysql-tutorial.com/form-validation-with-php.php
// http://www.lotsofcode.com/php/validation.htm
// http://www.phpbuilder.com/board/showthread.php?t=10352170

require_once "formvalidator.php";
$show_form=true;

class MyValidator extends CustomValidator
{
function DoValidate(&$formars,&$error_hash)
{
        if(stristr($formars['Comments'],'http://'))
        {
            $error_hash['Comments']="No URLs allowed in comments";
            return false;
        }
	return true;
}
}

if(isset($_POST['Submit']))
{
    $validator = new FormValidator();

// TAKEN FROM http://www.html-form-guide.com/php-form/php-form-validation.html

// VALIDATION FOR NAME -------------------------------------------------------------------- 
    $validator->addValidation("NAME","req","Please enter a name");
$validator->addValidation("NAME","alpha_s","Please enter only letters");

// VALIDATION FOR ID NUMBER -------------------------------------------------------------
$validator->addValidation("ID_NUMBER","req","Please enter a student number");
$validator->addValidation("ID_NUMBER","numeric","Please enter only numbers");
$validator->addValidation("ID_NUMBER","minlen=8","Please enter 8 numbers");
$validator->addValidation("ID_NUMBER","maxlen=8","Please enter 8 numbers");

// VALIDATION FOR ID NUMBER -------------------------------------------------------------
$validator->addValidation("MARK","req","Please enter a mark/grade");
$validator->addValidation("MARK","numeric","Please enter only numbers");

    $custom_validator = new MyValidator();
    $validator->AddCustomValidator($custom_validator);

    if($validator->ValidateForm())
    {
        echo "<h2>THANK YOU - THE STUDENT HAS BEEN ADDED</h2>" ; 

        $show_form=false;
    }
    else
    {
        echo "<B>--- PLEASE CORRECT THE FOLLOWING ERRORS TO SUCCESSFULLY ADD A STUDENT</B>";

        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
            echo "<p>$inpname : $inp_err</p>\n";
        }        
    }
}

if(true == $show_form)
{
?>
      </div></td>
    </tr>
  </table>
</div>
  <form action="addStudent.php" method="post">
  <div align="center">
<p> </p>
<p><strong>PLEASE ENTER THE FOLLOWING STUDENT DETAILS</strong></p>
<table width="468" border="1">
            <tr>
              <td><span class="style5">NAME: </span></td>
               <td class='element_label'>
                  <input class="violet" type="text" name="NAME" size="30" value="<?php echo $_POST['NAME'] ?>" />			   </td>
      </tr>

		    <tr>
      <td><span class="style5">ID NUMBER: </span></td>
      <td><input class="violet" name="ID_NUMBER" type='number' size='9' value="<?php echo $_POST['ID_NUMBER'] ?>" /></td>
    </tr>	
<tr>
      <td><span class="style5">MARK: </span></td>
      <td><input class="violet" name="MARK" type='number' size='3' value="<?php echo $_POST['MARK'] ?>" /></td>
    </tr>	
            <tr>
              <td colspan='2' align='center'>
                <div align="right">
                  <input class="blue" type='submit' name='Submit' value='ADD STUDENT'>  
                </div>
                <p align="right">
      			 <input class="blue" name="Submit2" type="reset" value="CLEAR ALL FIELDS" />
   			</p>			  </td>
      		</tr>
</table>        
	</td>
</tr>
</table>
  </div>
</form>
<?PHP
}//true == $show_form
?>
</body>
<html>

Link to comment
Share on other sites

Shouldn't you be inserting NAME, ID_NUMBER, and MARK from these fields:

 

            

 

AND NOT:

 

('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

 

I don't even see these input fields anywhere...

Link to comment
Share on other sites

sorry, i didn't have the time to change the code i copied. i did try and type the name of the tables in the database and not the form fields. ill see if this works.

 

do i put this code below the create database php code??? like this?

 

<?php
$con = mysql_connect("localhost","root","20247640");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// Create database
if (mysql_query("CREATE DATABASE stu_db",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }

// Create table
mysql_select_db("stu_db", $con);
$sql = "CREATE TABLE student
(
name varchar(30),
idNumber int( NOT NULL,
mark int
)";

// Execute query
mysql_query($sql,$con);

mysql_close($con);


mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>

Link to comment
Share on other sites

I'm confused, your form tells me that you want to insert Student data, not Person data.  Here is your table structure that YOU created (and assume you want to use):

 

$sql = "CREATE TABLE student
(
name varchar(30),
idNumber int( NOT NULL,
mark int
)";

 

So your query has the wrong names (I have no clue where the table Persons came from, along with its fields  ???).

 

The INSERT query should be this:

 

$sql="INSERT INTO student (name, idNumber, mark)
VALUES
('{$_POST['NAME']}','{$_POST['ID_NUMBER']}','{$_POST['MARK']}')";

Link to comment
Share on other sites

im still getting that error - Error: Incorrect integer value: '' for column 'idNumber' at row 1

 

<?php
$con = mysql_connect("localhost","root","20247640");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// Create database
if (mysql_query("CREATE DATABASE stu_db",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }

// Create table
mysql_select_db("stu_db", $con);
$sql = "CREATE TABLE student
(
name varchar(30),
idNumber int( NOT NULL,
mark int
)";

mysql_select_db("stu_db", $con);

[b]$sql="INSERT INTO student (name, idNumber, mark)
VALUES
('{$_POST['NAME']}','{$_POST['ID_NUMBER']}','{$_POST['MARK']}')";[/b]

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 RECORD ADDED";

// Execute query
mysql_query($sql,$con);

mysql_close($con);
?>

Link to comment
Share on other sites

$sql="INSERT INTO student (name, idNumber, mark)
VALUES
('{$_POST['NAME']}','{$_POST['ID_NUMBER']}','{$_POST['MARK']}')";

echo $sql; // add this line and post it

 

The error is saying that the $_POST['ID_NUMBER'] is blank, not sure why...

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.