PHP使用键和值对检查foreach循环中的数值?

时间:2015-07-01 10:47:04

标签: php

我正在尝试检查关联数组值,如果它是数字,这是我的代码

     $data = array('fullname'=>'Salah Saed', 'age'=>'33', 'gender'=>'Female');



public function insert($data, $table){
    /*$query =  "INSERT INTO  `oop_crud`.`customers` (";
    $query .= "`fullname` , `age` , `gender` )"; 
    $query .= "VALUES ('".$fullname."',  '".$age."',  '".$gender."')";
    */
    $feilds = array(); 
    $feilds_value = array();
    foreach ($data as $field => $field_value){

        $feilds[] = $field;

        echo $field;
        if (is_numeric($field_value)){

            $feilds_value[] = $field_value;

        }else{

            $feilds_value[] = "'".$field_value."'";
        }


    }

    $query = "INSERT INTO ".$table." (";
    $query .= implode(',', $feilds).")";
    $query .= "VALUES (";
    $query .= implode(',',$feilds_value).")";


    echo $query;

它返回字符串,所以我的代码有什么问题, 在条件部分,我使用了$ field_value,这个变量有数组数据,播放如何获取数组值。

2 个答案:

答案 0 :(得分:4)

首先,MySQL插入是与类型无关的,所以

SET UserAge = '33'

相同
SET UserAge = 33

所以你只需添加引号就更安全了。也就是说,如果您使用PDO(也称为参数化查询)搜索预准备语句,那么您是最安全的。看看那个

http://php.net/is_numeric应该识别可能无法被MySQL识别的0x5390b10100111001等值;你需要检查这些案件。

答案 1 :(得分:2)

以下是您的函数的简化版本,以防您想要改进查询生成器函数,

function insert($data, $table){

    $column_sql = '`' . implode('`,`', array_keys($data)) . '`';

    $record_sql = "'" . implode("','", $data) . "'";

    return "INSERT INTO `{$table}` ({$column_sql}) VALUES ({$record_sql})";

}

提供$datatest会给出

INSERT INTO `test` (`fullname`,`age`,`gender`) VALUES ('Salah Saed','33','Female')

注意:需要转义值mysqli_real_escape_string(),我会将其留给您,作为练习:)