在PHP函数中使用PDO查询

时间:2017-08-22 20:43:16

标签: php mysql pdo

我不是专业人士,刚开始学习PHP编码。

我遇到一些让PDO在函数内部工作的问题。希望有人能告诉我在函数内编码的正确方法。

function testKey($key){
// CHECK IF LINK IS AVAILABLE IN THE DATABASE
$result = dbConnect()->prepare("SELECT _uniq_key FROM _link_key WHERE 
_uniq_key= :1 AND _active= :2");
    $result->bindParam(':1', $key);
    $result->bindParam(':2', $o);
    $result->execute();
    $rows = $result->fetch(PDO::FETCH_NUM);
        if($rows > 0) {

            echo 'link is available';
            checkLink();

        }
        else 
        {

            echo 'link does not exist!';
        }
}

PDO无法正常工作,并且无法执行PDO脚本。

3 个答案:

答案 0 :(得分:1)

function testKey($key){
    // global $key; BAD
    // Assuming that active must be 1
    $active = 1;
    // CHECK IF LINK IS AVAILABLE IN THE DATABASE
    // Assuming that dbConnect() makes the correct PDO object
    $result = dbConnect()->prepare("SELECT _uniq_key FROM _link_key WHERE _uniq_key= :1 AND _active= :2");
    $result->bindParam(':1', $key);
    $result->bindParam(':2', $active); // only find active records
    $result->execute();
    $rows = $result->fetch(PDO::FETCH_NUM);

    if( $rows !== false ) {
        // http://php.net/manual/en/pdostatement.fetch.php
        // If no record, this function will also return false.
        echo 'link is available';
        checkLink(); // not sure what this does
    }
    else 
    {
        echo 'link does not exist!';
    }
}

现在调用函数:

$mySpecialKey = 'mango';
testKey($mySpecialKey); // note parameter is passed here

答案 1 :(得分:-2)

发现我的错误,工作代码:

function testKey($key){
global $key;
// CHECK IF LINK IS AVAILABLE IN THE DATABASE
$result = dbConnect()->prepare("SELECT _uniq_key FROM _link_key WHERE 
_uniq_key= :1 AND _active= :2");
$result->bindParam(':1', $key);
$result->bindParam(':2', $o);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
    if($rows > 0) {

        echo 'link is available';
        checkLink();

    }
    else 
    {

        echo 'link does not exist!';
    }
}

答案 2 :(得分:-2)

这里的调整很少

 if($rows > 0) {

    echo 'link is available';
    checkLink();

}
else 
{

    echo 'link does not exist!';
}

试试这个

 if($result->rowCount() > 0) {

    echo 'link is available';
    checkLink();

}
else 
{

    echo 'link does not exist!';
}