-2

I'm quite new to PDO and OOP. After, I try to execute the code given below , I get this output :- Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\Mine\OOPs\pdo progs\function.php on line 20. Thanks.

<?php

class main
       {

         public function __construct()
       { 

        $obj=new PDO("mysql:host=localhost;dbname=arnob-pdo",'root','');    

       }    

        public function reg()   
    {
        global $obj;
        $name=$_POST['name'];
        $email=$_POST['email'];
        $pass=$_POST['pass'];
                $sql=$obj->query("insert into memo set                                                            
                name='".$name."',email='".$email."',pass='".$pass."'");

        if($sql)
            {
             ?>

             <script type="text/javascript"> 
             alert("WELCOME <?php echo $_POST['name']; ?> to Memo"); 
             </script>
             <?php  
            }
             else echo 'Registration Failure';
       }        
        }
       $main=new main;

       ?>


        index.php:
        <?php require('function.php'); 

        if (isset($_POST['submit']))
         {  

      $exe=$main->reg();
      echo $exe; 
         } 

         ?>

with a form for submit.

Digital Chris
  • 6,098
  • 1
  • 16
  • 28
  • Error is on C:\xampp\htdocs\Mine\OOPs\pdo progs\function.php on line 20. so post code from function.php too for evaluation. – Alyas Jan 21 '14 at 12:39
  • Fix your code formatting please. Currently it's impossible to read. – vbo Jan 21 '14 at 12:39
  • You actually should avoid having `global` variables. You might benefit from [this](http://stackoverflow.com/a/11369679/727208) solution instead. – tereško Jan 21 '14 at 13:13
  • Thanks Guyzz for the quick feedback.. Actually, this code without wrapping functions in classes worked. So, thought to enquire! Yeah, I'm just a beginner in this concept and I've to dig a lot deeper . – user3219124 Jan 21 '14 at 18:59

1 Answers1

-1

Basic instructions for classes and variables can be seen in the documentation: http://php.net/oop5.basic

As stated by other users, use good code formatting and clear descriptions of your variables ($obj is not descriptive).

<?php
    class main {
        private $db;

        public function __construct(){
            $this->db = new PDO( ... );
        }

        public function reg(){
            ...
            $sql = $this->db->query( ... );
            ...
        }
    }
?>
Richard
  • 193
  • 1
  • 9