2

I'm trying to parse out my if-else statements nicely but it seems that it doesn't parse out the else statement.

$a = 1
if (is_numeric($a)) 
{
    $DB = new PDO('sqlite:database.db');
    $result = $DB->query('select id from staff where id='.$a);
        if ($result == "")
        {
        echo "'{$a}' is invalid. No such record", PHP_EOL;
        }
        else
        {
            echo "'{$a}' is found", PHP_EOL; 
        }

} 
else 
{
    echo "'{$a}' is NOT numeric", PHP_EOL;
}

My $result I think it will return in Integer as when I say to echo the $ result out, it says PDO statement cannot be converted to INT. It doesn't go to my first inner else statement. Please advise how did I make my mistake.

Thanks

4

1 回答 1

2

$result是一个对象,而不是一个整数。您需要调用 fetch 方法,例如fetchAll,甚至更简单,fetch将数据放入另一个变量中。

尝试:

$a = 1
if (is_numeric($a)) 
{
    $DB = new PDO('sqlite:database.db');
    $result = $DB->query('select id from staff where id='.$a);
        if ($result)
        {
            $data = $result->fetchAll(PDO::FETCH_NUM);
            if (!isset($data[0]))
                echo "'{$a}' is invalid. No such record", PHP_EOL;
            else
                echo "'{$a}' is found", PHP_EOL; 
        }    
} 
else 
{
    echo "'{$a}' is NOT numeric", PHP_EOL;
}

这是另一个例子fetch

$a = 1
if (is_numeric($a)) 
{
    $DB = new PDO('sqlite:database.db');
    $result = $DB->query('select id from staff where id='.$a);
        if ($result)
        {
            $data = $result->fetch(PDO::FETCH_ASSOC);
            if (!$data)
                echo "'{$a}' is invalid. No such record", PHP_EOL;
            else
                echo "'{$a}' is found", PHP_EOL; 
        }    
} 
else 
{
    echo "'{$a}' is NOT numeric", PHP_EOL;
}
于 2012-07-04T15:07:46.907 回答