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

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


第 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.

}

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



心有法竹
浏览 218回答 2
2回答

Smart猫小萌

$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();

红颜莎娜

您在插入查询中使用函数参数。所以你不应该检查来自 $_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}
打开App,查看更多内容
随时随地看视频慕课网APP