Mikkel Bertelsen Mikkel Bertelsen - 6 months ago 17
SQL Question

Adding more than one value into my database (PDO)

I got a problem with my code.
I want to add more than just my

:SteamID
to my database.

Currently this function/PDO runs every time you enter my site.
Working code:


/*Check possible existing data*/
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$SQLCheckLoginQuery = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `steamid` = :SteamID");
$SQLCheckLoginQuery -> execute(array(':SteamID' => $steamid));
// $SQLCheckLoginQuery -> execute(array(':avatar' => $avatarid));
$countUsers = $SQLCheckLoginQuery -> fetchColumn(0);

if($countUsers <= 0){
$SQLInsertQuery = $odb -> prepare("INSERT INTO `users` (steamid) VALUES (:SteamID)");
$SQLInsertQuery -> execute(array(':SteamID' => $steamid));


This is what I want to add to my database aswell.

**// I want this stuff to be updated every time it runs this section**
$SQLInsertQuery -> execute(array(':avatar' => $avatarid));
$SQLCheckLoginQuery -> execute(array(':steamName' => $steamname));
}
?>


The problem is that it wont let me add
:avatar and :steamName
into my database.

Answer

You'll need to bind both of the parameters to the query before calling execute.

/*Check possible existing data*/
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$SQLCheckLoginQuery = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `steamid` = :SteamID AND avatar = :avatar");
$SQLCheckLoginQuery -> bindParam(':SteamID', $steamid);
$SQLCheckLoginQuery -> bindParam(':avatar', $avatarid);
$SQLCheckLoginQuery -> execute();
$countUsers = $SQLCheckLoginQuery -> fetchColumn(0);

if($countUsers <= 0){
    $SQLInsertQuery = $odb -> prepare("INSERT INTO `users` (steamid, avatar) VALUES (:SteamID, :avatar)");
    $SQLInsertQuery -> bindParam(':SteamID',$steamid);
    $SQLInsertQuery -> bindParam(':avatar',$avatarid);
    $SQLInsertQuery -> execute();
}

More info on bindParam from the docs

Comments