使用DATEDIFF接收SQL错误

时间:2014-07-22 09:24:16

标签: mysql datediff

我正在尝试使用DATEDIFF计算pdate和mdate之间的天数;然后将其显示为ddate。我收到错误“错误:您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在'SELECT contacts DATEDIFF(2014-07-22,2014-07-22)附近使用正确的语法'在第2行“。我的代码究竟出了什么问题?

<?php $con=mysqli_connect("localhost","xxx","xxx","xxxx"); // Check connection 
 if (mysqli_connect_errno()) 
 {   
  echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
 }

// escape variables for security 
$pdate = mysqli_real_escape_string($con, $_POST['pdate']); 
$mdate = mysqli_real_escape_string($con, $_POST['mdate']); 
$amt = mysqli_real_escape_string($con, $_POST['amt']); 
$first = mysqli_real_escape_string($con, $_POST['first']); 
$last = mysqli_real_escape_string($con, $_POST['last']); 
$pid = mysqli_real_escape_string($con, $_POST['pid']); 
$cno = mysqli_real_escape_string($con, $_POST['cno']); 
$madd = mysqli_real_escape_string($con, $_POST['madd']); 
$bene = mysqli_real_escape_string($con, $_POST['bene']); 
$swc = mysqli_real_escape_string($con, $_POST['swc']); 
$bacc = mysqli_real_escape_string($con, $_POST['bacc']); 
$bank = mysqli_real_escape_string($con, $_POST['bank']); 
$badd = mysqli_real_escape_string($con, $_POST['badd']); 
$bno = mysqli_real_escape_string($con, $_POST['bno']);

$sql="INSERT INTO contacts (pdate, mdate, amt, first, last, pid, cno,madd, bene, swc, bacc, bank, badd, bno, ddate) VALUES ('$pdate','$mdate','$amt','$first','$last','$pid','$cno','$madd','$bene','$swc','$bacc','$bank','$badd','$bno','$ddate')";

$sql.="SELECT contacts DATEDIFF($pdate,$mdate) AS ddate";

if (!mysqli_query($con,$sql)) 
{   
 die('Error: ' . mysqli_error($con));
} 

echo "Client record has been added to the database!";

mysqli_close($con); 
?>

1 个答案:

答案 0 :(得分:0)

您不需要在select查询中使用表引用,因此如果定义了$ pdate和$ mdate变量并且具有日期值,则以下内容应该有效:

SELECT DATEDIFF($ pdate,$ mdate)AS ddate

此外,您正在将此查询与前一个插入相结合,因此您需要在插入的末尾添加一个分号。