【问题标题】:How to use function value in query如何在查询中使用函数值
【发布时间】:2017-05-21 08:34:19
【问题描述】:

我正在尝试在我的一个查询中使用时间函数...我有如下查询,用于在我的一个 DATETIME 字段中添加自定义时区时间。

$upd_qry = "update tbl_quotes 
                set qu_status='".$_GET['status']."', qu_time= $getDatetimeNow  
                where _quid='".$_GET['quotes_id']."'";
        $result=mysqli_query($mysqli,$upd_qry);

使用自定义时区获取时间的函数如下所示

function getDatetimeNow() {
        $tz_object = new DateTimeZone('Brazil/East');
        //date_default_timezone_set('Brazil/East');

     $datetime = new DateTime();
        $datetime->setTimezone($tz_object);
        return $datetime->format('Y\-m\-d\ h:i:s');
        }

但我的查询不起作用...这有什么问题?

谢谢

【问题讨论】:

  • 将查询添加到隐藏的 html 元素,如 使用 jquery 调用元素
  • 查看参数化查询

标签: php html mysql mysqli


【解决方案1】:

您需要将返回的函数值分配给另一个变量:

$getDatetimeNow = getDatetimeNow();

$upd_qry = "update tbl_quotes 
set qu_status='".$_GET['status']."', qu_time=".$getDatetimeNow." 
where _quid='".$_GET['quotes_id']."'";
$result=mysqli_query($mysqli,$upd_qry);

或直接调用它 - 如果您知道不需要在其他地方使用它的值 - 如下所示:

"update tbl_quotes
set qu_status='".$_GET['status']."', qu_time=".getDatetimeNow()." 
where _quid='".$_GET['quotes_id']."'"

更新:

您非常需要使用prepared 语句,因为您的代码容易受到SQL injection attacks 的攻击:

$getDatetimeNow = getDatetimeNow();
$upd_qry = "update tbl_quotes 
set qu_status=?, qu_time=? 
where _quid=?";
$stmt = mysqli_prepare($mysqli, $upd_qry);
mysqli_stmt_bind_param($stmt, "isi", $_GET['status'], $getDatetimeNow, $_GET['quotes_id']);
$result = mysqli_stmt_execute($stmt);

【讨论】:

  • 你是对的...非常感谢:)
【解决方案2】:

您不能使用变量之类的函数。函数与参数一起使用。这意味着它们必须与变量容器一起使用,例如 ($variable, $anotherVariable)

所有不带参数的函数都需要这种表示法。

$updateQuery = "UPDATE table_name SET field_name = " . functionName() . " WHERE id='" . (int) $_GET['id'] . "'";

$result = mysqli_query($mysqli, $updateQuery);

【讨论】:

  • 虽然此答案可能会解决 OP 的问题,但仅发布代码答案可能对 OP 或未来用户没有帮助。请详细说明您的答案,并明确解释它如何帮助 OP 实现他们所追求的解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-09-20
  • 2021-08-05
  • 2013-11-18
  • 2018-07-23
  • 2014-03-23
  • 2011-12-18
  • 1970-01-01
  • 2019-10-16
相关资源
最近更新 更多