SQL insert into database using PHP - php

Hey guys I'm just practising inserting data into my database for the first time and i've got a few issues with my code.
So what my code does is that it takes information from a form and simply inserts it into the database I have connected to. I'm getting 2 types errors, one is an undefined index at my POSTS and I'm also getting a SQL syntax error. I've tried looking around with no such luck in helping me fix the problem.
(yea I forgot to add the messages when I posted) Edit:
Undefined index: customerid on line 57
Problem with queryYou have an error in your SQL syntax; '', '', '', '', '', '')' at line 2
Any advice would be helpful:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Form</title>
</head>
<body>
<h1>Customer Information Collection <br /></h1>
<form method="post" action="task12.php" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11/></td>
</tr>
<tr>
<td><label for="customerfname">Customer First Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50/></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50/></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
</tr>
<tr>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td> State: </td>
<td> <select name="state" id="state">
<option value="--">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
</tr>
<tr>
<td><label for="postcode"> Post Code (default "2000"): </label></td>
<td><input type="text" id="postcode" name="postcode" value="2000" size=4/></td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
<td> <input type="reset" value="Clear" /> </td>
</tr>
</table>
</form>
<?php
$customeridstr = $_POST['customerid'];
$customerfnamestr = $_POST['customerfname'];
$customerlnamestr = $_POST['customerlname'];
$customeraddressstr = $_POST['customeraddress'];
$suburbstr = $_POST['suburb'];
$statestr = $_POST['state'];
$postcodestr = $_POST['postcode'];
?>
<?php
$conn = mysql_connect("xxxxx", "xxxxx", "xxxxxx");
mysql_select_db("xxxxxxx", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "INSERT INTO Customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ( '$customeridstr', '$customerfnamestr’, '$customerlnamestr', '$customeraddressstr', '$suburbstr', '$statestr', '$postcodestr');";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>
</body>
</html>

<?php
if(isset($_POST['customerid'])){
$customeridstr = $_POST['customerid'];
$customerfnamestr = $_POST['customerfname'];
$customerlnamestr = $_POST['customerlname'];
$customeraddressstr = $_POST['customeraddress'];
$suburbstr = $_POST['suburb'];
$statestr = $_POST['state'];
$postcodestr = $_POST['postcode'];
$conn = mysql_connect("xxxxx", "xxxxx", "xxxxxx");
mysql_select_db("xxxxxxx", $conn) or die ('Database not found ' . mysql_error() );
$sql = "INSERT INTO Customer (customerID, firstName, lastName, Address, suburb, state, postcode) VALUES ( '{$customeridstr}', '{$customerfnamestr}’, '{$customerlnamestr}', '{$customeraddressstr}', '{$suburbstr}', '{$statestr}', '{$postcodestr}');";
$rs = mysql_query($sql, $conn);
if($rs){
echo 'Records Inserted';
}else{
die ('Problem with query' . mysql_error());
}
}else{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Form</title>
</head>
<body>
<h1>Customer Information Collection <br /></h1>
<form method="post" action="" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11/></td>
</tr>
<tr>
<td><label for="customerfname">Customer First Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50/></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50/></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
</tr>
<tr>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td> State: </td>
<td> <select name="state" id="state">
<option value="--">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
</tr>
<tr>
<td><label for="postcode"> Post Code (default "2000"): </label></td>
<td><input type="text" id="postcode" name="postcode" value="2000" size=4/></td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
<td> <input type="reset" value="Clear" /> </td>
</tr>
</table>
</form>
</body>
</html>
<?php
}
?>
For now, try the above solution, this should work.
For further learning try these things:
Using mysqli instead my mysql library, it is deprecated now. try sanitizing the data (data you are getting from $_POST or $_GET).
Set a separate file for database connection and include it where it is needed but only one time in one php script/page.
Its also not a good practice to post the values on the same page, post it on some other page which is just dealing with the submitted data.
Also we just check one variable that is it set or not, and also that doesn't verifies that is it empty or not, so try checking every required variable and condition you want to check.
Cheers :)

Related

Check if record exists and autofill the id from mysql table

When user fills the form, if LinkedIn Id already exists, it should throw an error saying LinkedIn Id already exists..
Form is not saving data if user does not enter ContactID. ContactID is an auto-increment field in MySQL table. Since more than one user works on the same form at the same time, I want ContactID to be auto-filled by the next available number from MySQL table.
Here, is my HTML form code and following, the PHP code. If you require any other details to debug, please ask.
<html>
<body>
<form method="post" action="demo.php">
<link rel="stylesheet" href="contact_css.css">
<!--Create a table -->
<table>
<tr><td><b>Contact Information</b></td>
</tr>
<tr>
<div class="leftside">
<td>ContactID</td>
<td><input type="text" name="ContactID"></td>
</div>
<div class="rightside">
<td>ContactOwner</td>
<!-- <td><input type="text" name="ContactOwner"></td>-->
<td><select name="ContactOwner">
<option value="None">None</option>
<option value="Malik">Malik</option>
<option value="Ankit">Ankit</option>
<option value="Vikrant">Vikrant</option>
</select></td>
</div>
</tr>
<tr>
<div class="rightside">
<td>LeadSource</td>
<td><select name="LeadSource">
<option value="None">None</option>
<option value="Advertisement">Advertisement</option>
<option value="ColdCall">ColdCall</option>
<option value="LinkedIn">LinkedIn</option>
<option value="Web">Web</option>
</select></td>
<!--<td><input type="text" name="LeadSource"></td>-->
</div>
<div class="leftside">
<td>First_name</td>
<td><input type="text" name="First_name"></td>
</div>
</tr>
<tr>
<div class="rightside">
<td>Last_name</td>
<td><input type="text" name="Last_name"></td>
<td>AccountName</td>
<td><input type="text" name="AccountName"></td>
</tr>
<tr>
<td>Title</td>
<td><input type="text" name="Title"></td>
<td>EmailID</td>
<td><input type="text" name="EmailID"></td>
</tr>
<tr>
<td>Industry</td>
<td><input type="text" name="Industry"></td>
<td>Department</td>
<td><input type="text" name="Department"></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="Phone" required></td>
<td>Mobile</td>
<td><input type="text" name="Mobile"></td>
</tr>
<tr>
<td>Today_date</td>
<td><input type="date" name="Today_date"></td>
<td>LinkedIn</td>
<td><input type="text" name="LinkedIn"></td>
</tr>
<tr>
<td>CallStatus</td>
<td><select name="CallStatus">
<option value="None">None</option>
<option value="AnsweringMachine">AnsweringMachine</option>
<option value="Callback">Callback</option>
<option value="NotInterested">NotInterested</option>
<option value="Prospect">Prospect</option>
<option value="WrongContact">WrongContact</option>
<option value="PerformedInternally">PerformedInternally</option>
<option value="LessThan30Employee">LessThan30Employee</option>
</select></td>
<td>Website</td>
<td><input type="text" name="Website"></td>
</tr>
</table>
<!-- Second table-->
<table>
<tr><td><b>Address Information</b></td>
</tr>
<tr>
<div class="leftside">
<td>Street</td>
<td><input type="text" name="Street"></td>
</div>
<div class="rightside">
<td>OtherStreet</td>
<td><input type="text" name="OtherStreet"></td>
</div>
</tr>
<tr>
<div class="leftside">
<td>City</td>
<td><input type="text" name="City"></td>
</div>
<div class="rightside">
<td>State</td>
<td><input type="text" name="State"></td>
</div>
</tr>
<tr>
<td>Zip</td>
<td><input type="text" name="Zip"></td>
<td>Country</td>
<td><input type="text" name="Country"></td>
</tr>
</table>
<!--Third table-->
<table>
<tr><td><b>Description Information</b></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="Description" class="Description"></td>
</table>
<button type="button">Cancel</button>
<button type="button" class="button2" onclick="window.location.href='fetch_data.php'" />View</button>
<button type="button" class="button3" onclick="window.location.href='exm_list.php'" />Edit</button>
<button type="submit">Add</button>
</form>
< /body>
</html>
PHP Code:
<?php
// create a variable
if (isset($_POST)){
$ContactID=$_POST['ContactID'];
$ContactOwner=$_POST['ContactOwner'];
$LeadSource=$_POST['LeadSource'];
$First_name=$_POST['First_name'];
$Last_name=$_POST['Last_name'];
$AccountName=$_POST['AccountName'];
$Title=$_POST['Title'];
$EmailID=$_POST['EmailID'];
$Industry=$_POST['Industry'];
$Department=$_POST['Department'];
$Phone=$_POST['Phone'];
$Mobile=$_POST['Mobile'];
$Today_date=$_POST['Today_date'];
$LinkedIn=$_POST['LinkedIn'];
$CallStatus=$_POST['CallStatus'];
$Website=$_POST['Website'];
$Street=$_POST['Street'];
$OtherStreet=$_POST['OtherStreet'];
$City=$_POST['City'];
$State=$_POST['State'];
$Zip=$_POST['Zip'];
$Country=$_POST['Country'];
$Description=$_POST['Description'];
}
//create connection
$connect=mysqli_connect('localhost','root','','contacts');
$check="SELECT COUNT(*) FROM contact where ContactID='$_POST[ContactID]' ";
$result=mysqli_query($connect,$check);
$data=mysqli_fetch_array($result, MYSQLI_NUM);
if($data[0] > 1){
echo "LinkedIn id already exists";
}
else {
$newUser="INSERT INTO contact(ContactID,ContactOwner,LeadSource,First_name,Last_name,AccountName,Title,EmailID,Industry,Department,Phone,Today_date,LinkedIn,CallStatus,Website,Street,OtherStreet,City,State,Zip,Country,Description)
VALUES('$ContactID','$ContactOwner','$LeadSource','$First_name','$Last_name','$AccountName','$Title','$EmailID','$Industry','$Department','$Phone','$Today_date','$LinkedIn','$CallStatus','$Website','$Street','$OtherStreet','$City','$State','$Zip','$Country','$Description')";
if (mysqli_query($connect,$newUser))
{
echo "Information Added<br/>";
}
else
{
echo "Error adding user in database, ContactID exists.<br/>";
}
}
Try changing:
$check="SELECT COUNT(*) FROM contact where ContactID='$_POST[ContactID]' ";
to
$check="SELECT COUNT(*) FROM contact where ContactID='$ContactID' ";
Also:
Form is not saving data if user do not enters ContactID. *** ContactID
is an autoincrement field in mysql table.
In your insert do not include
ContactID,
since this is an autoincrement field as you mention. What you should do instead is to do this:
//create connection
$connect=mysqli_connect('localhost','root','','contacts');
$check="SELECT COUNT(*) FROM contact where ContactID='$ContactID' ";
$result=mysqli_query($connect,$check);
$data=mysqli_fetch_array($result, MYSQLI_NUM);
if($data[0] > 1){
echo "LinkedIn id already exists";
}else {
$newUser="INSERT INTO contact(ContactOwner,LeadSource,First_name,Last_name,AccountName,Title,EmailID,Industry,Department,Phone,Today_date,LinkedIn,CallStatus,Website,Street,OtherStreet,City,State,Zip,Country,Description)
VALUES('$ContactOwner','$LeadSource','$First_name','$Last_name','$AccountName','$Title','$EmailID','$Industry','$Department','$Phone','$Today_date','$LinkedIn','$CallStatus','$Website','$Street','$OtherStreet','$City','$State','$Zip','$Country','$Description')";
if (mysqli_query($connect,$newUser))
{
echo "Information Added<br/>";
}
}

PHP/SQL syntax Error at line 1

The error I'm having related to the drop-down list:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near '','100',' Progress ')' at line 1
<?php
session_start();
/* Database connection settings */
$host = '';
$user = '';
$pass = '';
$db = '';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Passport = $_POST['Passport'];
$TeachersName = $_POST['TeachersName'];
$Date = $_POST['Date'];
$CourseType = $_POST['CourseType'];
$CourseCode = $_POST['CourseCode'];
$Grammar = $_POST['Grammar'];
$Reading = $_POST['Reading'];
$Writing = $_POST['Writing'];
$Listening = $_POST['Listening'];
$Speaking = $_POST['Speaking'];
$TeachersAssessment = $_POST['TeachersAssessment'];
$Totalz = $_POST['Totalz'];
$Overallz = $_POST['Overallz'];
$Progress = $_POST['Progress'];
}
$Results = $Grammar + $Reading + $Writing + $Listening + $Speaking + $TeachersAssessment;
$Overall = $Results /130*100;
if(isset($_POST['SubmitForm']))
{
$checkBoxz= implode(",",$_POST['Progress']);
$query="INSERT INTO examresults (FirstName, LastName, Passport, TeachersName, Date, CourseType, CourseCode, Grammar, Reading, Writing, Listening, Speaking, TeachersAssessment, Totalz, Overallz, Progress) VALUES ('$FirstName','$LastName','$Passport','$TeachersName','$Date','$CourseType','$CourseCode','$Grammar','$Reading','$Writing','$Listening','$Speaking','$TeachersAssessment',$Totalz','$Overallz','". $checkBoxz ."')";
mysqli_query($mysqli,$query) or die($mysqli->error);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Exam Cover Sheet</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
</head>
<body>
<form name="form1" method="post" action="cal.php">
<p>
<label for="textfield"></label>
</p>
<table width="63%" border="0">
<tr>
<td width="19%"><strong>First Name:</strong></td>
<td width="31%"><label for="textfield9"></label>
<input type="text" name="FirstName" id="textfield9" value="<?= isset($_POST['FirstName']) ? htmlspecialchars($_POST['FirstName']) : '' ?>"/></td>
<td width="50%"> </td>
</tr>
<tr>
<td><strong>Last Name:</strong></td>
<td><input type="text" name="LastName" id="textfield10" value="<?= isset($_POST['LastName']) ? htmlspecialchars($_POST['LastName']) : '' ?>"/></td>
<td> </td>
</tr>
<tr>
<td><strong>Passport No.:</strong></td>
<td><input type="text" name="Passport" id="textfield11" value="<?= isset($_POST['Passport']) ? htmlspecialchars($_POST['Passport']) : '' ?>"/></td>
<td> </td>
</tr>
<tr>
<td><strong>Teacher's Name:</strong></td>
<td><input type="text" name="TeachersName" id="textfield13" value="<?= isset($_POST['TeachersName']) ? htmlspecialchars($_POST['TeachersName']) : '' ?>"/></td>
<td> </td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td><input type="text" name="Date" id="datepicker" value="<?= isset($_POST['Date']) ? htmlspecialchars($_POST['Date']) : '' ?>"/></td>
<td> </td>
</tr>
<tr>
<td><strong>Course Type:</strong></td>
<td><label for="select"></label>
<select name="CourseType" id="select">
<option value="Elementary 1">Elementary 1</option>
<option value="Elementary 2" >Elementary 2</option>
<option value="Elementary 3" >Elementary 3</option>
<option value="Intermediate 1" >Intermediate 1</option>
<option value="Intermediate 2" >Intermediate 2</option>
<option value="Intermediate 3" >Intermediate 3</option>
<option value="Pre-Intermediate 1">Pre-Intermediate 1</option>
<option value="Pre-Intermediate 2" >Pre-Intermediate 2</option>
<option value="Pre-Intermediate 3" >Pre-Intermediate 3</option>
</select></td>
<td> </td>
</tr>
<tr>
<td><strong>Course Code:</strong></td>
<td><label for="select2"></label>
<select name="CourseCode" id="select2">
<option value="Elementary 1">EL1</option>
<option value="Elementary 2" >EL2</option>
<option value="Elementary 3" >EL3</option>
<option value="Intermediate 1" >I1</option>
<option value="Intermediate 2" >I2</option>
<option value="Intermediate 3" >I3</option>
<option value="Pre-Intermediate 1">PI1</option>
<option value="Pre-Intermediate 2" >PI2</option>
<option value="Pre-Intermediate 3" >PI3</option>
</select></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td width="19%"><p><strong>Grammar:</strong></td>
<td width="31%"><p><input type="text" name="Grammar" id="textfield" value="<?= isset($_POST['Grammar']) ? htmlspecialchars($_POST['Grammar']) : '' ?>">
<strong>/35</strong></p></td>
<td width="50%"> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><strong>Reading:</strong></td>
<td><p><input type="text" name="Reading" id="textfield2" value="<?= isset($_POST['Reading']) ? htmlspecialchars($_POST['Reading']) : '' ?>">
<strong>/20</strong></p></td>
<td> </td>
</tr>
<tr>
<td><strong>Writing:</strong></td>
<td><p><input type="text" name="Writing" id="textfield3" value="<?= isset($_POST['Writing']) ? htmlspecialchars($_POST['Writing']) : '' ?>">
<strong>/20</strong></p></td>
<td> </td>
</tr>
<tr>
<td><strong>Listening:</strong></td>
<td><p><input type="text" name="Listening" id="textfield4" value="<?= isset($_POST['Listening']) ? htmlspecialchars($_POST['Listening']) : '' ?>">
<strong>/20</strong></p></td>
<td> </td>
</tr>
<tr>
<td><strong>Speaking:</strong></td>
<td><p><input type="text" name="Speaking" id="textfield5" value="<?= isset($_POST['Speaking']) ? htmlspecialchars($_POST['Speaking']) : '' ?>">
<strong>/20</strong></p></td>
<td> </td>
</tr>
<tr>
<td><strong>Teacher`s assessment:</strong></td>
<td><p><input type="text" name="TeachersAssessment" id="textfield6" value="<?= isset($_POST['TeachersAssessment']) ? htmlspecialchars($_POST['TeachersAssessment']) : '' ?>">
<strong>/15</strong></p></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td></td>
<td><input type="text" name="Totalz" id="textfield7" value="<?php echo "$Results" ?>">
<strong>/130</strong></td>
<td><input type="text" name="Overallz" id="textfield8" value="<?php echo "$Overall" ?>">
<strong>%</strong></td>
</tr>
<tr>
<td><input type="submit" name="Result" id="Result" value="Calculate"></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><strong>Teacher’s recommendation:</strong></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="Progress[]" value="Repeat" id="CheckboxGroup1_0">
Repeat</label>
<br></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="Progress[]" value="Progress" id="CheckboxGroup1_1">
Progress</label>
<br></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<p>
<input type="submit" name="SubmitForm" id="SubmitForm" value="Insert Records">
</p>
</form>
</body>
</html>
An error message is showing the the query part exactly after the error spot.
So if you look at your query in this place you will see the missed quote
,$Totalz','$Overallz','". $checkBoxz ."'
To prevent any possibility of introducing such an error (let alone protection from SQL injection to which your code is severely prone), you have to use prepared statements for your queries. For which purpose PDO is much more useful than mysqli.

Selection of two choices Show error

I have a form in php to select 3 choices , when i select all three no error is shown, but when i select two choices it shows error but choice is saved in data base, and shows record saved, but also show Notice: Undefined index: hb3 in C:\wamp\www\uni1\admin\courses.php on line 14
07/25/2014
<?php
include('auth.php');
include('conect.php'); $msg='';
if(isset($_POST['save']))
{
$category = $_POST['category'];
$cname = $_POST['cname'];
$code = $_POST['code'];
$type = $_POST['type'];
$dur = $_POST['dur'];
$fee = $_POST['fee'];
$hb1 = $_POST['hb1'];
$hb2 = $_POST['hb2'];
$hb3 = $_POST['hb3'];
$catid =mysql_insert_id();
$sql = mysql_query("select * from category where catid='$category'");// to get category code from category table
$rs = mysql_fetch_array($sql);
mysql_query("INSERT INTO courses1 (catid,cname, code, type, dur, fee, hb1, hb2, hb3)
VALUES ('$category','$cname','$code','$type','$dur','$fee','$hb1','$hb2','$hb3')");
$msg = '<h3>Record Saved</h3>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>courses</title>
<link rel="stylesheet" type="text/css" href="headerstyle.css" />
</head>
<body>
07/25/2014
<div class="fixx"><?php include('header.php');?></div>
<div class="tabl">
<table width="700" border="0">
<tr>
<td>
<form method="post" action="courses.php">
<table width="700" border="1" cellpadding="10">
<tr>
<td colspan="2"><h3> ADD COURSES | EDIT </h3></td>
</tr>
<tr>
<td colspan="2"><?php echo $msg;?></td>
</tr>
<tr>
<td width="174"><h4>Select Category </h4></td>
<td width="674"><label for="category"></label>
<select name="category" id="category">
<?php $qre = mysql_query("select * from category ORDER BY name");
while($res = mysql_fetch_array($qre))
{
echo '<option value="'.$res['catid'].'">'.$res['name'].'</option>';
}
?>
</select> </td>
</tr>
<tr>
<td width="174"><h4>Enter Course Name</h4></td>
<td width="674"><label for="cname"></label>
<input name="cname" type="text" id="cname" size="70" /></td>
</tr>
<tr>
<td><h4>Course Code</h4></td>
<td><input type="text" name="code" id="code" /></td>
</tr>
<tr>
<td><h4>Type</h4></td>
<td><label for="type"></label>
<select name="type" id="type">
<option value="Month"><h4>Month</h4></option>
<option value="Semester"><h4>Semester</h4></option>
<option value="Year"><h4>Year</h4></option>
</select></td>
</tr>
<tr>
<td><h4>Duration</h4></td>
<td><p>
<select name="dur" id="dur">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</p></td>
</tr>
<tr>
<td><h4>Fee</h4></td>
<td><input type="text" name="fee" id="fee" /></td>
</tr>
<tr>
<td><h4>Mode</h4></td>
<td><h4>Online
<input type="checkbox" name="hb1" id="hb1" value="online" /></h4><br />
<h4>Private
<input type="checkbox" name="hb2" id="hb2" value="private" /></h4>
<br />
<h4>Regular
<input type="checkbox" name="hb3" id="hb3" value="regular" />
</h4> <br />
</label></td>
</tr>
<tr>
<td><input type="submit" name="save" id="save" value="Submit" /></td>
</tr></h2>
</table>
</form>
</td>
</tr>
</table>
</div>
</body>
</html>
Please solve my problem
There is error because when you are selecting only two choices then third choice has null means no value
$hb3 has no value for choice
you should check is value set or not if not then assign some default values
$hb1 = isset($_POST['hb1'])?$_POST['hb1']:'';
$hb2 = isset($_POST['hb2'])?$_POST['hb2']:'';
$hb3 = isset($_POST['hb3'])?$_POST['hb3']:'';
You should do like that if don't want notice "Undefined index"
$hb1 = isset($_POST['hb1'])?$_POST['hb1']:'';
$hb2 = isset($_POST['hb2'])?$_POST['hb2']:'';
$hb3 = isset($_POST['hb3'])?$_POST['hb3']:'';
use hidden filed
<input type="hidden" id="hb1_" name="hb1" value="-1">
<input type="checkbox" id="hb1" name="hb1" value="online" />
<input type="hidden" id="hb2_" name="hb2" value="-1">
<input type="checkbox" id="hb2" name="hb2" value="private" />
<input type="hidden" id="hb3_" name="hb3" value="-1">
<input type="checkbox" id="hb3" name="hb3" value="regular" />
When checkox in not checked, then $_POST doesn't contain given key, so you cannot assign its value. Whenever you use checkbox, assign given post value like this:
$hb3 = isset($_POST['hb3'])?$_POST['hb3']:'';
then in case of undefined value you will assign an empty string and you will not see those notices.

Why is my PHP is not inserting data into MySQL database? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this form to input data into a MySQL database. It's not giving me any errors, but also not inserting data. I have looked around the web, with no avail. I'm not sure if it's my code or maybe I've misconfigured my database. Here's all the code.
<!DOCTYPE html>
<html>
<head>
<title>Steam Traps Form</title>
<style type="text/css">
table tr > td { text-align: right; }
table tr > td + td { text-align: left; }
</style>
</head>
<body>
<form action="FormHandler.php" method="post" >
<table border="0">
<tr>
<td align="center"><h1>Steam Trap Form Input</h1></td>
</tr>
<tr>
<td>
<tr>
<td>Date of Survey</td>
<td><input type="date" name="dateSurvey">
</td>
<tr>
<tr>
<td>Plant Name</td>
<td><input type="text" name="plantName"></td>
</tr>
<tr>
<td>Plant Location</td>
<td><input type="text" name="plantLoc"></td>
</tr>
<tr>
<td>Plant Contact Name</td>
<td><input type="text" name="plantContact"></td>
</tr>
<tr>
<td>Direction</td>
<td><select name="direction">
<option value="N">N</option>
<option value="NE">NE</option>
<option value="NW">NW</option>
<option value="S">S</option>
<option value="SE">SE</option>
<option value="SW">SW</option>
<option value="E">E</option>
<option value="W">W</option>
</select>
</td>
</tr>
<tr>
<td>Location (detailed as possible)</td>
<td><input type="text" name="location" size="40">
</td>
</tr>
<tr>
<td>Floor Level</td>
<td><select name="flrLevel">
<option value="grd">Ground</option>
<option value="1st">1st</option>
<option value="2nd">2nd</option>
<option value="3rd">3rd</option>
<option value="4th">4th</option>
<option value="5th">5th</option>
<option value="6th">6th</option>
<option value="7th">7th</option>
<option value="8th">8th</option>
<option value="9th">9th</option>
<option value="10th">10th</option>
<option value="11th">11th</option>
<option value="12th">12th</option>
<option value="13th">13th</option>
<option value="14th">14th</option>
<option value="15th">15th</option>
</select>
</td>
</tr>
<tr>
<td>Elevation (in ft)</td>
<td><input type="number" name="elevation" size="5">
</td>
</tr
<tr>
<td>Tag Number</td>
<td><input type="text" name="tagNum" size="20">
</td>
</tr>
<tr>
<td>MFG Model Number</td>
<td><input type="text" name="mmn" size="30">
</td>
</tr>
<tr>
<td>Size</td>
<td><input type="text" name="size" size="10">
</td>
</tr>
<tr>
<td>Pressure</td>
<td><input type="number" name="pressure" size="5">
</td>
</tr>
<tr>
<td>Service</td>
<td><input type="text" name="service" size="5">
</td>
</tr>
<tr>
<td>Trap Conditions</td>
<td><select name="trapCond">
<option value="OK">OK</option>
<option value="BT">BT</option>
<option value="RCL">RCL</option>
<option value="CP">CP</option>
<option value="VO">VO</option>
</select>
</td>
</tr>
<tr>
<td align="right"><input type="submit"
name="submit" value="Submit"></td>
</tr>
</form>
</td>
</tr>
</table>
<br />
</body>
</html>
Here is the PHP
<?php
$dateSurvey = $_POST["dateSurvey"];
$plantName = $_POST["plantName"];
$plantLoc = $_POST["plantLoc"];
$plantContact = $_POST["plantContact"];
$direction = $_POST["direction"];
$location = $_POST["location"];
$flrLevel = $_POST["flrLevel"];
$elevation = $_POST["elevation"];
$tagNumb = $_POST["tagNum"];
$mmn = $_POST["mmn"];
$size = $_POST["size"];
$pressure = $_POST["pressure"];
$service = $_POST["service"];
$trapCond = $_POST["trapCond"];
$sql_connection = mysql_connect("localhost", "******", "******");
mysql_select_db("******", $sql_connection) or die( "Unable to select database");
$sql = "INSERT INTO steamtraps (
dateSurvey,
plantName,
plantLoc,
plantContact,
direction,
location,
flrLevel,
elevation,
tagNum,
mmn,
size,
pressure,
service,
trapCond,
ContactDateCreated,
)
VALUES (
'{$dateSurvey}',
'{$plantName}',
'{$plantLoc}',
'{$plantContact}',
'{$direction}',
'{$location}',
'{$flrLevel}',
'{$elevation}',
'{$tagNum}',
'{$mmn}',
'{$size}',
'{$pressure}',
'{$service}',
'{$trapond}',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
Try to change the mysql_query to show errors meaningfully:
mysql_query($sql, $sql_connection) or die(mysql_error() . "<br/>Query was: " . $sql);
If you have an error, it will stop execution and you will see both the error and the query that was attempted to be executed.
I'm not sure what version of PHP you are running, but mysql_query and other related commands have been deprecated since PHP-5.5.0. http://php.net/manual/en/function.mysql-query.php
Try using the newer mysqli_query (you will need to update all of your sql commands like mysqli_connect and mysqli_close to match).
http://php.net/manual/en/mysqli.query.php

MySQL:(PHP) UPDATE Query issue

I have an UPDATE Query in MySQL
UPDATE users
SET fname='$fname',lname='$lname',username='$user',password='$pass',role='$role',status=$status
where id=$id
It works perfectly when I run it in Phpmyadmin by giving values manually but it gives me an error message when I use it in PHP Page.
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
The error is generated because I am doing echo mysql_error() I am getting values from the FORM like this;
$id=$_POST['id'];
$fname=$_POST['txt_fname'];
$lname=$_POST['txt_lname'];
$user=$_POST['txt_user'];
$pass=$_POST['txt_pass'];
$role=$_POST['txt_role'];
$status=$_POST['status'];
Frankly I sound like a stupid asking such a simple question, but I am stuck and need a bit of help. Thanks
FORM HTML
<div id="cuntable" style=" width:400px; margin:0 auto;">
<div class="CSSTableGenerator">
<form name="userform" action="updateuser.php" method="post">
<table >
<tr>
<td colspan="2"> Edit / Modify User Details </td>
</tr>
<tr>
<td>First Name </td>
<td><input type="text" name="txt_fname" placeholder="<?php echo $row[1];?>" /></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="text" name="txt_lname" placeholder="<?php echo $row[2];?>" /></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="txt_user" placeholder="<?php echo $row[3];?>"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="txt_pass" placeholder="<?php echo $row[4];?>" /></td>
</tr>
<tr>
<td>Username</td>
<td>
<select name="txt_role">
<option value=""> Select User Role </option>
<option value="user"> User </option>
<option value="admin">Administrator</option>
<option value="operator">Operator</option>
<option value="accountant">Accountant </option>
</select>
</td>
</tr>
<tr>
<td> Status </td>
<td>
<select name="status">
<option value="1"> Active </option>
<option value="0"> Suspended </option>
</select>
</td>
</tr>
</table>
</div>
<br />
<input type="submit" value=" ADD USER " />
<input type="hidden" name="txt_id" value="<?php echo $row[0];?>"
</form>

Categories