使用方法建立连接的问题

时间:2013-07-27 12:00:38

标签: php

我尝试使用代码中的方法建立连接失败了。以前我根据我的代码使用了$ con变量。这使得连接似乎都没问题。 P.S我所有的道路都是正确的。

 <?php

$con = new dbmember();
$con->openDB();

//
// this WORKS but I want to use my function to do this for me instead
//$con=mysqli_connect("localhost","user","password","db_name");
//  
$user=$_POST['user']; 
$password=$_POST['password'];

if(isset($_POST['submit'])){


//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password'])) 
    {    

        $user = stripslashes($user);
        $password = stripslashes($password);
        $user = mysqli_real_escape_string($con, $user);
        $password = mysqli_real_escape_string($con, $password);

        //SQL Injection Ahoy! I know...but future versions aim to be robust!

$sql="SELECT * FROM users WHERE username='users' and password='password'";
$result=mysqli_query($con, $sql);

$row=mysqli_fetch_array($result);

if($row[0]==1)
{
    session_start();
    $_SESSION['user'] = $user;
    $_SESSION['password'] = $password;
    $_SESSION['loggedin'] = "true";
    header("location:index.php");
}
        else
        {
            print ('<div id="error">Acess denied, wrong username or password?</div>');
        }
        }
        else
            {
            print ('<div id="error">Enter something!</div>');
        }

}

    ?>

这是我的方法

<?php

require("assets/configs/db_config.php");

class dbmember {
    /* DB connection handle */

    var $conn;


  function openDB() {


// 1. Create a database connection
$conn = mysqli_connect("localhost" , "username", "password","db_name");
if (!$conn)
{
    $this->error_msg = "connection error could not connect to the database:! ";  
    return false;

给出错误:

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 98

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 99

Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 104

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\c\login.php on line 106

我只能假设$ con一定不能正确传递。你能提供解决方案吗?

1 个答案:

答案 0 :(得分:1)

而不是

$result=mysqli_query($con, $sql);

$result=mysqli_query($con->conn, $sql);

并更改

$conn = mysqli_connect("localhost" , "username", "password","db_name");
if (!$conn)
{

$this->conn = mysqli_connect("localhost" , "username", "password","db_name");
if (!$this->conn)
{
....