php 使用 OOP 从 MySQL 中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6381250/
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
Fetch data from MySQL using OOP
提问by Mixin
I'm a beginner in OOP PHP. I'm trying to make a class that will connect,query and fetch data I done the below coding
我是 OOP PHP 的初学者。我正在尝试创建一个可以连接、查询和获取数据的类我完成了以下编码
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con= mysql_connect($this->host, $this->username, $this->password);
if(!$con){ die("Couldn't connect"); }
}
public function Database($set_database)
{
$this->database=$set_database;
mysql_select_db($this->database)or die("cannot select Dataabase");
}
public function Fetch($set_table_name){
$this->table_name=$set_table_name;
$query=mysql_query("SELECT * FROM ".$this->table_name);
$result= mysql_fetch_array($query);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
what I'm trying to achieve is this
我想要实现的是这个
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
and I want to fetch the data using a format like this
我想使用这样的格式获取数据
echo $result[0];
but I'm not getting that logic to make this happen please help
但我没有得到实现这一点的逻辑,请帮忙
Thanks!
谢谢!
回答by Fosco
Your Fetch
function is only pulling one row from the database, and you aren't returning the results...
您的Fetch
函数仅从数据库中提取一行,而您没有返回结果...
The method isn't the best, but in order to achieve what you're trying to do:
该方法不是最好的,但为了实现您想要做的事情:
public function Fetch($set_table_name){
$query=mysql_query("SELECT * FROM ".$set_table_name);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
This will make each row a part of $result, but you'll have to access it like this:
这将使每一行成为 $result 的一部分,但您必须像这样访问它:
You would call the fetch function like this:
您可以像这样调用 fetch 函数:
$result = $connect->Fetch('posts');
echo $result[0]['columnName']; // for row 0;
Or in a loop:
或者在一个循环中:
for ($x = 0; $x < count($result); $x++) {
echo $result[$x][0] . "<BR>"; // outputs the first column from every row
}
That said, fetching the entire result set into memory is not a great idea (some would say it's a very bad idea.)
也就是说,将整个结果集提取到内存中并不是一个好主意(有些人会说这是一个非常糟糕的主意。)
Edit: It also looks like you have other issues with your class... I have to run but will check back tomorrow and if others haven't set you straight I will expand.
编辑:看起来你的班级还有其他问题......我必须跑,但明天会回来检查,如果其他人没有让你直截了当,我会扩大。
Edit2: Ok, going to do a once-over on your class and try to explain a few things:
Edit2:好的,要对你的班级做一遍并尝试解释一些事情:
class MySQL {
//declaring the private variables that you will access through $this->variable;
private $host;
private $username;
private $password;
private $database;
private $conn; // Adding the connection, more on this later.
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// Combining the connection & connection check using 'or'
// Notice that I removed the semi-colon after the mysql_connect function
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function Database($set_database)
{
$this->database=$set_database;
// Adding the connection to the function allows you to have multiple
// different connections at the same time. Without it, it would use
// the most recent connection.
mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase");
}
public function Fetch($table_name){
// Adding the connection to the function and return the result object instead
return mysql_query("SELECT * FROM ".$table_name, $this->conn);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$posts = $connect->Fetch('posts');
if ($posts && mysql_num_rows($posts) > 0) {
echo "Here is some post data:<BR>";
while ($record = mysql_fetch_array($posts)) {
echo $record[0]; // or a quoted string column name instead of numerical index.
}
} else {
echo "No posts!";
}
I hope this helps... It should get you started at least. If you have more questions you should ask them separately.
我希望这会有所帮助......它至少应该让你开始。如果你有更多的问题,你应该单独问他们。
回答by khoomeister
That's because $result is set inside the Fetch function. It won't be available outside the Fetch function.
这是因为 $result 是在 Fetch 函数中设置的。它在 Fetch 函数之外不可用。
Instead of this line $result= mysql_fetch_array($query);
, you'll want something like return mysql_fetch_array($query);
.
而不是这一行$result= mysql_fetch_array($query);
,你会想要像return mysql_fetch_array($query);
.
And then in your code
然后在你的代码中
$row = $connect->Fetch('posts');
// do something with $row
On another note, your Fetch function only applies to database queries that return one row. You'll have to separate the mysql_query & mysql_fetch_array calls into another function if you want to loop through rows in a query result.
另一方面,您的 Fetch 函数仅适用于返回一行的数据库查询。如果要遍历查询结果中的行,则必须将 mysql_query 和 mysql_fetch_array 调用分离到另一个函数中。
And on another note, you shouldn't need to encapsulate this code into a class. PHP already provides OOP-based database classes called PDO, or PHP Data Objects. There's a learning curve to it, but it's best practice, and will help secure your code against things like SQL injection.
另一方面,您不需要将此代码封装到类中。PHP 已经提供了基于 OOP 的数据库类,称为 PDO,或 PHP 数据对象。它有一个学习曲线,但它是最佳实践,将有助于保护您的代码免受 SQL 注入等问题的影响。
This is a pretty good tutorial: http://www.giantflyingsaucer.com/blog/?p=2478
这是一个非常好的教程:http: //www.giantflyingsaucer.com/blog/?p= 2478
回答by Blake Basas
I would make a function that returns the value of the object.
我会创建一个返回对象值的函数。
public function returnData($data){
return $this->$data;
}
Then within the page you wish to get the data on just initiate the class and call the function within that class.
然后在页面中,您希望获取数据,只需启动类并调用该类中的函数即可。
$post->returnDate("row name here");
回答by Sahil Jangra
<?php
//database.php
class Databases{
public $con;
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "giit");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insert($table_name, $data)
{
$string = "INSERT INTO ".$table_name." (";
$string .= implode(",", array_keys($data)) . ') VALUES (';
$string .= "'" . implode("','", array_values($data)) . "')";
if(mysqli_query($this->con, $string))
{
return true;
}
else
{
echo mysqli_error($this->con);
}
}
public function selectmulti($selecttype,$table_name)
{
$array = array();
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
public function selectsingle($selecttype,$table_name)
{
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
$row = mysqli_fetch_assoc($result);
return $row;
}
}
?>
<?php
$data = new Databases;
$post_data = $data->selectmulti('*','centerdetail');
$n = 1;
foreach($post_data as $post)
{
echo $n.'.'.$post['CenterCode'].'___';
$n += 1;
}
echo '<br>';
$post_data = $data->selectsingle('*','centerdetail');
echo $post_data['CenterCode'];
?>