问题
I'm trying to create a class which can be used for connecting to MySQL database. This is my code:
The class:
<?php
class createCon {
var $host = 'localhost';
var $user = 'root';
var $pass = '';
var $db = 'example';
var $myconn;
function connect() {
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
if (!$con) {
die('Could not connect to database!');
} else {
$this->myconn = $con;
echo 'Connection established!';}
return $this->myconn;
}
function close() {
mysqli_close($myconn);
echo 'Connection closed!';
}
}
And this is where I try to query the database:
<?php
include 'connect.php';
$connection = new createCon();
$connection->connect();
$query = 'SELECT * FROM `nickname`';
$result = mysqli_query($connection, $query);
if($numrows = mysqli_num_rows($result)) {
echo $numrows;
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['nick'];
$dbpassword = $row['pass'];
echo $dbusername;
echo $dbpassword;
}
}
I get the following error when I try to make a query:
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\wamp\www\uppgift 1 kompletering\test.php on line 13
回答1:
You want to pass in $connection->myconn
instead of $connection
. As in:
$result = mysqli_query($connection->myconn, $query);
As it stands, you're passing in an instance of your class, rather than a mysqli, which is what the error messages are complaining about.
回答2:
In database connection class you return connection. In PHP class you have to catch that connection variable
$connection = new createCon();
$conn = $connection->connect();
Then you can use that $conn
variable as a mysqli_query()
parameter like
$result = mysqli_query($conn, $query);
回答3:
I personally use mysqli_ext
from Wolf Software with some minor modifications. Their website no longer has it available for download however I have placed a copy of my site for you to download. It is licensed under the GPL so you can tinker with it. It might replace your class, or it might give you the info you need to get your class working!
Connection:
$sDB = new mysqli_ext($dbHost, $dbUser, $dbPass, $dbBase);
if ($sDB->connection_failed) {
/* Error */
}
Select Query:
$sDB->select("SELECT * FROM `albums` WHERE `listedtype` = 'PUBLIC' ORDER BY `createdon` LIMIT ?, ?", "ii", $aStart, $aAlbums);
Other Queries:
$sDB->execute_query("UPDATE `photos` SET `views` = `views` + 1 WHERE `picid` = ?", "s", $sPhoto);
Download from: http://www.tip2tail.co.uk/files/mysqli.class.zip
来源:https://stackoverflow.com/questions/21223278/mysqli-query-expects-parameter-1-to-be-mysqli-object-given