Abhinav
Abhinav

Reputation: 709

How to use PDO to fetch data

Below are details: 1. PDO connect class which have the function to connect with DB. Say PDO_connect class. 2. Logic class file say MyLogic file, MyLogic file include PDO_connect and another class in which functions are written say MyFunction Class.

Problem : I am not able execute select query and fetch object using below query. MyFunction Class have function :

function gCD($query_type,$connection_obj,$u_id,$c_id)
{
    if($query_type == 'SELECT')
    {
        $prepare_sql = $connection_obj->prepare("SELECT c_n from cs where u_id=:u_id and c_id=:c_id");
        $query_select_clients = $prepare_sql->execute(array(':u_id'=>$u_id,':c_id'=>$c_id));
        echo "\n".$prepare_sql->rowCount();
        exit; //This is also not working.
        $g_c_obj = $prepare_sql->fetch(PDO::FETCH_OBJ);
        var_dump($g_c_obj);
      }
}

All arguments are passed from MyLogic File, connection and other details. If I do this debugging it returns true:

var_dump($prepare_sql->execute(array(':u_id'=>$u_id,':c_id'=>$c_id)))

But neither rowCount() nor fetch() are giving any output. Your help is highly valuable.

Upvotes: 1

Views: 102

Answers (1)

zedfoxus
zedfoxus

Reputation: 37119

This information was too long for a comment so I am typing this as an answer to help debug your case.

Test each case as you go through using PDO functionality. Each functionality like prepare, execute and fetch have a return value. Capture the return value, analyze it and act based on the return value. Substitute your information in appropriate places and see where your execution path stops.

<?php
$db = new PDO('mysql:host=localhost;dbname=xyz', 'user', 'pass');

gCD('SELECT', $db, 2, 2);

function gCD($query_type,$connection_obj,$u_id,$c_id)
{
    if($query_type == 'SELECT')
    {
        try
        {
            $prepare_sql = $connection_obj->prepare("SELECT c_n from cs where u_id=:u_id and c_id=:c_id");
            if ($prepare_sql === false)
            {
                echo "PDO prepare failed\n";
                return false;
            }
            $query_select_clients = $prepare_sql->execute(array(':u_id'=>$u_id,':c_id'=>$c_id));
            if ($query_select_clients === false)
            {
                echo "PDO execute failed\n";
                return false;
            }
            echo "\n".$prepare_sql->rowCount();
            $g_c_obj = $prepare_sql->fetch(PDO::FETCH_OBJ);
            if ($g_c_obj === false)
            {
                echo "PDO fetch failed\n";
                return false;
            }
            var_dump($g_c_obj);
            return true;
        }
        catch (Exception $e)
        {
            echo 'Exception: ', $e->getMessage(), "\n";
        }
    }
    else
    {
        echo 'Not a select statement', "\n";
    }
    return false;
}
?>

Upvotes: 1

Related Questions