I have a class in PHP and one of the methods needs to access a database.How do I correctly pass a database connection variable to a method? Does it get passed as a parameter through the constructor or method? Or is it something completely different?
Check the following updated answer. Tested and working.
<?php
class SomeClass
{
function setDb($servername, $username, $password, $database)
{
// Create the database connection and use this connection in your methods as $this->conn
$this->conn = new mysqli($servername, $username, $password, $database);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
echo "New successful connection to myDb \n";
}
public function createTable()
{
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($this->conn->query($sql) === TRUE) {
echo "New table created successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $this->conn->error;
}
}
public function normalInsertDb()
{
// sql to insert record using normal query
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($this->conn->query($sql) === TRUE) {
echo "New record inserted successfully using normal sql statement \n";
} else {
echo "Error: " . $sql . "<br>" . $this->conn->error;
}
}
public function preparedInsertDb()
{
// prepare and bind
$stmt = $this->conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records inserted successfully using PREPARED STATEMENTS \n";
$stmt->close();
$this->conn->close();
}
}
$obj = new SomeClass();
$obj->setDb('localhost', 'homestead', 'secret', 'myDb'); //we assume the database myDb exists
$obj->createTable();
$obj->normalInsertDb();
$obj->preparedInsertDb();
My Result: