简体   繁体   中英

How to run MYSQL query using OOP in PHP?

I'm a beginner in PHP OOP. I know about basic OOP using PHP. Now I wanted to create a simple form submit code using OOP. I want to save a name in database. But I don't know what to write for first parameter in mysqli_query

Here's my code:

<?php
class dbConnect{
    private $host="localhost";
    private $user="root";
    private $pass="";
    private $db="oodb";
    public function Connect(){
        $conn=mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if($conn){
            echo "Connected";
        }
    }
}
$dbConn=new dbConnect();
$dbConn->Connect();
class Signup{
    public function Insert($value){
        if(isset($_REQUEST["sub"])){
            $query="INSERT INTO signup(name) VALUES('$value')";
            //FOLLING STATEMENT IS INCORRECT
            $queryrun=mysqli_query($dbConn->Connect(), $query);
            echo "Inserted";
        }
        else{
            echo "Error";
        }
    }
}
$sign=new Signup();
if(isset($_POST['id'])){
$sign->Insert($_POST['id']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form name="form1" method="post">
    <input type="text" name="id">
    <input type="submit" name="sub">
</form>
</body>
</html>

Also, could you please tell me if I'm using OOP in a right way not? I think there are many mistakes.

The problem is that you are not passing along the connection to the query. This is fixed by return -ing it in the Connect method and the passing it along to the Insert method.

This would change your code to

<?php
class dbConnect{
    private $host="localhost";
    private $user="root";
    private $pass="";
    private $db="oodb";
    public function Connect(){
        $conn=mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if($conn){
            echo "Connected";
        }

        return $conn;
    }
}
$dbConn=new dbConnect();
$conn = $dbConn->Connect();
class Signup{
    public function Insert($conn, $value){
        if(isset($_REQUEST["sub"])){
            $query="INSERT INTO signup(name) VALUES('$value')";
            //FOLLING STATEMENT IS NOW CORRECT
            $queryrun=mysqli_query($conn, $query);
            echo "Inserted";
        }
        else{
            echo "Error";
        }
    }
}
$sign=new Signup();
if(isset($_POST['id'])){
$sign->Insert($conn, $_POST['id']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form name="form1" method="post">
    <input type="text" name="id">
    <input type="submit" name="sub">
</form>
</body>
</html>

But I agree with Nikola, that you should take a look at PDO. It's the object-oriented approach.

As for the quality - I suggest you read some introduction to OOP, because using classes is not writing OOP :)

EDIT: I updated to code to pass the connection along.

Cheers, Mike

In order to understand what the parameter should be like, you need to be aware of how prepared statements work . Please, read the linked article.

Here's a quick example:

$db = 'oodb';
$host = 'localhost';
$username = 'root';
$password = '';

$dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host);
$pdo = new PDO($dsn, $username, $password);

$statement = $pdo->prepare('INSERT INTO signup(name) VALUES(:name)');

$statement->execute(array(
    'name' => $name,
));

Here's your code adapted to run using this simple example:

<?php

// configuration parameters
$db = 'oodb';
$host = 'localhost';
$username = 'root';
$password = '';
$dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host);


// classes
class SignUp
{
    /**
     * @var PDO
     */
    protected $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function insert($name)
    {
        $statement = $pdo->prepare('INSERT INTO signup(name) VALUES(:name)');

        $statement->execute(array(
            'name' => $name,
        ));
    }
}

// actual program flow
$pdo = new PDO($dsn, $username, $password);
$signUp = new SignUp($pdo);

if (array_key_exists('id', $_POST)) {
    $signUp->insert($_POST['id']);

    echo 'inserted';
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form name="form1" method="post">
    <input type="text" name="id">
    <input type="submit" name="sub">
</form>
</body>
</html>

As for your question whether you are doing PHP OOP the right way, my answer would be a solid NO.

OOP stands for Object-Oriented Programming . It is about different objects interacting with one another. The code you have done has one class that wraps a function. That's a class, not OOP.

Getting into OOP can get frustrating at first, so buckle up and be sure to read more on the topic. Remember that no one is born with experience.

I see what the issue is, try making these changes:

$dbConn=new dbConnect();
$conn = $dbConn->Connect();

And then try again with this:

$queryrun = mysqli_query($conn, $query) ;

All you needed to do was use the right instance to the mysqli_query() method.

Also, please make sure you return $conn in the 'connect()' method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM