当我在PHPmyadmin中运行此查询SELECT COUNT(ID) FROM blog_posts
时,它会返回我想要的数据库中的行数,但现在我希望使用{{success.php
页面显示此数字。 1}}下面。
到目前为止,我的代码是:
count method
Database.class.php
<?php
include 'config/config.php'; // Inlude the config file, this is where the database login info is stored in an array
class database {
private $dbc; // Define a variable for the database connection, it's visabiliatly is set to 'private' so only this class can access it
function __construct($dbConnection){
// Running the __construct() magic function,
// I am passing through a variable into the contruct method which when the object is created will hold the login details from the $dsn array in config.php
$this->dbc = $dbConnection; // This is saying that the variable $dbc now has the same value as $dbConnection ($dsn array)
$this->dbc = mysqli_connect($this->dbc['host'], $this->dbc['username'], $this->dbc['password'], $this->dbc['database']);
// ^ Running the mysqli_connect function to connect to the database.
if(mysqli_connect_errno()){ // If there is a problem connecting it will throw and error
die("Database connection failed" . mysqli_connect_error());
} else {
echo "allgood";
}
}
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
}
function count($countSQL){ // This is the method used for counting
mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
}
}
?>
Success.php
答案 0 :(得分:2)
实际上,在查询中添加别名要好得多:
$countSQL = "SELECT COUNT(ID) as total FROM blog_posts";
$result = $objdb->count($countSQL);
echo $result['total'];
然后,在你的方法上:
function count($countSQL){ // This is the method used for counting
$query = mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
$result = $query->fetch_assoc();
return $result;
}
其他信息:
在其他方法上放置返回值可能也不错。这样你就会知道它运作正常。
示例:
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
$query = mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
return $this->dbc->affected_rows;
}
所以在这里:
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$insert = $objdb->insert($insertSQL); // so that its easy to test if it indeed inserted
if($insert > 0) {
// hooray! inserted!
}