Hey everyone. I'm not a very good OO programmer but I'm really trying to learn 🙂 I'm new to OO programming AND prepared statements, so I'm fairly positive I'm just doing something lame wrong.
I'm having an issue trying to create a method in a Database class that uses PHP prepared statements to insert a user into a database. I'm assuming this is a syntax/logical error because when I made the method use mysqli_query($connection, $query) it ran fine, but when I tried to alter it to use prepared statements it doesn't 'break' anything, but the query never gets executed.
I'd really appreciate it if anyone could help point out where I went wrong! Here's the code:
class Database {
private $connection;
// CONSTRUCT FUNCTION
function __construct() {
$this->open_connection();
}
// OPEN_CONNETION FUNCTION
public function open_connection() {
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$this->connection) {
die("Database connection failed: " . mysqli_error());
}
}
// CREATE USER FUNCTION
public function createUser() {
$stmt = $this->connection->stmt_init();
$query = "INSERT INTO users values (?, ?, ?, ?, ?)";
if($stmt->prepare($query)) {
$stmt->bind_param('issss', null, $user_fname, $user_lname, $user_email, $user_status);
$user_fname = "Jane";
$user_lname = "Doe";
$user_email = "email@email.com";
$user_status = "a";
$stmt->execute();
$stmt->close();
}
}
}
And then, to run the function I have
$database = new Database();
$database->createUser();
After I get this to work I'm just going to alter the createUser() method to take the insert values as parameters.
Thanks!