php PHP数据库连接类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3228694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:05:04  来源:igfitidea点击:

PHP database connection class

phpmysqlclass

提问by Odyss3us

I am trying to get a users ID from a database within a class, but I have very little to no experience with classes, how could I go about getting the uid from the DB and then return the uid?

我正在尝试从类中的数据库中获取用户 ID,但我对类的经验很少甚至没有,我该如何从数据库获取 uid 然后返回 uid?

so basically something like this,

所以基本上是这样的,

class hello {
   public function getUid(){
      //connect to the db
      //get all of the users info
      $array = mysql_fetch_array($result);
      $uid = $array['uid'];

      return $uid;
   }
}

Like I said, I am still new to classes, so any advice or help would be greatly appreciated!

就像我说的,我还是个新手,所以任何建议或帮助将不胜感激!

Thanx in advance!

提前谢谢!

回答by Jaison Justus

First build a MySQL class library... suiting the requirements like in this sample piece:

首先构建一个 MySQL 类库...适合本示例中的要求:

<?php

include '../config/Dbconfig.php';

class Mysql extends Dbconfig    {

public $connectionString;
public $dataSet;
private $sqlQuery;

    protected $databaseName;
    protected $hostName;
    protected $userName;
    protected $passCode;

function Mysql()    {
    $this -> connectionString = NULL;
    $this -> sqlQuery = NULL;
    $this -> dataSet = NULL;

            $dbPara = new Dbconfig();
            $this -> databaseName = $dbPara -> dbName;
            $this -> hostName = $dbPara -> serverName;
            $this -> userName = $dbPara -> userName;
            $this -> passCode = $dbPara ->passCode;
            $dbPara = NULL;
}

function dbConnect()    {
    $this -> connectionString = mysql_connect($this -> serverName,$this -> userName,$this -> passCode);
    mysql_select_db($this -> databaseName,$this -> connectionString);
    return $this -> connectionString;
}

function dbDisconnect() {
    $this -> connectionString = NULL;
    $this -> sqlQuery = NULL;
    $this -> dataSet = NULL;
            $this -> databaseName = NULL;
            $this -> hostName = NULL;
            $this -> userName = NULL;
            $this -> passCode = NULL;
}

function selectAll($tableName)  {
    $this -> sqlQuery = 'SELECT * FROM '.$this -> databaseName.'.'.$tableName;
    $this -> dataSet = mysql_query($this -> sqlQuery,$this -> connectionString);
            return $this -> dataSet;
}

function selectWhere($tableName,$rowName,$operator,$value,$valueType)   {
    $this -> sqlQuery = 'SELECT * FROM '.$tableName.' WHERE '.$rowName.' '.$operator.' ';
    if($valueType == 'int') {
        $this -> sqlQuery .= $value;
    }
    else if($valueType == 'char')   {
        $this -> sqlQuery .= "'".$value."'";
    }
    $this -> dataSet = mysql_query($this -> sqlQuery,$this -> connectionString);
    $this -> sqlQuery = NULL;
    return $this -> dataSet;
    #return $this -> sqlQuery;
}

function insertInto($tableName,$values) {
    $i = NULL;

    $this -> sqlQuery = 'INSERT INTO '.$tableName.' VALUES (';
    $i = 0;
    while($values[$i]["val"] != NULL && $values[$i]["type"] != NULL)    {
        if($values[$i]["type"] == "char")   {
            $this -> sqlQuery .= "'";
            $this -> sqlQuery .= $values[$i]["val"];
            $this -> sqlQuery .= "'";
        }
        else if($values[$i]["type"] == 'int')   {
            $this -> sqlQuery .= $values[$i]["val"];
        }
        $i++;
        if($values[$i]["val"] != NULL)  {
            $this -> sqlQuery .= ',';
        }
    }
    $this -> sqlQuery .= ')';
            #echo $this -> sqlQuery;
    mysql_query($this -> sqlQuery,$this ->connectionString);
            return $this -> sqlQuery;
    #$this -> sqlQuery = NULL;
}

function selectFreeRun($query)  {
    $this -> dataSet = mysql_query($query,$this -> connectionString);
    return $this -> dataSet;
}

function freeRun($query)    {
    return mysql_query($query,$this -> connectionString);
  }
}
?>

and the configuration file...

和配置文件...

<?php
class Dbconfig {
    protected $serverName;
    protected $userName;
    protected $passCode;
    protected $dbName;

    function Dbconfig() {
        $this -> serverName = 'localhost';
        $this -> userName = 'root';
        $this -> passCode = 'pass';
        $this -> dbName = 'dbase';
    }
}
?>

回答by gblazex

Alright, one piece of advice:

好吧,给一个建议:

Do everything for a reason. Don't use things you don't know. Go and learn them instead.

做任何事都是有原因的。不要使用你不知道的东西。去学习它们吧。

One may give you an answer for this specific question, but until you don't know what Object Orientedmeans and why there are classesat all, you shouldn't use them.

对于这个特定的问题,您可能会给出答案,但是在您不知道面向对象的含义以及为什么存在类之前,您不应该使用它们。

回答by rashedcs

You can use custom database class.
Code :

您可以使用自定义数据库类。
代码 :

<?php 
Class Database
{
    private $user ;
    private $host;
    private $pass ;
    private $db;

    public function __construct()
    {
        $this->user = "root";
        $this->host = "localhost";
        $this->pass = "";
        $this->db = "db_blog";
    }
    public function connect()
    {
        $link = mysql_connect($this->user, $this->host, $this->pass, $this->db);
        return $link;
    }
}
?>

回答by Anax

There is a problem with the way your code is written, not with the class. Take a closer look at this line:

你的代码的编写方式有问题,而不是类。仔细看看这条线:

$array = mysql_fetch_array($result);

This is the first time variable $resultappears on the function. Therefore, it is not possible to communicate with the database.

这是变量第一次$result出现在函数上。因此,无法与数据库进行通信。

A possible pseudo-code would be:

一个可能的伪代码是:

  • connect to the DB server
  • query the database
  • fetch the results
  • return the uidfield.
  • 连接到数据库服务器
  • 查询数据库
  • 获取结果
  • 返回uid字段。

Have a look at the relevant documentation first:

先看看相关文档:

回答by dwich

  • Create two classes. One for working with database, second one for managing User or Auth data.
  • For SQL class create methods connect(), query(), fetch() etc
  • For User class create methods get($id) etc
  • 创建两个类。一个用于处理数据库,第二个用于管理用户或身份验证数据。
  • 对于 SQL 类创建方法 connect()、query()、fetch() 等
  • 对于用户类创建方法 get($id) 等

回答by Patel

Try following:

尝试以下操作:

ini_set("display_errors", 'off');
    ini_set("error_reporting",E_ALL);   

class myclass {
    function myclass()   {    
        $user = "root";
        $pass = "";
        $server = "localhost";
        $dbase = "";

           $conn = mysql_connect($server,$user,$pass);
           if(!$conn)
        {
            $this->error("Connection attempt failed");
        }
        if(!mysql_select_db($dbase,$conn))
        {
            $this->error("Dbase Select failed");
        }
        $this->CONN = $conn;
        return true;
    }
    function close()   {   
        $conn = $this->CONN ;
        $close = mysql_close($conn);
        if(!$close)
        {
            $this->error("Connection close failed");
        }
        return true;
    }       function sql_query($sql="")   {    
        if(empty($sql))
        {
            return false;
        }
        if(empty($this->CONN))
        {
            return false;
        }
        $conn = $this->CONN;
        $results = mysql_query($sql,$conn) or die("Query Failed..<hr>" . mysql_error());
        if(!$results)
        {   
            $message = "Bad Query !";
            $this->error($message);
            return false;
        }
        if(!(eregi("^select",$sql) || eregi("^show",$sql)))
        {
            return true;
        }
        else
        {
            $count = 0;
            $data = array();
            while($row = mysql_fetch_array($results))
            {
                $data[$count] = $row;
                $count++;
            }
            mysql_free_result($results);
            return $data;
         }
    }      
} 
$obj = new myclass();
$obj->sql_query("");