i have a php site
in index file include connect to db function :
function connect(){
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("database");
}
and i use this function in everywhere i need connection
for example:
<?php
connect();
$lastnews_sql = mysql_query("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
if(mysql_num_rows($lastnews_sql)) {
while($Result123 = mysql_fetch_object($lastnews_sql)) {
?>
and use this selection:
text; ?>
in end of using :
<?php
}
}
mysql_close();
?>
there are more than 10 connect(); and mysql_close(); in index file
so there are too many connection error in index file
how can i optimize this metod ?
A singleton pattern seems to suit this down to the ground.
class Database
{
private static $instance;
public function getInstance()
{
if(self::$instance == null)
{
// Create a connection to the database.
// NOTE: Use PDO or mysqli. mysql is deprecated.
}
return self::$instance;
}
}
Use
In your classes, instead of calling connect, assuming you're using a PDO object, you could do something like:
$db = Database::getInstance();
$statement = $db->prepare("SELECT * FROM tblName WHERE val = :val");
$statement->bindParam(":val", $value);
$statement->execute();
$result = $statement->fetchAll();
Why this pattern ?
A Singleton pattern has the advantage of only having one instance of itself exist at one time. That means that you will only ever create one connection to the database.
Setting this up
Okay, so the first thing you want to do is to make a new file, let's call it Database.php. Inside Database.php, you want to pretty much write the code that I've written, only do NOT use mysql_*. Have a look at the PDO tutorial that I have provided, on how to connect to a database using a PDO object, and then you put that connection code inside the if statement, so it might look something like:
if(self::$instance == null)
{
self::$instance = new PDO('mssql:host=sqlserver;dbname=database', 'username', 'password');
}
Then, to use it in another class, put a require statement at the top. Something like:
require_once('Database.php');
Finally, look at the code I put in the use section, above. That is how you use it in your class.
Useful links
PDO Tutorial : http://php.net/manual/en/book.pdo.php
Singleton Pattern : http://www.oodesign.com/singleton-pattern.html
Related
hoping someone can help me, I am having the following error, looked online and tried a load of things but can't seem to figure it out, error:
Fatal error: Call to undefined method mysqli::mysqli_fetch_all() in C:\xampp\htdocs\cyberglide\core-class.php on line 38
heres my code:
<?php
class Core {
function db_connect() {
global $db_username;
global $db_password;
global $db_host;
global $db_database;
static $conn;
$conn = new mysqli($db_host, $db_username, $db_password, $db_database);
if ($conn->connect_error) {
return '<h1>'."Opps there seems to be a problem!".'</h1>'.'<p>'."Your Config file is not setup correctly.".'</p>';
}
return $conn;
}
function db_content() {
//this requires a get, update and delete sections, before its complete
$conn = $this->db_connect();
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM content";
// Escape Query
$query = $conn->real_escape_string($query);
// Execute Query
if($result = $conn->query($query)){
// Cycle through results
while($row = $conn->mysqli_fetch_all()){
//echo $row->column;
}
}
}
}
$core = new Core();
?>
I am trying to create a db_connect function, which I want to be able to call anywhere on the site that needs a database connection, I am trying to call that function on a function within the same class, I want it to grab and display the results from the database. I am running PHP 5.4.7, I am calling the database on a blank php file which includes a require to include the class file, then using this at the moment $core->db_content(); to test the function. I am building this application from scratch, running from MySQLi guides (not used MySQLi before, used to use normal MySQL query's) so if I am doing anything wrong please let me know, thanks everyone.
mysqli_fetch_all is a method of a mysqli_result, not mysqli.
So presumably it should be $result->fetch_all()
References:
http://php.net/manual/en/mysqli-result.fetch-all.php
Important: keep in mind mysqli_result::fetch_all returns the whole result set not a row as you assume in your code
There are three problems I see here.
while($row = $conn->mysqli_fetch_all()){
The method name is fetch_all() when used in the OOP way.
fetch_all() should be used with the $result object
fetch_all() is only available when the mysqlnd driver is installed - it frequently is not.
Reference
Only $result has that method. If you want to use it in a while loop use fetch_assoc(). fetch_all() returns an associative array with all the data already.
while($row = $result->fetch_assoc()){
}
thanks all, its working fine now, i had it as while($row = $conn->fetch_assoc()){
} before and changed to what i put above, but dident see it should of been $result instead of $conn, thanks for pointing that out.
I've been using PHP procedurally for years, but I've decided to really get with the times and start practicing OOP.
Suppose I have something like the following:
<?php
$db = new mysqli(host, user, pass, db);
class user {
public $username;
public function __construct($ID) {
$sql_query = "SELECT `username` FROM `users` WHERE `userid`='$ID'";
// execute that query somehow, store result in $result.
$this->username = $result;
}
}
$some_user = new user(1);
(I know that query needs to be escaped etc, I'm just trying to give a basic example)
My main question is what's the best way to interact with the $db object within a class? I would call $db->query($sql_query); but $db is not accessible. A lot of Googling hasn't given me a solid answer, but I've seen a lot of suggestions to pass in the $db object into the constructer, like:
$some_user = new user(1, $db);
Am I right in understanding this as "Data Injection"? It seems like there must be a better way than to explicitly include it in every single constructor. Of course I could always create $db within each class but repeatedly connecting to the database also seems unnecessary.
//this seems to happen in the global scope, so $db isn't accessible in class user yet
$db = new mysqli(host, user, pass, db);
class user {
public $username;
//to make global $db accessible, pass a reference to user's constructor:
public function __construct($ID,&$db) {
$sql_query = "SELECT `username` FROM `users` WHERE `userid`='$ID'";
// execute that query somehow, store result in $result
// if you exec the query, first you get a mysqli result *OBJECT*:
$result_obj = $db -> query($sql_query);
// next you pull out the row out of this object as an associative array:
$row = $result_obj -> fetch_assoc();
//finally you assign the retrieved value as a property of your user:
$this->username = $row['username'];
}
}
//be careful NOT to pass a reference here!!
$some_user = new user(1,$db); // NO ampersand here! passing by ref is deprecated!
i am trying to use PDO in php using classes.
so i have defined one config file like that
<?php
global $configVars;
$configVars['online'] = false;
if(($_SERVER['SERVER_NAME'])!='localhost' and ($_SERVER['SERVER_NAME'])!='abc')
{
$configVars['dbhost'] = "localhost";
$configVars['dbuser'] = "dbuser";
$configVars['dbpassword'] = "dbpass";
$configVars['dbname'] = "dbname";
}
?>
then i have defined class to connect the database
<?php
class dbClass{
var $dbHost,
$dbUser,
$dbName,
$dbPass,
$dbTable,
$dbLink,
$resResult,
$dbh,
$dbPort;
function dbClass(){
global $configVars;
$this->dbHost = $configVars['dbhost'];
$this->dbUser = $configVars['dbuser'];
$this->dbPass = $configVars['dbpassword'];
$this->dbName = $configVars['dbname'];
$this->connect_PDO();
}
function connect_PDO(){
try {
$dbh = new PDO('mysql:host='.$this->dbHost.';dbname='.$this->dbName.'', $this->dbUser, $this->dbPass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected.";
}
catch(PDOException $e) {
echo "I'm sorry Charlie, I'm afraid i cant do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
$dbh = null;
}
}
}
?>
now i have defined another class to select the records from table
<?
class cms extends dbClass
{
function get_rec($id=0)
{
($id==0?$addQuery="":$addQuery=" where id =".$id);
$statement = $dbh->prepare("select * from TABLENAME :name order by id");
$statement->execute(array(':name' => $addQuery));
$row = $statement->fetchAll();
return $row ;
}
}
?>
now when i am using this function in my PHP file like this
<?php
$objCMS=new cms();
$getCMS=$objCMS->get_rec(1);
echo $getCMS[0];
?>
i got following out put
Connected.
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs
i am trying to sort this out from last 2 days but no success.
i am new to PDO and want to use it.
Thanks
You $dbh is declared in the base class but without a specific scope I think it's going to default to 'private'. Hence not visible in the sub class.
Also you aren't calling the constructor. Add a call to 'parent::__construct()' in your sub class. http://php.net/manual/en/language.oop5.decon.php
You are going in wrong direction about solving this one.
If you want to give some object access to database, then that object needs access to database object that provides methods to interact with the database. You got that right.
But, inheritance is "IS A" relationship. And your CMS object is not a database type of object, and doesn't have same function as database object right? CMS object should just use Database and this is called composition. This relationship is also called "HAS A" relationship.
So instead of using Inheritance here, you should use Composition like this:
class CMS
{
protected $db;
// other CMS related stuff
}
$db = new PDO($dsn, $username, $password, $options);
$cms = new User($db);
This way your CMS can use database without using inheritance.
Google about composition vs. inheritance and when to use it.
Also take a look at this answer here:
PHP Mysqli Extension Warning
And read this article and go through examples to understand why
composition is a way to go when providing some class a way to
interact with database.
I know this is not an answer to your question, but you have gone in the wrong direction to solve your problems. I see lots of people use only inheritance so just be aware that there is much more then inheritance to make your objects interact. And in this situation, its just wrong to use Inheritance since your CMS object has nothing to do with Database, they are not the same "type". CMS should only use Database.
Hope this helps!
You need to call dbClass() in your constructor for cms
add this to the cms class
function cms() {
parent::dbClass();
}
and change get_rec to have:
$statement = $this->dbh->prepare("select * from TABLENAME :name order by id");
when using $dbh you need to reference it as $this->dbh
You need to make the $dbh to $this->dbh changes in you need to update connect_PDO() also
I have this php file. The lines marked as bold are showing up the error :"mysql_query() expecets parameter 2 to be a resources. Well, the similar syntax on the line on which I have commented 'No error??' is working just fine.
function checkAnswer($answerEntered,$quesId)
{
//This functions checks whether answer to question having ques_id = $quesId is satisfied by $answerEntered or not
$sql2="SELECT keywords FROM quiz1 WHERE ques_id=$quesId";
**$result2=mysql_query($sql2,$conn);**
$keywords=explode(mysql_result($result2,0));
$matches=false;
foreach($keywords as $currentKeyword)
{
if(strcasecmp($currentKeyword,$answerEntered)==0)
{
$matches=true;
}
}
return $matches;
}
$sql="SELECT answers FROM user_info WHERE user_id = $_SESSION[user_id]";
$result=mysql_query($sql,$conn); // No error??
$answerText=mysql_result($result,0);
//Retrieve answers entered by the user
$answerText=str_replace('<','',$answerText);
$answerText=str_replace('>',',',$answerText);
$answerText=substr($answerText,0,(strlen($answerText)-1));
$answers=explode(",",$answerText);
//Get the questions that have been assigned to the user.
$sql1="SELECT questions FROM user_info WHERE user_id = $_SESSION[user_id]";
**$result1=mysql_query($sql1,$conn);**
$quesIdList=mysql_result($result1,0);
$quesIdList=substr($quesIdList,0,(strlen($quesIdList)-1));
$quesIdArray=explode(",",$quesIdList);
$reportCard="";
$i=0;
foreach($quesIdArray as $currentQuesId)
{
$answerEnteredByUser=$answers[$i];
if(checkAnswer($answerEnteredByUser,$currentQuesId))
{
$reportCard=$reportCard+"1";
}
else
{
$reportCard=$reportCard+"0";
}
$i++;
}
echo $reportCard;
?>
Here is the file connect.php. It is working just fine for other PHP documents.
<?php
$conn= mysql_connect("localhost","root","password");
mysql_select_db("quiz",$conn);
?>
$result2=mysql_query($sql2,$conn);
$conn is not defined in the scope of your function (even if you're including the connect.php file before that.
although you can use the suggestion to make $conn global, it's usually better practice to not make something global just for the sake of globalizing it.
i would instead pass $conn to the function as a parameter. this way, you can reuse the same function you wrote with different connections.
$conn isn't declared as a global so the function cannot access it, as it is not defined within it.
Either simply add
global $conn;
To the top of the function to allow it to access the $conn.
Or you can remove $conn from the mysql_query() statement. By default it will use the current connection (as mentioned in the comments below).
Where do you set $conn? It doesn't look like you set a connection within that function
I'm having some issues using mysqli to execute a script with SELECT,DELETE,INSERT and UPDATE querys. They work when using norm mysql such as mysql_connect but im getting strange results when using mysqli. It works fine with a lot of the SELECT querys in other scripts but when it comes to some admin stuff it messes up.
Its difficult to explain without attaching the whole script.
This is the function for modifying...
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $databaseUsername;
global $databasePassword;
global $databaseDebugMode;
$link = #mysql_connect($databaseServer,$databaseUsername,$databasePassword);
#mysql_select_db($databaseName,$link);
$result = mysql_query($sql,$link);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysql_error()."]";
}
$insertId = mysql_insert_id();
return mysql_affected_rows();
}
and heres what I changed it to for mysqli
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $dbUser_feedadmin;
global $dbUser_feedadmin_pw;
global $databaseDebugMode;
$link = #mysqli_connect($databaseServer,$dbUser_feedadmin,$dbUser_feedadmin_pw,$databaseName);
$result = mysqli_query($link, $sql);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysqli_error()."]";
}
$insertId = mysqli_insert_id();
return mysqli_affected_rows();
}
Does that look right?
It isn't actually producing an error but its not functioning in the same way as when using mysql. any ideas?
Here is the way I normally use Mysqli
$mysqli = new mysqli($myServer, $myUser, $myPass, $myDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
$result = $mysqli->query($query);
while ($row=$result->fetch_assoc()) {
print_r($row);
}
Note: mysqli is a class, $mysqli is the variable that holds the instance of that class, query is a method of that class that returns a result class that has methods of its own.
You are running all statements at once as far as php is concerned, so functions like affected rows or last inserted id will not work as expected.
(Correct me if I'm wrong I haven't been using mysqli for a while.)
some of the mySqli functions needed some tinkering such as including $link