1

I have created a function where I just need to fetch single data for some reason it is not working and I don't know what's the problem

here's my code

$functions->fetch_single('user_tbl', $objectID, $id, 'hidden_post');


function fetch_single($table_name = '' ,$where = '', $where2 = '', 
  $fetch = '', $debug=false){
    $query = "SELECT * FROM $table_name WHERE $where = $where2";

    if($debug){
        exit($query);
    }

    $statement = $this->connection->prepare($query);

    if($statement->execute()){
        $fetch_single_data =  $statement->fetchAll(PDO::FETCH_ASSOC);
        return $fetch_single_data[0]['$fetch'];  
    }
    return false;
}


  function execute_query($query){
    $statement = $this->connection->prepare($query);

    if( $statement->execute() ){
        return $statement;
    }
    return false;
}

It's not even go inside if statement execute and I don't know what is the problem. please help thank you

  • 1
    Probably a quoting issue with values. Try echoing out the produced SQL and show us the result. – Jonnix Jul 18 '19 at 13:51
  • 3
    Your prepare failed. If you're going to prepare a statement, then use [bindParam](http://php.net/manual/en/pdostatement.bindparam.php) or [bindValue](http://php.net/manual/en/pdostatement.bindvalue.php) to prevent quoting issues and SQL injection. You should also check for PDO errors. See https://stackoverflow.com/questions/32648371/my-pdo-statement-doesnt-work for more information. – aynber Jul 18 '19 at 13:53
  • This is the result I get @Jonnix SELECT * FROM user_tbl WHERE user_isd = bcf1cdb5b285669a859fc95443869f84 I think there's no problem – Christian Read Jul 18 '19 at 14:08
  • 4
    You need quotes around string values in SQL - `"SELECT * FROM $table_name WHERE $where = '$where2'"` – MER Jul 18 '19 at 14:23
  • 2
    Possible duplicate of [When to use single quotes, double quotes, and backticks in MySQL](https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql) – aynber Jul 18 '19 at 14:24
  • Already solved the problem thank you guys for helping me, @MER is correct I just overlooked to add quotes around the string values in my SQL thank you <3 – Christian Read Jul 18 '19 at 15:54

1 Answers1

0

Already solved the problem thank you guys for helping me I just need to add quotes around the string values in my SQL

 $query = "SELECT * FROM $table_name WHERE $where = '$where2'";
  • your SQL / PHP is **deepy** unsafe. While you may have solved your issue, you **really *really*** should explore how to [safely build SQL queries in OO PHP](https://phpdelusions.net/pdo). – Martin Jul 18 '19 at 16:29