Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

php - How to make a PDO class method for inserting/updating/deleting with an unknown number of parameters in the arg

Currently Im trying to create a PDO class where I will have a method to run a query like INSERT, UPDATE, or DELETE.

For examaple this is my method for a SELECT

 public function getPreparedQuery($sql){
    $stmt = $this->dbc->prepare($sql);
    $stmt->execute([5]);
    $arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if(!$arr) exit('No rows');
    $stmt = null;
    return $arr;
}

And i Simply call it like this:

    $stmt = $database->getPreparedQuery($sql2);
var_export($stmt);

And so far I know that a runQuery should work something similar to this:

Insert Example without using a method:

$idRol = "6";
$nomRol = "test6";                          
$stmt = $database->dbc->prepare("insert into roles (idRol, NomRol) values (?, ?)");
$stmt->execute(array($idRol,$nomRol));
$stmt = null;

But I want to make it into an universal method where i simply can pass the sql sentence, something like this:

$database->runQuery($query);

but the query can happen to be

$query = "INSERT INTO roles (idRol, NomRol) VALUES ('4','test')";

or

$query = "INSERT INTO movies (movName, movLength, movArg) VALUES ('name1','15','movie about...')";

So how do I slice the arg $query so I can get all the variables that are being used in order to make an universal runQuery?

Because I can imagine that my method should be something like this

runQuery([$var1 , $var2, $var3....(there can be more)] , [$var1value, $var2value, $var3value...(there can be more)]){

        $stmt = $database->dbc->prepare("insert into movies($var1 , $var2, $var3....(there can be more)) values (?, ? , ? (those are the values and there ca be more than 3)"); //how do i get those "?" value and amount of them, and the name of the table fields [movName, movLength, movArg can be variable depending of the sentence]?
        $stmt->execute(array($var1,$var2, $var3, ...)); //this is wrong , i dont know how to execute it
        $stmt = null;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to add a second parameter to your function. Simply an array where all those variables would go. An array by definition can have an arbitrary number of elements, which solves your problem exactly:

public function runQuery($sql, $parameters = []) {
    $stmt = $this->dbc->prepare($sql);
    $stmt->execute($parameters);
    return $stmt;
}

this simple function will run ANY query. You can see the usage example in my article dedicated to PDO helper functions:

// getting the number of rows in the table
$count = $db->runQuery("SELECT count(*) FROM users")->fetchColumn();

// the user data based on email
$user = $db->runQuery("SELECT * FROM users WHERE email=?", [$email])->fetch();

// getting many rows from the table
$data = $db->runQuery("SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();

// getting the number of affected rows from DELETE/UPDATE/INSERT
$deleted = $db->runQuery("DELETE FROM users WHERE id=?", [$id])->rowCount();

// insert
$db->runQuery("INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);

// named placeholders are also welcome though I find them a bit too verbose
$db->runQuery("UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);

// using a sophisticated fetch mode, indexing the returned array by id
$indexed = $db->runQuery("SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);

As you can see, now your function can be used with any query with any number of parameters


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...