从foreach循环内部重置变量的值

时间:2019-09-13 09:02:03

标签: php variables foreach

我正在处理其他人的代码,看来MySQL插入语句存在一些问题...

  

第1行的“ floorSize”列的数据被截断了

似乎可以在很多字段中执行此操作,但理想情况下,我希望允许它们为空。

所以我要遍历发布的数据并寻找一个空字符串,如果它是一个空字符串,我想将该变量重置为NULL。这样数据库就可以接受空值而不是''字符串。

目前,我正在使用一个foreach循环来查看其值是否为空,然后尝试将该值设置为NULL。但是看起来不多

当前代码段为:

function add_user($first_name, $last_name, $gender, $date_of_birth, $address1, $address2, $city, $state, $country, $zip_code, $mobile, $phone, $username, $email, $password, $profile_image, $description, $status, $user_type, $property, $VAN, $agent, $propertyType, $buyerType, $houseName, $street, $postcode, $parish, $zoning, $lat, $lng, $price, $ARV, $tax, $fees, $availableDate, $term, $type, $bedrooms, $bathrooms, $powderrooms, $guestAccom, $furnished, $shortDescription, $floorSize, $plotSize, $pool, $waterfront, $dock, $tennis, $view, $garden, $pets, $fireplace, $laundry, $ac, $patio, $deck, $verandah, $beach, $propertySkipper, $mooring, $gym, $showMap, $display, $videoURL, $garage, $tankSize, $water, $well, $tank, $holiday) {

    global $db;

    $vars = $_POST;

    $count = 0;
    foreach($vars as $k => $v)
    {
        if($v == '')
        {
            $k = NULL;
        }
    }

    //Running Query to add user.
        $query = "INSERT into users VALUES(NULL, '".$first_name."', '".$last_name."', '".$gender."', '".$date_of_birth."', '".$address1."', '".$address2."', '".$city."', '".$state."', '".$country."', '".$zip_code."', '".$mobile."', '".$phone."', '".$username."', '".$email."', '".$password_con."', '".$profile_image."', '".$description."', '".$status."', '', '".date('Y-m-d')."', '".$user_type."', '".$property."', '".$VAN."', '".$agent."', '".$propertyType."', '".$buyerType."', '".$houseName."', '".$street."', '".$postcode."', '".$parish."', '".$zoning."', '".$lat."', '".$lng."', '".$price."', '".$ARV."', '".$tax."', '".$fees."', '".$availableDate."', '".$term."', '".$type."', '".$bedrooms."', '".$bathrooms."', '".$powderrooms."', '".$guestAccom."', '".$furnished."', '".$shortDescription."', '".$floorSize."', '".$plotSize."', '".$pool."', '".$waterfront."', '".$dock."', '".$tennis."', '".$view."', '".$garden."', '".$pets."', '".$fireplace."', '".$laundry."', '".$ac."', '".$patio."', '".$deck."', '".$verandah."', '".$beach."', '".$propertySkipper."', '".$mooring."', '".$gym."', '".$location_id."', '".$showMap."', '".$display."', '".$videoURL."', '".$garage."', '".$tankSize."', '".$water."', '".$well."', '".$tank."', '".$holiday."')";
}

因此,例如$ floorSize设置为'',但理想情况下,我想覆盖以将其设置为NULL。

我的查询是:

INSERT into users VALUES(NULL, '', '', '', '2000-01-01', '', '', '', '', 'Bermuda', '', '', '', '', 'amy.peniston@gmail.com', '0cc0d896622bca5f24125fd5e5f2fabb', '', '', 'activate', '', '2019-09-13', 'subscriber', 'PW Property', '', 'sue', '1', '0', '', '', '', 'devonshire', '', '32.309851', '-64.781894', '125000', '100', '1', '2', '', '', 'sale', '3', '3', '1', '0', '0', '', '', '', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '472', '0', '0', '', '0', '', '0', '0', '0', '0')

谢谢

2 个答案:

答案 0 :(得分:2)

$k是键,您需要分配值。您可以通过将$v用作参考变量来完成此操作。

    foreach($vars as $k => &$v)
    {
        if($v == '')
        {
            $v = null;
        }
    }

如果您要这样调用函数:

add_user($_POST['first_name'], $_POST['last_name'], ...);

然后您需要在调用函数之前而不是函数内部放置此循环 。并且您需要遍历$_POST,而不是将其复制到的另一个变量(除非调用时在参数列表中使用了该变量)。

然后,您需要使用准备好的语句。如果仅将变量连接到SQL字符串,则null会变成一个空字符串,它将不会成为数据库中的NULL值。准备好的语句还将防止SQL注入。

$query = "INSERT into users VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $db->prepare($query);
$date = date('Y-m-d');
$stmt->bind_param("sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss", $first_name,$last_name,$gender,$date_of_birth,$address1,$address2,$city,$state,$country,$zip_code,$mobile,$phone,$username,$email,$password_con,$profile_image,$description,$status,$date,$user_type,$property,$VAN,$agent,$propertyType,$buyerType,$houseName,$street,$postcode,$parish,$zoning,$lat,$lng,$price,$ARV,$tax,$fees,$availableDate,$term,$type,$bedrooms,$bathrooms,$powderrooms,$guestAccom,$furnished,$shortDescription,$floorSize,$plotSize,$pool,$waterfront,$dock,$tennis,$view,$garden,$pets,$fireplace,$laundry,$ac,$patio,$deck,$verandah,$beach,$propertySkipper,$mooring,$gym,$location_id,$showMap,$display,$videoURL,$garage,$tankSize,$water,$well,$tank,$holiday);
$stmt->execute();

答案 1 :(得分:0)

您正在插入查询中使用函数参数。因此,您不应检查$ _POST中的值。

// we can use this function inside of your function to get all paramenters
$params = get_defined_vars();

global $db;

foreach($params as $key => $param){
    if(empty($param)){
        ${$key} = NULL;
    }
    // we need to remove special characters to prevent sql injection
    ${$key} = mysqli_real_escape_string($db, $param);
}

// your query here

无论如何,这都不是理想的解决方案,因为它可能会遇到很多问题,因此我建议您删除所有函数参数,因为有很多直接使用$_POST的值。

function add_user() {
    global $db;

    $values = $_POST;

    foreach ($values as $key => $value) {
        $values[$key] = mysqli_real_escape_string($db, $value);

        if(empty($value)){
            $values[$key] = 'NULL';
        }
    }


    $first_name = $values['first_name'];
    $last_name = $values['last_name'];
    // .... and all your variables

    // be careful to get the right key from $POST variable when setting these variables

}