简体   繁体   English

MySQL选择oop PHP

[英]mysql select oop php

This is my oop php code for connection for my database. 这是我的数据库连接的oop php代码。 But how can i do the SELECT function. 但是我该怎么做SELECT功能。 i wanna show data in my page from database. 我想在数据库中的页面上显示数据。 help me with this 帮我这个

class createConnection //create a class for make connection
{
    var $host = "localhost";
    var $username = "root"; // specify the sever details for mysql
    var $password = "";
    var $database = "akpGroup";
    var $myconn;

    function connectToDatabase() // create a function for connect database
    {
        $conn = mysql_connect($this->host, $this->username, $this->password);
        if (!$conn) // testing the connection
        {
            die ("Cannot connect to the database");
        } else {
            $this->myconn = $conn;
            echo "Connection established";
        }

        return $this->myconn;
    }

    function selectDatabase() // selecting the database.
    {
        mysql_select_db($this->database); //use php inbuild functions for select database
        if (mysql_error()) // if error occured display the error message
        {
            echo "Cannot find the database " . $this->database;
        }
        echo "Database selected..";
    }

    function closeConnection() // close the connection
    {
        mysql_close($this->myconn);
        echo "Connection closed";
    }

May be something like this 可能是这样的

$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT column FROM tablename';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);

First of all consider using mylsqi_ or PDO functions. 首先考虑使用mylsqi_或PDO函数。

Basically your function for querying should look something like the one below. 基本上,您的查询功能应类似于以下内容。 It makes query and puts all the results into an array. 它进行查询并将所有结果放入数组中。

You can return the array or assign it to a class variable like you did in other methods. 您可以像在其他方法中一样返回数组或将其分配给类变量。

  function query($sql) {
        $result_array = array();
        $query = mysql_query($sql);
        if(mysql_affected_rows() > 0) {
              while($fetch = mysql_fetch_assoc($query)) {
                    $result_array[] = $fetch;
              }
        }
        else {
              //no results action if needed
        }

        return $result_array;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM