您好,我试图使用PHP将数据插入MSSQL。我已经多次尝试弄清楚问题可能是什么,但我似乎没有找到它。有什么东西没有得到正确或缺失吗?
<?php
//pull form fields into php variables
$no = $_POST['no'];
$name= $_POST['name'];
$date = $_POST['date'];
$leave = $_POST['leave'];
$days= $_POST['days'];
$empno= $_POST['empno'];
//connect to sql
$dbc = mssql_connect('Server-PC','user','password','database')or die('Error connecting to
the SQL Server database.');
// Input into staff database
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No_],[Employee Name],
[Leave Name], [Start Date],[Leave Days],Satus) VALUES
('$no','$name','$leave','$date','days','empno')";
$r esult = mssql_query($query,$dbc)or die('Error querying MSSQL database');
//close to sql
mssql_close($dbc);
echo $name . 'Your submission has been received<br />';
echo 'If you need change this request please contact your HR Manager<br />';
echo 'Thank you <br />';
echo 'HR Manager';
?>
我收到此错误消息:
警告:mssql_query()[function.mssql-query]:message:无效的对象名称'dbo.CAGD Plan'。
(严重级16)在第110行的C:\ xampp \ htdocs \ CAGD \ leave_request.php
Warning: mssql_query() [function.mssql-query]: Query failed in C:\xampp\htdocs
\CAGD\leave_request.php on line 110
Error querying MSSQL database
答案 0 :(得分:2)
首先指定数据库连接...
mssql_connect('Server-PC','user','password','database')
like -> "localhost","root","XXXX", "DBNAME"
然后查询
$query = "INSERT INTO TABLENAME (id,name) VALUES
('$id','$name')";
$result = mssql_query($query,$dbc)
答案 1 :(得分:2)
您可以使用SQLSRV驱动程序代替MSSQL驱动程序,然后尝试使用
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$no = $_POST['no'];
$name= $_POST['name'];
$query = "INSERT INTO dbo.Test
(No_,FirstName)
VALUES(?, ?)";
$params1 = array($no,$name);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
这更有用,你可以在这里了解更多:
https://msdn.microsoft.com/en-us/library/cc626305(v=sql.105).aspx
答案 2 :(得分:0)
嗯,在我看来,你在表格中有7个字段但只提交了6个值 - 你缺少第一列的值[No_]
。
此外,最后一列satus
(我认为它应该是'status')没有de []
分隔符。
返回的错误告诉您表的名称是错误的。
是的变量名称在PHP中区分大小写,它应该是$ leave - 最好退出字符串并连接 - 类似于"bla bla".$leave."anything here with spaces or not"
。
答案 3 :(得分:0)
这应该是变量吗?
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No
^^^^^^
如果是这样,那么它在您的代码中显然未定义,并且生成的查询字符串将包含dbo.[CAGD Plan]
,而不是该变量中应该包含的任何值。如果$
确实在您的表名中,那么它应该是CAGD\$Leave
,因此$Leave
不会被视为变量。