2

I'm still new in PHP and I can't seem to run my simple test code when I do it OOP style. What my simple test program does is save your name, age and sex in the database.

It used to run when it was still in procedural style but when I do it OOP style it doesn't run any more. By the way I use MS SQL Server as my database.

Here's my PHP code with a file name of process.php:

<?php

class Connection {
    public function connectDatabase() {
        $serverName = "localhost"; 
        $uid = "sa";   
        $pwd = "joseph04";  
        $databaseName = "Profile"; 

        $connectionInfo = array( "UID"=>$uid, "PWD"=>$pwd, "Database"=>$databaseName); 

        // Connect using SQL Server Authentication 
        public $conn;
        $conn = sqlsrv_connect( $serverName, $connectionInfo);  

        // Test Connection
        if( $conn === false )
        {
            echo "Connection could not be established.\n";
            die( print_r( sqlsrv_errors(), true));
        }
    }
}

class Insert extends Connection {
    public function post() {
        $Name = $_POST["NAME"];
        $Age = $_POST["AGE"];
        $Sex = $_POST["SEX"];

        $sql = "INSERT INTO dbo.ProfileTable 
        (
            Name,
            Age,
            Sex
        )
        VALUES 
        (
            '$Name',
            '$Age',
            '$Sex'
        )";

        $parameters = array($Name, $Age, $Sex);
        $stmt = sqlsrv_query($conn, $sql, $parameters);

        if( $stmt === false ){
            echo "Statement could not be executed.\n";
            die( print_r( sqlsrv_errors(), true));
        } 
        else {
            echo "Rows affected: ".sqlsrv_rows_affected( $stmt )."\n";
        }
        // Free statement and connection resources
        sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn);
    }
}


?>

And here's my HTML code:

<!DOCTYPE html>
<html>
   <head>
      <title>Sample Form</title>
      <link href="main1.css" rel="stylesheet" type="text/css">
   </head>

   <body>
      <form method="post" action="process.php">
         <table width="400" border="0">
            <tr>
            <td>Name:</td>
            <td></td>
            <td><input type="text" name = "NAME"></td>
            </tr>
            <tr>
            <td>Age:</td>
            <td></td>
            <td><input type="text" name = "AGE"></td>
            </tr>
            <tr>
            <td>Sex:</td>
            <td></td>
            <td><input type="text" name = "SEX"></td>
            </tr>
         </table>
         <input type="submit" name="formSubmit" value="Submit!"> 
      </form>
   </body>
</html>
3
  • 2
    Ok you have created classes. But where is the code creating instances of the classes and calling methods? eg. $o = new Insert(); $o->post(); Commented May 22, 2014 at 10:04
  • Oh I dont have those, how do I do that? help please? thank you for your response.. Commented May 22, 2014 at 10:06
  • In your form action file first create a instance of Class Insert Like $obj = new Insert(); called the method post like $obj->post(). And you have to call the connectDatabase method into post method. You can see the result. then Commented May 22, 2014 at 10:10

3 Answers 3

2

As said in the comments, at the bottom of your file, you need to add:

$i = new Insert();
$i->connectDatabase();
$i->post();

But I spot 1 more problem, causing an SQL injection vulnerability. You need to change:

    VALUES 
    (
        '$Name',
        '$Age',
        '$Sex'
    )";

into:

    VALUES 
    (
        ?,
        ?,
        ?
    )";

Because without doing so, you will be injecting the variables directly into your query, without escaping them. And you will be sending parameters without using them.

edit:

You also need to remove public $conn; from inside the function. Variables declared inside a function are scoped within that function and thus cannot be public. If you want to declare a public variable, then decalre it inside the class, but outside the functions. So like this:

class Connection {

    public $conn;

    public function connectDatabase() {
        // ...
Sign up to request clarification or add additional context in comments.

1 Comment

@JosephRojas consider upvoting the answers that helped and selecting one of them as the accepted answer by ticking the checkbox next to it.
0

The instanciation code is missing.

You can add at the end of your process.php file :

$o = new Insert();
$o->connectDatabase();
$o->post();

The $o variable will be an instance of the Insert class. And then be able to call the post() method, and execute your code.

I'll add that there is some things you can change in your code :

  • use parameters in the connect Database method to pass db parameters ($user, $pass, $host etc)
  • merge the 2 classes since you only have 2 methods and they are quite linked.

3 Comments

Thank you for yuor help @Thibault :)
One final question if its okay? why do I have an error when I run the program? This is my error: Parse error: syntax error, unexpected 'public' (T_PUBLIC) in C:\wamp\www\process.php on line 14 my line 14 is: public $conn; Thank you in advance!
@JosephRojas I have edited my answer, and added the solution for this latest problem
0

You have a problem with your $conn variable. It only exists inside the functions where you use it. If you run Insert::connectDatabase() the value is set, but it is only usable inside this function. The Insert::post() function has a different variable scope and doesn't have access to the variables inside other functions.

You need to add this to your base class:

class Connection {
    private $conn;

// ... the rest of your class
}

Then you need to access it with $this->conn instead of $conn. That way you can use the variable in all functions inside your class.

Samples:

$this->conn = sqlsrv_connect( $serverName, $connectionInfo);
$stmt = sqlsrv_query($this->conn, $sql, $parameters);

2 Comments

Thank you @Gerald Schneider :) yey! my program runs.
I don't think it worked with private , did it? You need to set it to protected or public.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.