Forum Moderators: coopster

Message Too Old, No Replies

PHP MySQL Insert

         

Saboi

1:04 pm on Jul 27, 2015 (gmt 0)

10+ Year Member



Hello friends,

Wrote the following. After running, nothing is inserted in the database.

Where could I be getting it wrong?


<?php

$forename = $_POST["forename"];

$surname = $_POST["forename"];

$gender = $_POST["forename"];

//Database connection variables

$servername = "";//servername
$username = "";//username
$password = "";/password
$database = "registration";

//Connect to Database

mysql_connect($servername, $username, $password, $database);

@mysql_select_db($database) or die("Unable to select database");

$query = "INSERT INTO students(forename, surname, gender) VALUES($forename, $surname, $gender)";

//mysql_query($query);

mysql_close();
?>

robzilla

1:21 pm on Jul 27, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You have mysql_query commented out.
//mysql_query($query);

Saboi

1:28 pm on Jul 27, 2015 (gmt 0)

10+ Year Member



Removed the comments.

Still has not worked.

whitespace

3:18 pm on Jul 27, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



So, what actually happens? What errors are reported?

You need to implement some basic error checking. Enable full error_reporting in PHP whilst developing. Don't use error suppression. Check the return values from your function calls, and examine SQL errors on failure.

There are numerous sources of error in your script, although assuming you are connecting to your DB ok, the fact that you've not quoted your string values in your INSERT statement is certainly a show stopper. (However, if you had implemented basic error checking, this would be an easy catch.)

Other sources of concern:

- You are assigning $_POST["forename"] to $forename, $surname and $gender. "Forename" is presumably not a valid "gender" so this could also break. In a live script never use $_POST["<anything>"] without sanitizing / validation first.

- Presumably you are assigning something meaningful to your DB connection vars? And you are indeed connected?

- You are using the deprecated mysql extension. mysql_connect() does not have a 4th "database" parameter. You are mixing this up with mysqli_connect() - which is perhaps the extension you should be using (or preferably PDO).

robzilla

4:35 pm on Jul 27, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Try to get the MySQL error message, if there is one:
mysql_query($query) or die(mysql_error());

And check your error logs for any PHP errors.