I need some help with this project. I've gone as far as I can go, with no results, The inquiry form works, but I need to populate it with my sql table. I could only screen shot my sql and I have no idea of how to put it on here. The following is the scenerio: Uploading Information Directly into the Inquiry Table
In this scenario I will be using the inquiry form that I created in one of my projects, and the table named inquiry created with SQL in another project. User responses’ must be uploaded into the inquiry table by using the MySQL statements. Add the code to upload the information to the inquiry table on the email.php file (the file used to send the emails from the inquiry form). To test that the results were uploaded into the table, use an if…else statement to display to the screen if the results were uploaded or not. Add at least 3 inquiry responses.
NOTE: Be sure the fields names of the inquiry form match the values variable names created to ensure the results are uploaded into the table. If problems with uploading the results, first look at the names of the fields, and order listed.
This is my inquiry.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$name = $_POST ['name'];
$address = $_POST ['address'];
$city = $_POST ['city'];
$state = $_POST ['state'];
$zip = $_POST ['zip'];
$phone = $_POST ['phone'];
$email = $_POST ['email'];
$major = $_POST ['major'];
$year = $_POST ['year'];
$semester = $_POST ['semester'];
$to="bgoog#mail.nira.edu, ther691#gmail.com"; //an email is sent to your email account and to
$message="To Whom It May Concern, <br>";
$message.="My information is listed below: <br><br>";
$message.="Name: $name<br>";
$message.="Address: $address<br>";
$message.="City: $city<br>";
$message.="State: $state<br>";
$message.="Zip: $zip<br>";
$message.="Phone: $phone<br>";
$message.="Email: $email<br>";
$message.="Major: $major<br><br>";
$message.="I plan to enter in the $semester of $year. <br>";
$message.="Please assist me in this matter.<br><br>";
$message.="Respectfully,<br>";
$message.="B Good<br>";
$subject="University - Inquiry Form";//The subject of the email is �University - Inquiry Form�
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: <therock691#gmail.com>" . "\r\n";//the email should like it was sent from the person contacting University
$response=mail($to,$subject,$message,$headers);
if($response)
{
Echo "Email sent successfully";
}
else //
{
Echo "Error Occured while sending email";
}
$hostname = "localhost";
$username = "vde_bgood";
$password = "s0123456";
$database = "vde_bgood";
$table = "inquiry";
mysql_connect($hostname, $username, $password) or die("Unable to connect to database");
mysql_select_db($database) or die ("Unable to select db");
$fields = "id, name, address, city, state, zip, phone, email, major, semester year";
$values = "'$id', '$name', '$address', '$city', 'state', 'zip', 'phone', 'email', 'major'. 'semester', 'year'";
$query = "INSERT INTO $table ($fields) VALUES ($values)";
$result = mysql_query($query);
if($result)
echo "Thank you for completing the Inquiry Form";
else
echo "Sorry, this is not currently working";
?>
<br>
<br>
<a href='inquiry.html'>Go back to contact form</a></body>
</html>
.HTML Document:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function MM_validateForm()
{ //v4.0
if (document.getElementById)
{
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3)
{
test=args[i+2];
val=document.getElementById(args[i]);
if (val)
{
nm=val.name;
if ((val=val.value)!="")
{
if (test.indexOf('isEmail')!=-1)
{
p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
}
else if (test!='R')
{
num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1)
{
p=test.indexOf(':');
min=test.substring(8,p);
max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
}
}
}
else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n';
}
}
if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
}
}
</script>
</head>
<body>
<form action="inquiry.php" method="post" name="form1" id="form1">
<h2>Nira University Enrollment Form</h2>
<table width="500" border="1">
<tr>
<td width="171"><label for="name">Name:</label></td>
<td width="313"><input name="name" type="text" id="name" form="form1" title="name"></td>
</tr>
<tr>
<td width="171"><label for="name">Street Address:</label></td>
<td width="313"><input type="text" name="address" id="address"></td>
</tr>
<tr>
<td width="171"><label for="name">City:</label></td>
<td width="313"><input type="text" name="city" id="city"></td>
</tr>
<tr>
<td width="171"><label for="name">State:</label></td>
<td width="313"><input type="text" name="state" id="state"></td>
</tr>
<tr>
<td width="171"><label for="name">Zip Code:</label></td>
<td width="313"><input type="text" name="zip" id="zip"></td>
</tr>
<tr>
<td width="171"><label for="name">Telephone:</label></td>
<td width="313"><input name="phone" type="text" id="phone" onBlur="MM_validateForm('name','','R','address','','R','city','','R','state','','R','zipcode','','RisNum','phone','','R','email','','RisEmail','major','','R');return document.MM_returnValue"></td>
</tr>
<tr>
<td width="171"><label for="name">Email Address:</label></td>
<td width="313"><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td width="171"><label for="name">Intended Major:</label></td>
<td width="313"><input type="text" name="major" id="major"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><label for="select">Year:</label></td>
<td><select name="year" id="year" >
<option value="">Select Year</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
</select></td>
<label for="select3"></label>
<tr>
<td><label for="select">Semester:</label></td>
<td width="313"><select name="semester" id="semester" title="semester">
<option value="">Select Semester</option>
<option value="Spring">Spring</option>
<option value="Summer">Summer</option>
<option value="Fall">Fall</option>
</select></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td width="171"><input name="submit" type="submit" id="submit" onClick="MM_validateForm('name','','R','address','','R','city','','R','state','','R','zip','','RisNum','phone','','R','email','','NisEmail','major','','R');return document.MM_returnValue" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
I don't even know what your supposed to be asking us? However if the problem is coming from your mysql query try this:
$result = mysql_query("INSERT INTO inquiry($fields) VALUES('$values')");
You may want to check your $fields and $values variables as you have some inconsistencies. You do not have semester and year separated with a comma in $fields, but you have them separated in the $values. Also, you have a period, not a comma, in between major and semester in $values.
Now, if I'm understanding this right, you have your table with your information in it and now want to populate your form with this information. You're going to have to query your DB and select the information then display it on your form either using variables or an array.
$query = "SELECT * FROM table_name";
$result = mysqli_query($con, $query);
$data = mysqli_fetch_array($result);
Then you can use as so:
$name = $data['name'];
$address = $data['address'];
etc.
Then using PHP you can plug these variables where you would like to display them. You can find more info here: http://us1.php.net/manual/en/book.mysqli.php and here: http://www.tutorialspoint.com/php/mysql_select_php.htm.
Hope this helps.
Related
This question already has answers here:
What does enctype='multipart/form-data' mean?
(9 answers)
Closed 6 years ago.
I have a simple registration form, in which I accept inputs from the user that includes an image, and insert the values in a table : temporary_employees table . In my code, I check whether the email id and the user id entered by the user already exists and if they dont , i go ahead and perform the insert after moving the image to a folder named 'images' . While running the code , I am getting an error Undefined index: image, on the line where I have the following piece of code :
$target_file = $target_path . basename ($_FILES['image']['name']);
The most interesting thing is the same line of code has worked perfectly well in another php file . I had given the same name for the input in the html form . . How is it possible ? Any help will be appreciated .
Here is my code :
//start the session before anything is echoed to the browser
if (session_status()===PHP_SESSION_NONE) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Login form
</title>
</head>
<body>
<h3>Registration Form</h3>
<form action ="" method="POST">
<table align="center" cellpadding="10">
<tr>
<td>Name</td>
<td><input type="text" maxlength='100' name="empname" id="empname" required></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="text" maxlength='100' name="emailid" id="emailid" required>
</td>
</tr>
<tr>
<td>User Id</td>
<td><input type="text" maxlength='100' name="userid" id="userid" required ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" maxlength='100' name="pwd" id="pwd" required ></td>
</tr>
<tr>
<td>Date of Birth</td>
<td>
<select name='year'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
</select>
<select name='month'>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
</select>
<select name='day'>
<option value='01'>1</option>
<option value='02'>2</option>
<option value='03'>3</option>
<option value='04'>4</option>
<option value='05'>5</option>
</select></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" maxlength='100' name="designation" id="designation" required></td>
</tr>
<tr>
<td>Department</td>
<td><input type="text" maxlength='100' name="department" id="department" required></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" maxlength='100' name="image" required></td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Register Yourself">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
//create a connection
$conn = mysqli_connect('localhost', 'root', '', 'attendance');
//on the click of submit button
if (isset($_POST['login'])) {
//capture the $_POST values
$name = $_POST['empname'];
$name = trim($name);
$email = $_POST['emailid'];
$email = trim($email);
$userid = $_POST['userid'];
$userid = trim($userid);
$pwd = $_POST['pwd'];
$pwd = trim($pwd);
$desg = $_POST['designation'];
$desg = trim($desg);
$dept = $_POST['department'];
$dept = trim($dept);
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$date = $year.$month.$day;
//display a message if there is a blank entry for email
if ($email=="") {
echo "Please enter a valid email id";
}
//display a message if there is a blank entry for userid
if ($userid=="") {
echo "Please enter a valid User Id";
}
//check if the email id exists
$sql_check_email = "select * from employee where emp_email='$email';";
mysqli_query($conn, $sql_check_email);
$aff_email = mysqli_affected_rows($conn);
// if email id exists ..display message
if ($aff_email==1) {
$msgemail = "The email id exists";
echo $msgemail;
//display error message if there is an error
} else if ($aff_email>1) {
$msgemail = "There are multiple employees with the same email";
echo $msgemail;
//display message if there is an error firing the query
} else if ($aff_email<0) {
echo "There is an error ..Try again";
}
//check if the user id exists
$sql_check_userid = "select * from employee_login where emp_uid='$userid';";
mysqli_query($conn, $sql_check_userid);
$aff_userid = mysqli_affected_rows($conn);
if ($aff_userid==1) {
$umsg = "User id already exist";
echo $umsg;
//display error message if there is an error when the query is fired
} else if ($aff_userid<0) {
echo "There is an error ..Try again";
}
//if neither the user id nor the email id exist, upload image and do the insert
if ($aff_userid==0 && $aff_email==0) {
$target_path = "images/";
$target_file = $target_path . basename ($_FILES['image']['name']);
//if the image is moved to the images folder , do the insert
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
$image = basename($_FILES['image']['name']);
$sql_ins = "INSERT INTO temporary_employee(emp_uid,emp_pwd,
emp_name,emp_email,emp_dob,emp_designation,
emp_department,emp_image)
VALUES('$userid','$pwd','$name','$email','$date',
'$desg','$dept','$image')";
mysqli_query($conn, $sql_ins);
$aff_insert = mysqli_affected_rows($conn);
//display success message if insert is successfull
if ($aff_insert==1) {
echo "You have successfully registered ...awaiting approval by admin";
//display message if there were no insert
} else if ($aff_insert==0) {
echo "The registration has failed ..Try again";
//diplay error message if there was an error while firing the insert query
} else if ($aff_insert<0) {
echo "There was an error ..Try again";
}
}
}
}
?>
While using Image Uploading in the form you have to use the enctype in the form attribute.
<form action ="" method="POST" enctype="multipart/form-data">
</form>
Change
<form action ="" method="POST">
to
<form enctype="multipart/form-data">
And try again.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
I have a dropdown HTML menu with some values which I want to insert into an input table. When the 'Insert Production' button is clicked I want it to insert these values into the relevant data table.
Previously I just entered the 'genre' details manually as text and they input into the table ok, but have now changed the input to a dropdown, but the value doesn't get entered into the table. Is there a simple way of ensuring that this value gets uploaded to the table? Sorry if this is painfully basic, but am still pretty new to all this.
<html>
<head>
<title>Inserting Production</title>
</head>
<body>
<form method="post" action="insert_product.php" enctype ="multipart/form-data">
<table width="500" height="650" align="center" border="2" bgcolor="#c6ff1a">
<tr align="center">
<td colspan="2"<h1>Insert new production:</h1></td>
</tr>
<tr>
<td align="right"><b>Production Name:</b></td>
<td><input type="text" name="prod_name" size="40"/></td>
</tr>
<tr>
<td align="right"><b>Production Genre:</b></td>
<td><select>
<option value="Drama">Drama</option>
<option value="Thriller">Thriller</option>
<option value="Comedy">Comedy</option>
<option value="Children">Children</option>
<option value="Sci-fi">Sci-fi</option>
<option value="Horror">Horror</option>
<option value="Documentary">Documentary</option>
<option value="Fantasy">Fantasy</option>
</select></form></td>
</tr>
<tr>
<td align="right"><b>Production Year</b></td>
<td><input type="text" name="prod_year"</td>
</tr>
<tr>
<td align="right"><b>Production Description</b></td>
<td><textarea name="prod_desc" cols="35" rows="10"/></textarea></td>
</tr>
<tr>
<td align="right"><b>Product Keywords</b></td>
<td><input type="text" name="prod_keywords"</td>
</tr>
<tr>
<td align="right"><b>Production Image</b></td>
<td><input type="file" name="prod_img"</td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="insert_production" value ="Insert Production"/></td>
</tr>
</form>
</body>
</html>
<?php
//fetches product title, cat etc and submits them to database
if(isset($_POST['insert_production'])) {
//text data variables
$product_name = $_POST['prod_name'];
$product_genre = $_POST['prod_genre'];
$product_year = $_POST['prod_year'];
$product_desc = $_POST['prod_desc'];
$product_keywords = $_POST['prod_keywords'];
//Inserting image names in db and image files saving in my htdocs/Admin_area/product_images/$product_img1
//Images names
$product_img1= $_FILES['prod_img']['name'];
//Image temporary name(we have to set image temporary names)
$temp_name1= $_FILES['prod_img']['tmp_name'];
if ($product_name == '' OR $product_genre == '' OR $product_desc == '' OR $product_year == ''){
//Simple validation alert. If user leaves any of above fields empty
//will pop-up alert box saying 'Please insert your data etc ...'
echo "<script>alert('Please complete all fields!')</script>";
exit();
}//if
else {
move_uploaded_file($temp_name1,"product_images/$product_img1");
$insert_product = "insert into productions (prod_name, prod_genre, prod_year, prod_desc, prod_keywords, prod_img)
values ('$product_name', '$product_genre', '$product_year', '$product_desc', '$product_keywords', '$product_img1')";
$run_product = mysqli_query($db, $insert_product);
//If this query runs
if ($run_product) {
echo "<script>alert('Production inserted successfully!')</script>";
echo "<script>window.open('index.php?insert_product', '_self')</script>";
}//if
}//else
}//if
?>
just add this line and try again to submit the from.
<select name="prod_genre">
You forgot to give your select tag a name. You need to give it a name if you want to use this form element for e.g. database storage etc.
So change <select> to <select name="prod_genre">
I hope this helps you!
At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>
Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)
You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];
Okay I have this MySQL database form and am trying to add validation to it. After 2 days of fighting with it, I thought I would get some advice. Would like that the selected item from dropdown and Firstname, Phone, Email, are all required. Then I want to verify that the data in the Firstname, Lastname, Phone (doesn't have to be any special format), Email and Comments are all acceptable formats before putting in database. Here is what I have so far:
<?php
include('inc_header.php');
if(isset($_POST['add']))
{
require('dbcon.php');
if(! get_magic_quotes_gpc() )
{
$Id = addslashes ($_POST['Id']);
$List = addslashes ($_POST['List']);
$Firstname = addslashes ($_POST['Firstname']);
$Lastname = addslashes ($_POST['Lastname']);
$Phone = addslashes ($_POST['Phone']);
$Email= addslashes ($_POST['Email']);
$Calltime = addslashes ($_POST['Calltime']);
$Comment = addslashes ($_POST['Comment']);
}
else
{
$Id = $_POST['Id'];
$Date = $_POST['Date'];
$List = $_POST['List'];
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Calltime = $_POST['Calltime'];
$Comment = $_POST['Comment'];
}
$error = '';
//put chosen function here
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function isValidEmail( $Email ){
return filter_var( $Email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$List = mysql_real_escape_string($_POST['List']);
if(!$List){ $error .= "Please choose one<br />"; }
$Firstname = mysql_real_escape_string($_POST['Firstname']);
if(!$Firstname){ $error .= "First name is required<br />"; }
//get values and validate each one as required
$Lastname = mysql_real_escape_string($_POST['Lastname']);
if(!$Lastname){ $error .= "Last name is required<br />"; }
//repeat for each field
$Email = mysql_real_escape_string($_POST['Email']);
if(!isValidEmail($Email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<? print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><? print(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>
</body>
</html>
So far I just keep chasing error message. Please forgive formatting I am trying to learn be gentle.
Your query arguments are backwards, and you should be using mysqli_. Here is the correct order.
$retval = mysqli_query($conn, $sql);
mysqli_query documentation
you need an end bracket for this statement: (if(!$error){)
edit: the } you were missing is actually a closing bracket for if(isset($_POST['add'])), not magic quotes. sorry!
//and so on...
if(!$error)
{
//add insert into database code here
// this probably won't run right...
// you're missing a ( after the word values...
// insert into tablename (id, name, stuff) values (1,'gloomy','stuff);
// this part of your statement is not correct: "VALUES'$Id,','$Date',
// and the commas are off, too.
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
// print your SQL here to make sure it is correct.
// copy and paste it to run it directly in the DB. if it won't run there
// it won't run here
print $sql."<br/>";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
} // <-------- you're missing this closing bracket
} // this ends the statement for if(isset($_POST['add'])) { ....
else
{
// REMOVE this... or else it will print the world else somewhere
// i put this here to debug...
print "else<br/>";
?>
formatting your code helps a lot
EDIT: looking over the code, there's a lot of small issues everywhere. I'm not trying to be mean. I'm just saying... why don't you try to break the code up into smaller pieces and make sure all the parts will compile and work properly on their own before putting them all together? This is a lot to tackle all at once. Just try to dump your variables (arrays in particular) when you need to and each time you write a new chunk, make sure it works correctly and make sure everything else still works correctly. Then, move forward... it's easier to isolate problems that way.
this works for me. it uses pdo. oh, and now you don't need to worry about sql injection as much. this pretty much takes care of it completely. like everything, there's always ways around things but you do not need to check for magic quotes, you do not need to escape anything. doing the parameterization handles all that for you.
edit: so... when you write code... don't write a whole bunch of stuff and then see if it all works. write a few lines. test. write some more. test. make sure the new stuff works. make sure the old stuff still works. write a little more. i have absolutely no clue how you got that far with so many little issues. i'm not trying to be mean. write code in lil chunks, though. even logic. always test everything again, then move on.
and I left my debug statements in there... the print_r($array) and the var_dump(variable) so that you can see how that stuff is set up, where your values are coming from, what everything holds at whatever point, how to use them, where to put them. it will print weird things now. comment it out or remove them.
I understand there's a lot more tutorials for mysql_ functions but they are old and not safe at all. If you have issues using PDO, just come back to StackOverflow with your errors, issues and code and just write a disclaimer that "you know mysql_ functions are bad but the pdo is harder to learn" and people will be happy to help because it is that much better.
these are important PDO pages:
$stmt->bindParam()
$stmt->execute()
$stmt->rowCount() (I didn't use this but you might want it later)
$stmt->fetchAll() - for your select statements. this returns all the data in a huge array
how to prepare statements
and the code...
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// include('inc_header.php');
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function isValidEmail($Email) {
return filter_var($Email, FILTER_VALIDATE_EMAIL);
}
// ====================================================================================
// ====================================================================================
if (!empty($_POST)) {
print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>";
}
$error = '';
if (isset($_POST['add']))
{
// require('dbcon.php');
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
// what if the array index ['whatever'] doesn't exist? errors.
// so we need to check and make sure it is set... then assign.
// this also gives us a blank default value, which is nice....
$id = isset($_POST['Id']) ? $_POST['Id'] : 'NULL';
$date = isset($_POST['Date']) ? $_POST['Date'] : '';
$list = isset($_POST['List']) ? $_POST['List'] : '';
$firstname = isset($_POST['Firstname']) ? $_POST['Firstname'] : '';
$lastname = isset($_POST['Lastname']) ? $_POST['Lastname'] : '';
$phone = isset($_POST['Phone']) ? $_POST['Phone'] : '';
$email = isset($_POST['Email']) ? $_POST['Email'] : '';
$calltime = isset($_POST['Calltime']) ? $_POST['Calltime'] : '';
$comment = isset($_POST['Comment']) ? $_POST['Comment'] : '';
if (!$list) {
$error .= "Please choose one<br />";
}
if (!$firstname) {
$error .= "First name is required<br />";
}
if (!$lastname) {
$error .= "Last name is required<br />";
}
if (!isValidEmail($email)) {
$error .= "The email entered is invalid<br />";
}
var_dump($error);
if (!$error)
{
$stmt = $conn->prepare("INSERT INTO contacts (id, date, list, firstname, lastname, phone, email, calltime, comment) \n".
" VALUES (:id, :date, :list, :firstname, :lastname, :phone, :email, :calltime, :comment) ");
$success = $stmt->execute(array(':id'=>$id, ':date'=>$date, ':list'=>$list, ':firstname'=>$firstname, 'lastname'=>$lastname,
':phone'=>$phone, ':email'=>$email, ':calltime'=>$calltime, ':comment'=>$comment));
if (!$success)
{
echo "\nPDO::errorInfo():\n";
print "<pre>".print_r($dbh->errorInfo(),true)."/<pre>";
}
else
{
print "it worked! the new row's ID is ".$conn->lastInsertId()."...!!!<br/>";
}
echo "Entered data successfully<br/><br/>";
} // end of if (!$error) { ... }
else
{
print "$error<br/>";
}
echo "<a href='contactsadd.php' style='font-color=#000000'>Back</a>\n";
} // end of if(isset($_POST['add'])) { ... }
else
{
// ====================================================================================
// ====================================================================================
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<?php print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><?phpprint(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>
I'm working with a form that I've altered from another site I created, which works, and for some reason it's not working here. I've been through the code a hundred times and am missing the vital clue!
The form includes php validation. If the required fields aren't filled it shows the form again, with anything that HAS been filled automatically put into the new form. Except that it's not automatically filling those completed fields, and it's not validating a valid submission.
I'm guessing that the data isn't being posted correctly, but I can't see where the problem is!
Here's the initial form:
<form name="userform" method="post" action="send_form_email.php">
<table>
<tr>
<td class="form_item_name">Name:</td><td><input type="text" name="name"></td>
</tr>
<tr>
<td class="form_item_name">Company name:</td><td><input type="text" name="company"> </td>
</tr>
<tr>
<td class="form_item_name">Email:</td><td><input type="text" name="email"></td>
</tr>
<tr>
<td class="form_item_name">Phone:</td><td><input type="text" name="phone"></td>
</tr>
<tr>
<td class="form_item_name"></td>
<td>
<select name="subject">
<option value="Requesting A Quote" selected="selected">Requesting A Quote</option>
<option value="Product/Service Support">Product/Service Support</option>
<option value="General Enquiry">General Enquiry</option>
</select>
</td>
</tr>
<tr>
<td class="form_item_name">Your comments:</td><td><textarea style="resize:none; width:350px;" name="comments" rows="10" wrap="hard"></textarea><br />
<br />
<input class="button_send" type="image" value=" " src="images/transparent.gif"></form>
And here's the action php (send_form_email.php):
<?php
if(strlen($name) > 2 &&
strlen($email) > 2 &&
strlen($comments) > 2) {
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_to = "sales#happytobevisuals.com";
$email_from = "Website: Contact Us";
if (strpos($subject,'General Enquiry') !== false) {
$email_subject = "General Enquiry";
}
elseif (strpos($subject,'Product/Service Support') !== false) {
$email_subject = "Product/Service Support";
}
elseif (strpos($subject,'Request A Quote') !== false) {
$email_subject = "Quote Request";
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Company: ".clean_string($company)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
$email_message .= "Phone: ".clean_string($phone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
"Reply-To: ".$email."\r\n" .
"X-Mailer: PHP/" . phpversion();
#mail($email_to, $email_subject, $email_message);
?>
<font face="times new roman" color="#FFF" size="+3">Thanks for that, your message has been sent!</font><br>
Click here to go back to the home page
<?php
}else{
?>
<font face="times new roman" color="#FFF" size="+3">Woops! Missed something ...</font>
<br>
<br>
<form name="userform" method="post" onsubmit="return validate();" action="send_form_email.php">
<table>
<tr>
<td class="form_item_name">Name:</td><td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td class="form_item_name">Company name:</td><td><input type="text" name="company" value="<?php echo $company;?>"></td>
</tr>
<tr>
<td class="form_item_name">Email:</td><td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td class="form_item_name">Phone:</td><td><input type="text" name="phone" value="<?php echo $phone;?>"></td>
</tr>
<tr>
<td class="form_item_name"></td>
<td>
//this next bit's about autofilling the dropdown to reflect their previous selection
<?php
if (strpos($subject,'General Enquiry') !== false) {
echo '<select name="subject">
<option value="General Enquiry">General Enquiry</option>
<option value="Product/Service Support">Product/Service Support</option>
<option value="Complaint">Complaint</option>
</select>';
}
if (strpos($subject,'Product/Service Support') !== false) {
echo '<select name="subject">
<option value="General Enquiry">General Enquiry</option>
<option value="Product/Service Support" selected="selected">Product/Service Support</option>
<option value="Complaint">Complaint</option>
</select>';
}
if (strpos($subject,'Complaint') !== false) {
echo '<select name="subject">
<option value="General Enquiry">General Enquiry</option>
<option value="Product/Service Support">Product/Service Support</option>
<option value="Complaint" selected="selected">Complaint</option>
</select>';
}
}
?>
</td>
</tr>
<tr>
<td class="form_item_name">Your comments:</td><td><textarea style="resize:none; width:350px;" name="comments" rows="10" wrap="hard"><?php echo $comments ?></textarea><br />
<br />
<input type="submit" value="valid"></form>
So... can you see it? All help appreciated!
PS. Is there a quicker way on stackoverflow to put code into a block than adding four spaces manually before each line? Cheers :)
I dont see where $name, $email, etc are coming from. Did you assinged the $_POST data to your variables?
this way
$name = $_POST['name']
$email = $_POST['email']
$phone = $_POST['phone']
$comments = $_POST['comments']
//etc
You probably have register_globals off on this host (which is a VERY good thing from a security standpoint - see http://php.net/manual/en/security.globals.php !), which explains why this was working on your other host but not here. If that's the case, the variables you're referencing don't exist in the global scope. Use the $_POST array when referencing posted variables.
This at the top of your script should get it working:
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
// etc...
You need to pull the variables from the $_POST array in order to utilize them in PHP. Your HTML is fine, but to retrieve the form submission, you must use code akin to the following:
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];