如何将我的每个数据库字段变成php中的公共变量?

时间:2017-11-13 16:43:05

标签: php html mysql

我通过执行此查询获得了我的所有数据库字段

"SHOW  COLUMNS FROM admin"

但我想知道如何将每个人变成一个公共变量! 是的,这些变量将在一个类中,因为我正在做OO PHP。

首先,我需要从我的数据库中获取所有字段名称。然后我需要把它们放到一个类的变量中。

2 个答案:

答案 0 :(得分:1)

这是您使用PDO连接数据库和执行查询的方式:

try{
            $db_host = '...';  //  hostname
            $db_name = '...';  //  databasename
            $db_user = '...';  //  username
            $user_pw = '...';  //  password
            $pdo = new PDO("mysql:host=".$db_host.";dbname=".$db_name, $db_user, $user_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            //---------------------- QUERY -----------------------
            $sql = "insert your query here";
            //----------------------END QUERY -----------------------

            $data = $pdo->query($sql);
            //the next lines will convert the query results to an array 
            //containing the contents as single variables
            $return = array();
            foreach($data as $row){
                $data = $row[0];
                array_push($return, $row);
            }
            return $return;
        }catch(PDOException $erro){
            echo $erro->getMessage();
        }
    }

$return变量将是查询返回的每一行的数组,然后您可以将其作为单个变量访问。

答案 1 :(得分:1)

您不需要像这样预定义列名,以便将数据库行作为对象访问。

假设您有established a PDO connection $pdo,您可以针对表执行select查询,并使用与表中列名对应的公共属性名称return your results as objects

$stmt = $pdo->query('SELECT * FROM admin');
while ($row = $stmt->fetchObject()) {
    // each $row is an object with public properties matching the column names
    // so you can do things with $row->column_a, etc.
    // (obviously I don't know your actual column names)
}

mysqli非常相似:

$result = $mysqli->query('SELECT * FROM admin');
while ($row = $result->fetch_object()) { // ... }