我试图通过调用函数和向方法添加$sql参数,在页面的任何地方创建一个类来进行查询。
一切都处于品尝阶段,所以我知道一些小问题,比如SQL注入,但这不是这里的主题。
在测试完课程之后,我对它进行了测试,但没有得到任何结果,我不知道为什么,因为事情对我来说很好,但我可能错过了一些有趣的东西。
我的PHP脚本:
<?php
class Query{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function connectAction(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
public function queryAction($sql){
mysqli_query($this->connectAction(),$sql);
//$count = mysqli_num_rows($query);
/*if($query == true && $count > 0){
}else{
}*/
}
}
$execute = new Query();我的第二个文件试图显示结果:
<html>
<head>
<title>
</title>
</head>
<body>
<h1>Welcome</h1>
<h3><?php
require_once('query.php');
$sql = 'SELECT * FROM tbl_user';
$execute->queryAction($sql);
foreach($execute as $item){
echo $item['user_pass'];
}
?></h3>
</body>
</html>有人能帮我吗?
发布于 2014-10-10 12:05:18
在对象中添加:
protected $results;在queryAction函数中,行更改为:
$this->results = mysqli_query($this->connectAction(),$sql);超过:
foreach ($execute->results as $result){}发布于 2014-10-10 12:02:00
试试这个..。
功能:
function select_rows($table,$fieldlist,$condition)
{
$sql="select $fieldlist from $table $condition ";
/// echo $sql;exit;
$resArray=$this->QueryResult($sql,'Select');
return ($resArray);
}//end function
//function for execute query
function QueryResult($sql,$PVal)
{
if($sql!=NULL)
{
//$rs=mysql_query($sql, $this->dblink) or die(mysql_error().':'.$PVal);
$rs=mysql_query($sql);
if(!$rs)
{
return $this->MysqlError($PVal);
}//end if
else
{
return $rs;
}//end else
}//end if
else
{
return '<b>MySQL Error</b>: Empty Query!';
}//end else
}//end function
//function for print error msg
function MysqlError($eVal)
{
if(mysql_error()!= '')
{
echo mysql_error().$eVal.;
}//end if
}//end funciton 用法:
$cond="condition";
$pass_select=$objA->select_rows(TABLEPREFIX.'tablename','fields',$cond);发布于 2014-10-10 12:12:20
试试这个:
public function connectAction()
{
if(!$this->con)
{
$this->con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
}
return $this->con;
}https://stackoverflow.com/questions/26298910
复制相似问题