I am very new to PHP & MySQL. Just designing websites for friends as a hobby, so any help is greatly appreciated. When I have a simple contact form on my page I keep getting error messages when submitting the information. Here is the PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con)) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database_name", $con);
$sql="INSERT INTO contact (first_name, last_name, email, phone, message)
VALUES
('$_POST[first_name]','$_POST[last_name]','$_POST[email]','$_POST[phone]','$_POST[message])";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I put in my username & password where necessary, but I keep “localhost” there. Is this correct? I have hosting through webhostingpad. I also insert my database name above. Here is my HTML:
<!--Start of order form-->
<form id="contactform" method="POST" action="http://www.talephotography.com/insert.php">
<p><label>First Name:<br />
<input type="text" name="first_name" class="textfield" value="" />
</label></p>
<p><label>Last Name:<br />
<input type="text" name="last_name" class="textfield" value="" />
</label></p>
<p><label>Email: <br />
<input type="text" name="email" class="textfield" value="" />
</label></p>
<p><label>Phone: <br />
<input type="text" name="phone" class="textfield" value="" />
</label></p>
<p><label>Message: <br />
<textarea name="message" class="textarea" cols="45" rows="5"></textarea>
</label></p>
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
<!--End of order form-->
I can elaborate anywhere necessary.
Changed some of the code, it’s only posting the email address to the database however.
mysql_select_db("databasename", $con);
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($_POST['last']);
$email = strip_tags(mysql_real_escape_string($_POST['email']));
$number = preg_replace('/[^0-9]/', '', $_POST['number']);
$number = (int) $number;
$sql="INSERT INTO contact (first, last, email, phone);
VALUES
('$first','$last','$email','$number')";
There’s my code, however when I check my database the only info listed is the email address.
localhostis correct if the database server is on the same machine as the web server. When you set up the database it should have told you somewhere what you need to connect to.That aside, escape your ———–ing inputs!!!!
Seriously, take those variables and wash them thoroughly with
mysql_real_escape_stringand then concatenate them into the query. You’ll thank me later.