2 回答
TA贡献1911条经验 获得超7个赞
$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();
TA贡献1842条经验 获得超13个赞
您在插入查询中使用函数参数。所以你不应该检查来自 $_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
}
- 2 回答
- 0 关注
- 217 浏览
添加回答
举报
