我有一个foreach代码,可以从其他表中收集每个员工ID的数据(例如评估,出勤)。
现在我想将这些新收集的数据推送到名为dss
的新表中,所以这是我的代码
$servername = "localhost";
$dbname = "ems_db";
// Create connection
$conn = new mysqli($servername, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO dss (emp_name, average, date)
VALUES ($name, $average, $date)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
这是我得到的结果
Error: INSERT INTO dss (emp_name, average, date) VALUES (Francis Ajax, 65, 2016-03-17)
No database selected
Error: INSERT INTO dss (emp_name, average, date) VALUES (Horus Skye, 66, 2016-03-17)
No database selected
Error: INSERT INTO dss (emp_name, average, date) VALUES (Lotus Po, 68, 2016-03-17)
No database selected
有人可以告诉我我做错了什么以及如何解决它? :(
发现新错误
Error: INSERT INTO dss (emp_name, average, date) VALUES (Lotus Po, 68, 2016-03-17)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Po, 68, 2016-03-17)' at line 2
我认为是因为varchar需要" "
或' '
,但由于我的值来自变量,我真的不知道如何修复它。
答案 0 :(得分:1)
您的连接语法看起来不正确
试试这个:
$conn = mysqli_connect($servername, $username, $password, $db_name) or die( mysqli_connect_error());
// By default $username = 'root' and $password = ''
$sql = "INSERT INTO dss (emp_name, average, date) VALUES ('".$name."', '".$average."', '".$date."')";
希望这有帮助。
和平!的xD
答案 1 :(得分:1)
http://php.net/manual/en/mysqli.construct.php
构造新mysqli对象的语法是:
$conn = new mysqli($servername, $username, $password, $dbname);
因此,您应该提供用户名和密码。这些可能是空白或默认值。
答案 2 :(得分:1)
使用它进行数据库连接并尝试:
$ dbserver ='localhost';
$ dbusername ='您的用户名';
$ dbpassword ='您的密码';
$ dbname ='ems_db';
if(!mysql_connect($ dbserver,$ dbusername,$ dbpassword))
{
die(“数据库连接失败”.mysql_error());
}
如果(!mysql_select_db($ DBNAME))
{
die(“数据库选择失败”.mysql_error());
}