jd5
jd5

Reputation: 11

Can not insert data into mysql database with php

I am having trouble inserting data to my table via PHP. The "cc_connect.php" is the file that connects the database. The form is there but when I submit it, no data is added to my table. I've followed several tutorials and matched their methods without success. Is something not set up in my db?

the function $dbcon is associated with my connection

<form method="post" action="cc_registration.php">
<input type="hidden" name="submitted" value="true" />

    First Name: <input type="text" name="first_name" />
    Last Name: <input type="text" name="last_name" />

<br />
<input type="submit" value="submit" />

  <?php

   if(isset($_POST['submit'])) {

   include ('cc_connect.php');

   if (!$dbcon) {

   die("Can not Connect: " . mysql_error());

}

   mysql_select_db("cooperstown",$dbcon);

$sql = "INSERT INTO cobra_registration (first_name,last_name) VALUES ('$_POST[first_name]', '$_POST[last_name]')";

mysql_query($sql,$dbcon);



mysql_close($dbcon);

}

  ?>

Upvotes: 0

Views: 394

Answers (2)

Matthew Johnson
Matthew Johnson

Reputation: 5165

The mysql_* functions are deprecated, and should no longer be used. Look into mysqli or PDO.

IMPORTANT NOTE

This is WIDE open to SQL Injection attacks. You should use prepared statements to protect against such attacks.

GGio nailed his answer, it was the submitted, but checking for submit. He also provided a PDO example, so I'll demonstrate the same thing in mysqli:

$firstName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
$lastName = isset($_POST['last_name']) ? $_POST['last_name'] : '';

if ($firstName && $lastName) {
    $stmt = $mysqli->prepare("INSERT INTO cobra_registration (first_name,last_name) 
  VALUES (?, ?)"); 
    $stmt->bind_param("ss", $firstName, $lastName);
    $stmt->execute();  

}

Upvotes: 2

GGio
GGio

Reputation: 7653

$_POST['submit'] is never set because you are passing submitted.

change:

<input type="hidden" name="submitted" value="true" />

to:

<input type="hidden" name="submit" value="true" />

As a side note your current query can easily be hacked. Use Prepared statements instead like PDO or MysQLi, here is an example in PDO:

$fName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
$lName = isset($_POST['last_name']) ? $_POST['last_name'] : '';

if ($fName && $lName) {
   $stmt = $db->prepare('
      INSERT INTO cobra_registration (first_name,last_name) 
      VALUES (:fname, :lname)
   ');

   $stmt->bindParam(':fname', $fName, PDO::PARAM_STR);
   $stmt->bindParam(':lname', $lName, PDO::PARAM_STR);

   $res = $stmt->execute();

   if ($res) {
      echo 'Success';
   } else {
      echo 'Failure';
   }
}

Upvotes: 3

Related Questions