PHP - Passing pdo connection query via php function

时间:2015-09-14 16:12:55

标签: php mysql pdo

So i'm trying to pass PDO Query by using php, like this(index.php):

include("dbconn.php");
mysqlConnect("'SELECT * FROM users WHERE name =' . $conn->quote($name))", "jeff");

while my dbconn file that contains the function is(dbconn.php):

function mysqlConnect($queryString, $name) {

    // DB Credentials
    $dbName = 'db';
    $dbUser = 'root';
    $dbPass = '';
    $dbHost = 'localhost';

try {
    $conn = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Here goes the first parameter, then it uses the second parameter as a variable
    $data = $conn->query($queryString);
    // So the output should be this:
    // $data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));

    foreach($data as $row) {
        print_r($row); 
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
}

So in my function call the php actually executes the $conn->quote($name)) code, making my application not work.

How should i do this? is this allowed in php?

Edit:

or in other words: i call a function and give it 2 parameters, one of the parameters(even tho it's in double quotes) is executed by php which shouldn't happen. How can i fix this

1 个答案:

答案 0 :(得分:1)

你写的方式,它永远不会奏效。您只需要学会将字符串文字与可执行代码区分开来。

无论如何,你根本不需要这样的弗兰肯斯坦。已经有一种机制可以将您的变量放在查询中,称为预处理语句。你只需要使用它们。

您的代码也存在其他问题。我在最近写的文章The only proper guide on PDO中已经对它们进行了描述,我相信你会发现它很有趣 - 所有问题包括错误的错误处理,完全错误的连接方式,缺乏准备好的语句 - 都在那里描述。让所有这些解决后,这里有你需要的正确功能:

function pdo($sql, $data=[]) 
{
    global $pdo; // you can add a call to your favorite IoC here.
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    return $stmt;
}

用作

include("dbconn.php");
$user = pdo("SELECT * FROM users WHERE name = ?", ["jeff"])->fetch();
var_dump($user);

这就是必须使用PDO的方式。

通过返回一个声明,您将能够使用PDO的所有功能,在一行中获取所需的数据,比如列表

$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
var_dump($news); // already an array

或只是一个值

$count = pdo("SELECT count(*) FROM posts WHERE author=?", [$id])->fetchColumn();
var_dump($count); // already a number

或简单地逐个迭代结果

$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
foreach ($news as $row) {
    var_dump($row);
}

等等。