php select语句使用用户输入无效

时间:2016-02-04 14:05:43

标签: php

我无法弄清楚这一点。在用户输入用户名后,我试图从我的数据库中获取数据,传递给我所做方法的$username变量取自登录页面$_POST全局变量。我意识到代码仅在我手动输入值时才起作用,我试图绑定变量,但这对我来说也不起作用。

public static function pullbyUsername($username,$table,$object){
    $sql = "";
    if(is_numeric($username == true)){
        $sql = "SELECT {$object} FROM {$table} WHERE pollId = '{$username}'";
    }
    else{
        $sql = "SELECT {$object} FROM {$table} WHERE username = '{$username}'";
    }
    if($sql != ""){
        try{
            $pdo = new PDO(includes::get('mysql/host'),includes::get('mysql       /username'),includes::get('mysql/password'));

            $result =$pdo->query($sql);
            $rows = $result->fetchAll(PDO::FETCH_ASSOC);

            return $rows[0][$object];
        }
        catch (PDOException $ex) {
            die($ex->getMessage());  
        }
    }
    else{
        return null;
    }
}

我试过这段代码而且它也无法正常工作

public static function pulbyUsername($username,$table,$object){
    $sql = "";
    if(is_numeric($username) == true){
      $sql = "SELECT {$object} FROM {$table} WHERE pollId = ':username}'";
    }
    else{
      $sql = "SELECT {$object} FROM {$table} WHERE username = ':username'";
    }
        try{
       $pdo = new PDO(includes::get('mysql/host'),includes::get('mysql/username'),includes::get('mysql/password'));
       $statement = $pdo->prepare($sql);
       $statement->execute(array('username'=>$username));
       $result = $statement->fetchAll();
       var_dump($result);

       }

2 个答案:

答案 0 :(得分:0)

 function pulbyUsername($username,$table,$object){
    //$db = new PDO('mysql:dbname=wp_db;host=localhost', 'root', '');
    $connStr = 'mysql:dbname=wp_db;host=localhost'; 
    $pdo = new PDO($connStr,'root','');  
    $sql = "";
    if(is_numeric($username) == true){
      $sql = "SELECT ".implode(",", $object)."FROM {$table} WHERE pollId = ':username'";
      //echo $sql;
    }
    else{
      $sql = "SELECT " .implode(",", $object)." FROM {$table} WHERE user_login = '{$username}'";
      //echo $sql;
    }

       //$pdo = new PDO(includes::get('mysql/host'),includes::get('mysql/username'),includes::get('mysql/password'));
       $statement = $pdo->prepare($sql);
        $statement->execute(array('username'=>$username));
       $result = $statement->fetchAll();
       var_dump($result);
       //print_r($result);

 }
 $image_exts = array('ID','user_email');
 pulbyUsername('admin','wp_users',$image_exts);

答案 1 :(得分:0)

我明白了,瓦西姆·范扎拉说得对,但是有空白区域,所以我对它进行了尝试并且它的工作原理谢谢你