代码之家  ›  专栏  ›  技术社区  ›  Siraj Alam

如何归纳bind_-param中的数据类型?

  •  0
  • Siraj Alam  · 技术社区  · 8 年前

    我正在编写一个类方法,它将根据该方法的参数返回数据。

          public function getRow($value, $name='id'){
            con();
            $statement = $GLOBALS['con']->prepare('SELECT * FROM '.$this->tableName.' WHERE '.$name.' = ?')
                or die('Statement preparation failed.'.$GLOBALS['con']->error);
            $statement->bind_param('i', $id);
            $statement->execute();
            return $statement->get_result()->fetch_assoc();
        }
    

    这里的方法叫做like,

    getRow(10)
    

    所以查询将是

    SELECT * FROM table_name WHERE id = 10
    

    当它是

    getRow('StackOverflow', 'name');
    

    所以查询将是

    SELECT * FROM table_name WHERE name = 'Stackoverflow';
    

    但问题是变量的数据类型没有定义,有时是 int 有时 string .

    那么,如何在 bind_param 功能?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Devon Bessemer    8 年前

    如果不指定类型,只想绑定任何动态值,请使用“s”作为字符串。

    由于MySQL仍然使用整数和用引号括起来的浮点数,所以在PHP中进行类型检查没有意义,因为不管结果如何,它都将以相同的结果结束。

        2
  •  -1
  •   Dave    8 年前

    虽然这个功能是与PDO一起使用的,我确实建议您使用它,但是它很容易修改以满足您的需求。

    //
    // Return the proper PDO value for binding based on the data passed
    //
    
     function PDO_bind($variable) {
    
        if(is_numeric($variable)) return PDO::PARAM_INT;
        if(is_bool($variable))    return PDO::PARAM_BOOL;
        if(is_null($variable))    return PDO::PARAM_NULL;
    
        return PDO::PARAM_STR;
    
    }  // end of PDO_bind function
    
    推荐文章