0

I got this piece of piece code from csfinance from a few years ago. I was wondering how I can printf the error code on the very last else when the query gets returned as false? (for example if its a duplicate entry print duplicate entry). Thanks for your help in advance!

function query(/* $sql [, ... ] */)
{
    // SQL statement
    $sql = func_get_arg(0);

    // parameters, if any
    $parameters = array_slice(func_get_args(), 1);

    // try to connect to database
    static $handle;
    if (!isset($handle))
    {
        try
        {
            // connect to database
            $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER . ';charset=utf8mb4', USER, PASSWORD);

            // ensure that PDO::prepare returns false when passed invalid SQL
            $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
        }
        catch (Exception $e)
        {
            // trigger (big, orange) error
            trigger_error($e->getMessage(), E_USER_ERROR);
            exit;
        }
    }
    // prepare SQL statement
    $statement = $handle->prepare($sql);
    if ($statement === false)
    {
        // trigger (big, orange) error
        trigger_error($handle->errorInfo()[2], E_USER_ERROR);
        exit;
    }

    // execute SQL statement
    $results = $statement->execute($parameters);

    // return result set's rows, if any
    if ($results !== false)
    {
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }
    else
    {
        return false;
    }
} 
4
  • The php doc on PDO::errorInfo is probably a good place to start. Commented Dec 3, 2016 at 23:22
  • The problem is that the handle.prepare function is returning true, its the fetchAll function that is returning the false Commented Dec 8, 2016 at 10:42
  • Sorry, I misunderstood the question. You might find a way with PDOStatement::errorinfo. You would probably have to split the return from the false to get the error information. Generally speaking, one should not have to debug CS50 supplied functions. It tends to be easier to troubleshoot sqls in phpMyAdmin; ie paste your sql, run it, see what is the result. Commented Dec 8, 2016 at 13:58
  • Actually finally that's what I ended up doing (posting the queries directly into phpmyadmin)! I'll continue to see if there isn't a more elegant solution but anyways thanks for your help! Commented Dec 8, 2016 at 15:10

0

You must log in to answer this question.

Browse other questions tagged .