0

what's wrong here?:) I want to put data to database (I'm pretty sure that connection to db works).

$host="localhost";
$username="root";
$password="root";
$db_name="db";
$tbl_name="changes";

mysql_connect("$host","$username","$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");


$when=$_POST['when'];
$bad_teacher=$_POST['bad_teacher'];
$teacher=$_POST['teacher'];
$hour=$_POST['hour'];
$class=$_POST['class'];

$sql="INSERT INTO $tbl_name (when, bad_teacher, teacher, hour, class) VALUES (`$when`,`$bad_teacher`,`$teacher`,`$hour`,`$class`)";
mysql_query($sql);

?>
2

2 Answers 2

2

WHEN is mysql reserved keyword you need to use bactiks arround your column names matched with Rererved Keywords,and why you have used bacticks arround the values.

$sql="INSERT INTO 
$tbl_name (`when`, `bad_teacher`, `teacher`, `hour`, `class`) 
VALUES 
('".$when."','".$bad_teacher."','".$teacher."','".$hour."','".$class."')";

Also mysql* family is depreiciated you need to move on with pdo or aleast with mysqli* family.

Pdo demo

$dbhost     = "localhost";
$dbname     = "dbname";
$dbuser     = "user";
$dbpass     = "pass";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);


// query
$sql = "INSERT INTO books (`when`, `bad_teacher`, `teacher`, `hour`, `class`)
 VALUES (:when,:bad_teacher,:teacher,:hour,:class)";
$q = $conn->prepare($sql);
$q-> bindParam(':when', $when);
$q-> bindParam(':bad_teacher',$bad_teacher);
$q-> bindParam(':teacher', $teacher);
$q-> bindParam(':hour', $hour);
$q-> bindParam(':class', $class);
$q->execute();

Pdo Reference

Sign up to request clarification or add additional context in comments.

2 Comments

This should use query parameters instead of putting $_POST variables directly into SQL expressions.
you should probably put quotation marks around the php variables in case a variable has a space in it or some other invalid markup
0
//connection.php 

$dsn  = 'mysql:host=localhost;dbname=db';
$user = 'root';
$pass = 'root';
$option = array(
    PDO::MYSQL_ATTR_INIT_COMMAND =>'SET NAMES utf8',
);

try {
    $con = new PDO($dsn, $user, $pass,$option);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e) {
    echo 'Failed To Connect'.$e->getMessage();
}

//INSERT 

$sqli="INSERT INTO 
$tbl_name (`when`, `bad_teacher`, `teacher`, `hour`, `class`) 
VALUES 
('".$when."','".$bad_teacher."','".$teacher."','".$hour."','".$class."')";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.