2

So i have made a php file to insert data into my database. I have been trying for a while and can't seem to figure out where my code is wrong.

I am using this form:

<form class="form-horizontal" role="form" method="post" action="#section4">
      <div class="form-group">
        <label for="first_name" class="col-sm-2 control-label">Name</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="first_name" name="first_name" placeholder="First name" value="<?php echo htmlspecialchars($_POST['first_name']); ?>">
          <?php echo "<p class='text-danger'>$errName</p>";?>
        </div>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last name" value="<?php echo htmlspecialchars($_POST['last_name']); ?>">
          <?php echo "<p class='text-danger'>$errName</p>";?>
        </div>
      </div>
      <div class="form-group">
        <label for="email" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-10">
          <input type="email" class="form-control" id="email" name="email" placeholder="eksample@domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
          <?php echo "<p class='text-danger'>$errEmail</p>";?>
        </div>
      </div>


      <div class="form-group">
        <div class="col-sm-10 col-sm-offset-2">
          <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
          </div>
      </div>
    </form>

first i have the variables of information from my form:

<?php
if ($_POST["submit"]) {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];}

Then i log onto my database:

$dbhost = 'mysql.info.dk';
$dbuser = 'myinfo';
$dbpass = 'mypass';
$dbname = 'moreinfo';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname);

i then "attempt" to insert the info from the form to a table in my database:

$sql = "INSERT INTO contacts(`first_name`, `last_name`, `email`) VALUES ([$first_name],[$last_name],[$email])";

and close my connection:

mysqli_close($conn);
?>

Can someone help me spot where my code is wrong?

Emil Østervig
  • 440
  • 4
  • 20
  • 1
    `[...]` is the problem instead use `quotes`. And mysql is deprecated instead use `mysqli or PDO`. – Saty Dec 11 '15 at 10:16

1 Answers1

4

Use single quotes while insering and use mysqli instead of mysql

        $sql = "INSERT INTO contacts(`first_name`, `last_name`, `email`) VALUES ('$first_name','$last_name','$email')";
Oops
  • 1,373
  • 3
  • 16
  • 46