从php代码向MySQL数据库添加元素

时间:2014-01-01 20:19:06

标签: php mysql database

这里有什么问题?:)我想把数据放到数据库中(我很确定与数据库的连接有效)。

$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 个答案:

答案 0 :(得分:2)

WHEN是mysql保留关键字,你需要使用与你的列名匹配的bactiks Rererved Keywords,以及为什么你在价值观中使用了bacticks。

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

此外,mysql *系列已被删除,您需要使用mysqli *系列继续使用pdo或aleast。

Pdo演示

$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

答案 1 :(得分: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."')";