dpjo15650 2013-11-14 22:08
浏览 59
已采纳

如何在非面向对象的环境中使用PHP mysqli()

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?

  • 写回答

3条回答 默认 最新

  • ds0409 2013-11-14 22:13
    关注

    $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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器