php - Converting to PDO -
Many thanks for reading my post
I am quite new in PHP. I am working on the project which uses Mysore and I am trying to change it to use PDO. I have a database class in my current set up but I have read and closed that when using PDOs, it is not useless for at least one database class or using PDO. Wanted. I know its a common question, but I want to make sure that as I changed my site, I am moving forward in the right way.
Thank you very much
OK, this is the most basic example of my first block block. Please do not try to work very hard ... See this
try {$ handler = new PDO ('mysql: host = localhost; dbname = app', 'root', 'fidelio'); $ Handler- & gt; Set Attribute (PDO: ATTRRAMOD, PDO :: ERRMODE_EXCEPTION); } Hold (PDOException $ e) {echo $ e-> getMessage (); Die (); } $ Name = "pdotest"; $ Message = "test message"; $ Sql = "Include guestbook (name, message, posted) VALUES (?,?, NOW ())"; $ Query = $ Handler- & gt; Ready ($ sql); $ Query-> Execute ($ name, $ message); This works
but why does not it work ....
class database {personal $ handler; Connect function () {$ db_host = "localhost"; $ Db_name = "app"; $ Db_user = "root"; $ Db_pass = "Fidelio"; {$ This- & gt; Handler = New PDO (try "mysql: host =". $ Db_host. "; Dbname =". $ Db_name, $ db_user, $ db_pass); } Hold (PDOException $ E) {Dead ($ E); }} }
database = new database; $ Name = "pdotest"; $ Message = "test message"; $ Sql = "Include guestbook (name, message, posted) VALUES (?,?, NOW ())"; $ Database- & gt; Handler- & gt; ($ SQL) ready; Database-> Execute ($ name, $ message);
The first $ handler is private, you can not access them directly
Second, you get $ Database-> Connect (); class database {... public function forgotten to getHandler () {$ $ this- & gt; Handler; }} $ Database = new database; $ Database- & gt; Connect (); $ Name = "pdotest"; $ Message = "test message"; $ Sql = "Include guestbook (name, message, posted) VALUES (?,?, NOW ())"; $ Database- & gt; GetHandler () - & gt; Ready ($ SQL); $ Database-gt; GetHandler () - & gt; Execution (array ($ name, $ message)); Note getHandler () function.
As noted by "your general knowledge", note that the connect function should be called only once - so for this you can call it function in Class Constructor.
You can call the class constructor __ construct ()
connect to the class database () function {..... ** ** Category creator creates a new object Time / Public Function __construct () {$ this- & gt; Connect (); }}
Comments
Post a Comment