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条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么