Search code examples
phpmysqlpdo

php pdo function connect to DB and do query


I am trying to be as efficient with code as possible. Unfortunately, I can't seem to figure out a good way of doing this. I have tried using Sammitch's code which does look cleaner but unfortunately it doesn't seem to work.

I would like a way to stop having to use prepare, execute, every time and a function to me makes the most sense. Using Simmitch's suggestion, I removed the initial connection to database to stop unnecessary overheads but the code still does not work. Showing a "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" error.

My code at present (some parts omitted as not necessary):

/*Function to talk to database*/
function doQuery($myDB, $myQuery, $myValues)
{
    try
    {     
        $st = $myDB->prepare($myQuery);       
        $st->execute($myValues);
        //echo $success;
    }
    catch (PDOException $e)
    {
        echo "Failed because: " . $e->getMessage();
    }
}

    $db = new PDO('mysql:host=localhost;dbname='dbanme';charset=utf8', 'dbuser', 'dbpass');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
    $query = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
    $values = array('username' => $_POST['username'],
                     'password' => $_POST['password1'],
                     'email' => $_POST['email'],
                     'county' => $_POST['county']
                     );
    doQuery($db, $query, $values);

Solution

  • <?php
    
    function doQuery($db, $query, $arguments) {
        //Prepare and execute SQL         
        $st = $db->prepare($query);       
        $st->execute(array($values));
        return $st;
        // it makes no sense to echo PHP errors manually, hence no try catch needed
    }
    
    // 1. Don't create the database inside of the same function that does the queries,
    //    creation/destruction of the objects/connections will cause unnecessary overhead,
    $myDb = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbuser', 'dbpassword');
    $myDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
    
    $myQuery = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
    
    // 2. You can't define an array like that.
    // 3. You do not need to add colons to the array indexes.
    $myValues = array(
        'username' => $_POST['username'],
        'password' => $_POST['password1'],
        'email' => $_POST['email'],
        'county' => $_POST['county']
    );
    
    doquery($myDb, $myQuery, $myValues);
    // having a single db handle lets you to get the insert id
    $id = $myDb->insertId();
    // Returning the statement allows to use this function with SELECT queries as well:
    $row = doquery($myDb, "SELECT * FROM users WHERE id=?", [$id])->fetch();