gpt4 book ai didi

php - CASE 更新的 SQL 条件

转载 作者:行者123 更新时间:2023-11-30 00:01:48 25 4
gpt4 key购买 nike

我正在更新 php/SQL 中的表单。该表单成功更新了 MYSQL,但删除了所有空字段。我想尝试一个根据表单是否有条目进行更新的 CASE 语句。

CASE
WHEN (variable is set/is not null?) UPDATE `sales` SET `company` ='$company'
END CASE

我找不到检查变量是否为 NULL 的方法。那可能吗?语法是什么?

//可能不需要的额外注释以下是有关我在 php 中所做的事情的信息。这与问题本身无关,但我发现人们更喜欢获得更多信息。该表单提交给一个类和构造函数。我正在研究依赖注入(inject)类,但这似乎有点矫枉过正。

<?php
echo "<html>
<form method='POST'>
<fieldset>
<input id='company' name='company' type='text' class='form-control' placeholder='". $company. "'>";
</fieldset>
</form>
</html>
?>

帖子:

<?php
if(isset ($_POST ["company"] )){
require 'updatereq.php';
//$update is the constructor
$update= new Salesupdateentry (($_POST ["company"]));
//update is just the SQL update in a php function, which works, but deletes blanks
$update->__update();
?>

//请注意 - 我已精简为一个变量,但实际上有 7 个。我试图使其更具可读性,但简单的 if (isset($_POST["company"])) 不会工作,因为还有 6 个其他 POSTS,它们有一个需要 POST 的构造函数。这就是为什么我想用 SQL 来做这件事

<?php
class Sales
{
public $company;
private $db;
public function __construct($company)
{
$this->company = $company;
$this->db =mysqli_connect("localhost", "databasename", "password", "table");
}

public function __save()
{
$this->company=htmlspecialchars($this->company);

$sql = ("INSERT INTO " . "`sales` " . "(`company`)" . " VALUES " . "('{$this->company}') ;");
return mysqli_query($this->db, $sql);
}
}

最佳答案

您无法检查 MySQL 中是否设置了 PHP 变量。

更好、更稳定的方法是在 PHP 中检查变量是否为 null 并执行相应的 SQL 语句。

如果你的变量是 MySQL 变量,你可以检查它是否为 null,如下所示:

CASE WHEN TABLE.FIELD IS NOT NULL...

您还可以使用IFNULL()用于此目的的功能。

NULL值不能与MySQL中的条件运算符一起使用,因此不能使用<, > or = 。相反,你必须使用 IS NULLNOT NULL .

关于php - CASE 更新的 SQL 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24968153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com