1

I am new to PHP, and I have been trying to make a small Homework Organiser Application.

The idea is that you can input a Subject and Description and it will be added to a MySQL Database (that's it for now).

I have created a html form:

<form action="insert.php">
        <label for="subj">Subject:</label>
        <br>
        <input type="text" name="subj">
        <br>
        <label for="desc">Description:</label>
        <br>
        <input type="text" name="desc">
        <br>
        <input type="submit" value="Submit" name="submit">
    </form>

and some php code:

<?php
$subject = $_POST['subj'];
$description = $_POST['desc'];
$subject = mysql_real_escape_string($subject);
$description = mysql_real_escape_string($description);

$dbhost = ''; //These are filled in actually
$dbuser = ''; //These are filled in actually
$dbpass = ''; //These are filled in actually
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}

$sql = 'INSERT INTO organiser '.
    '(subject,description) '.
    'VALUES ('$subject', '$description')';

mysql_select_db(''); //These are filled in actually
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
    die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>

The problem is that the input from the Subject and Description boxes on the HTML form don't go into the MySQL Database.

However, If I set

'VALUES ('$subject', '$description')';

to

'VALUES ("test", "test")';

it works.

Any help is appreciated! Thanks!

Th3No0b
  • 43
  • 8
  • You're missing `method="post"` in your form element. Aside from that, you should be doing some validation server side before using the data, and you shouldn't be using `mysql_` as it's deprecated now. – scrowler Aug 11 '14 at 22:34
  • For good measure: [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – esqew Aug 11 '14 at 23:04

3 Answers3

1

In addition to the answer already given in regards to missing dots for the concatenate:

Form method defaults to a GET method, if the method is omitted from the form tag.

You are using <form action="insert.php"> which is equivalent to doing
<form action="insert.php" method = "get"> which is not what you want nor required.

Change it to

<form action="insert.php" method="post">

since you are using POST variables.

That is the contributing reason why 'VALUES ("test", "test")'; works and not the other way, since both of these variables $subject - $description, are based on your POST variables:

$subject = $_POST['subj'];
$description = $_POST['desc'];

You can either do

$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";

as stated in a comment.

or

$sql = "INSERT INTO organiser (subject,description) VALUES ('".$subject."', '".$description."')";

Add error reporting to the top of your file(s)

error_reporting(E_ALL);
ini_set('display_errors', 1);

which would have signaled errors found in your code.


Yet, your method is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.


Use a mysqli prepared statements method; it's safer.

<?php 

$DB_HOST = "xxx"; // replace with your own
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
  die('Connection failed [' . $conn->connect_error . ']');
}

// optional to check for empty fields
// if(isset($_POST['submit']) && !empty($_POST['subj'])  && !empty($_POST['desc'])) {
if(isset($_POST['submit'])) {

$subject = stripslashes($_POST['subj']);
$description = stripslashes($_POST['desc']);

$stmt = $conn->prepare("INSERT INTO organiser (`subject`, `description`) VALUES (?, ?)");

$stmt->bind_param('ss', $subject, $description);

    if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

        else{
          echo "<h2>Success!</h2>";
        }

$stmt->close(); // Statement
$conn->close(); // MySQLi

}

?>

Form: (new)

<form action = "insert.php" method = "post">
        <label for="subj">Subject:</label>
        <br>
        <input type="text" name="subj">
        <br>
        <label for="desc">Description:</label>
        <br>
        <input type="text" name="desc">
        <br>
        <input type="submit" value="Submit" name="submit">
</form>
Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

You forgot the dots around the variables and you can add some double quotes around that depending on the content of your variables :)

'VALUES ("'.$subject.'", "'.$description.'")';
Alex
  • 478
  • 2
  • 11
  • 1
    or just `$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";` –  Aug 11 '14 at 22:34
  • Very true, but then you have to explain him the difference between wrapping with simple / double quotes :) – Alex Aug 11 '14 at 22:35
0

Your problem is because you are using single quotes in your $sql declaration,

$sql = 'INSERT INTO organiser '.'(subject,description) '.'VALUES ('$subject', '$description')';

When you use single quotes you are telling PHP that you would like everything within the quotes to be taken literally.

$age = 20; 
$myAge = 'I am $age years';
echo $myAge; 

This would echo I am $age years since you used single quotes.

However, if you used double quotes instead,

$age = 20; 
$myAge = "I am $age years";
echo $myAge;

The output would be,

I am 20 years

Thus, your $sql statement should be (I write it on one line instead),

$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
       ^                                                                               ^

If you echo your $sql it would become something along the lines of,

INSERT INTO organiser (subject,description) VALUES ('Your subject', 'Your description') 

Your use of single quotes within your SQL-statement is correct, you can read more about the subject here: When to use single quotes, double quotes and backticks

Community
  • 1
  • 1
Erlesand
  • 1,525
  • 12
  • 16