-4

I am a beginner at PHP and MYSQL. Here is my simple code to add data to a data base. it is not working the connection.php(sets up the mysql connection variables) files have already been created and are working fine with other files and functions. Am receiving no errors while this code here does not add the data to the database could someone please tell me where the problem could be?

<?php

if (isset($_POST['bookt']) & isset($_POST['type']) &           isset($_POST['publisher']) & isset($_POST['year']) & isset($_POST['class']) &  isset($_POST['subject'])) {

//set the values
$bookt= $_POST['bookt'];
$type= $_POST['type'];
$publ=$_POST['publisher'];
$year=$_POST['year'];
$class= $_POST['class'];
$subj= $_POST['subject'];

    //INSERTING A ROW
$add_query= "INSERT INTO books ('Book Title','Type','Publisher','Yearp', 'Class','Subject') 
VALUES ('$bookt','$type','$publ','&year','$class','$subj')";

 //query
$result=mysql_query($add_query);
if (!$result) {die("couldn't perform query".mysql_error());}
 if ($result) {echo " </ br> <p><script type='text/javascript'>alert('INSERT         SUCCESSFUL!!!');</script></p><br /><br /> insert id was ".mysql_insert_id();}
};

?>
  • 2
    It's `$year`, not `&year`. Also, you are wide open to [**SQL injection**](https://www.owasp.org/index.php/SQL_Injection). – elixenide Dec 14 '16 at 00:11
  • 1
    Please [stop using the mysql_ functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) as they have been removed from PHP – Machavity Dec 14 '16 at 00:17

2 Answers2

1

If you want multiple conditions in your if-statement use a logical operator "&". Also mysql_ has been gone from PHP7 for a long time.

1

You have a lot of major problems with this code.

First, please don't use mysql_*; the mysql_* functions are outdated, deprecated, and insecure. They were removed entirely from PHP 7. Use MySQLi or PDO instead.

Second, the Boolean "and" operator is &&, not & (the bitwise "and" operator).

Third, it's $year, not &year.

Fourth, put column names in backticks, not single quotes ('...'):

$add_query= "INSERT INTO books (`Book Title`,`Type`,`Publisher`,`Yearp`, `Class`,`Subject'`) 
VALUES ('$bookt','$type','$publ','$year','$class','$subj')";

Single quotes will cause your query to fail. This is why your query isn't working at all.

Fifth, you aren't doing any error checking or data validation.

Sixth, you are wide open to SQL injection. You need to use prepared statements and never put user input directly into SQL.

There may be even more issues, but these are the big ones.

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100