简体   繁体   中英

How to use PHP mysqli() in a non-object oriented environment

I have the following connection file...

<?php
session_start(); 

// Create new mysql connection object
$DBConnect = @new mysqli("localhost","root","","Ladle");
?>

which I include in the following script...

<?php ob_start() ?>
<?php session_start() ?>
<?php
//Connects to the database
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;

// Get the e-mail address entered
$email = $_POST['user_email'];

$sql = $this->DBConnect->mysql_query("SELECT * FROM tblEmployees WHERE fldEmail='".
                            $email."'") or die(mysql_error());

$Result = mysql_fetch_assoc($sql);

//validate email fo valid maine account
if($Result)
{ ...

I tried running this but got an error of "Using $this when not in object context"; I just need to perform simple queries and don't want to deal with OO PHP but I have no choice now that mysql is deprecated. How can I reference the included connection file to run the SELECT query in this no OO file?

$this is a keyword reserved for Classes in PHP. Since you're running the queries in a procedural manner, there's no need for the $this-> prerequisite.

You can easily use the mysqli object inside your code as follows:

$DBConnect = new mysqli("localhost","root","","Ladle");

// Get the e-mail address entered
$email = $_POST['user_email'];

$sql = $DBConnect->query("SELECT * FROM tblEmployees WHERE fldEmail='".
                            $email."'");

$Result = $DBConnect->fetch_assoc($sql);

//validate email fo valid maine account
if($Result)
{ ...

For reference, using @ to surpass errors is a bad habit to get into. You should really handle errors using try { } catch() { } blocks.

Secondly, your code is vulnerable to SQL injection - so it might be wise for you to look into Prepared Statements .

Just because mysqli provides an OO interface, it doesn't mean that your code has to be written in OO style. You can just use ordinary functions and variables in your application.

$email = $DBConnect->real_escape_string($_POST['user_email']);

$sql = $DBConnect->query("SELECT * FROM tblEmployees WHERE fldEmail='".
                        $email."'") or die($DBConnect->error);

$Result = $sql->fetch_assoc();

You're mixing OO and functional calls, which is causing you confusion. The mysql_* functions are not the same as mysqli_* functions, so everywhere you have mysql_* is wrong.

Also, don't do this: DBConnect->mysql_query . DBConnect is an instance of MySQLi, so just call DBConnect->query .

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