Similar questions to this my have been asked a lot of times before. But since I did not find a solution in any of the questions asked before me, I take the liberty of asking it again.
My program uses a class made by me which handles all database connections for the program. Several modules I've used before used the same class without fail but when I chose to do a new module using the same class, the warning shows as-
Warning: mysql_query(): 7 is not a valid MySQL-Link resource in wherever... on line 49.
The warning happens when I execute a MySQL query through a function I made. The function is as follows-
public function runquery($_query)
{
$result = mysql_query($_query,$this -> connection); //line 49
if (! $result) die(mysql_error());
else return $result;
}
The function belongs to a class named mysql and it has not been tampered with or made changes to. So the function should technically work as expected, as every other module relying on the same class for database connectivity works just fine.
The query execution is successful however and I manage to update tables with no problems (except the warning). The block of code in the main program where the runquery() function is called from is as follows-
$phpmyadmin = new mysql();
$phpmyadmin->connect('localhost', 'root', '');
$phpmyadmin->setdb('test_db');
$result = $phpmyadmin->runquery($Query);
unset($phpmyadmin);
So the mysql's functions work just as fine as ever and the query executes just fine. But the warning shows for a reason I cannot understand. Any help?
The symptoms suggest that the database connection has been closed or dropped. Look for unwanted mysql_close() calls in your code. Additionally, you can use the following functions to troubleshoot the issue:
is_resource() and get_resource_type() to confirm that $this->connection is a valid data type.
mysql_ping() to find out if the database connection is alive.
If it's a rare issue, log stuff into a file and wait until it happens again.
There should not be spaces.
$result = mysql_query($_query,$this->connection);
Related
I'm writing a simple blogging web app for my portfolio and I've come across this strange problem. I wrote a PHP script to connect to a database and read and write data to a database by RESTful calls.
I've done this before in other programs with no problems, but in this one I get an error. I wrote a simple test page to check that the RESTful calls would work before I started using them in my main app. Instead of working, I got an error back from my PHP script.
The error goes like this:
Warning: mysqli_connect() [function.mysqli-connect]: (HY000/2002): Can't connect to local MySQL server through socket '/No-MySQL-hostname-was-specified' (2) in /home/releesquirrel/storage.electricsquirrel.net/SimpleBlog/php/model_SimpleBlog.php on line 35
The code leading up to line 35 goes like this:
class model_SimpleBlog {
// Properties
// Database Info
private $serverName = "mysql.electricsquirrel.net";
private $userName = "esqrl_client";
private $userPassword = "fakepassword";
private $dbaseName = "esquirrel_simpleblog";
// Methods
public function model_SimpleBlog() {
//
}
// Load the ten latest entries after an offset
public function loadEntries($offset) {
$result = false;
// Connect to the Database Server
$connection = mysqli_connect($serverName, $userName, $userPassword, $dbaseName);
I've changed the password for privacy but that's the code that's throwing the error. I'm completely stumped. I've used code similar to this with no problems before, and I've tried googling the error code with no luck.
Does anybody know why I'm getting this error and what I can do to fix my code?
In PHP, you need to refer to object variables with $this->:
$connection = mysqli_connect($this->serverName, $this->userName, $this->userPassword, $this->dbaseName);
$serverName, for instance, looks for a variable with that name in the scope of the function. Obviously none exists.
See the manual for more information on PHP object properties.
I am developing an agent-port application in CodeIgniter with PostgreSQL by using mutiple schemas from a single database. The setup I have designed is working fine.
So the problem I am facing right now is when after some interval it starts showing the following errors on different pages, like:
Fatal error: Call to a member function result() on a non-object in
D:\xampp\htdocs\mangonet\application\modules\settings\models\adminmodel.php
on line 30
Fatal error: Call to a member function num_rows() on a non-object in
D:\xampp\htdocs\mangonet\application\modules\users\models\adminmodel.php
on line 56
Fatal error: Call to a member function row() on a non-object in
D:\xampp\htdocs\mangonet\application\modules\users\models\adminmodel.php
on line 86
Let me give one example
I try to find out a particular problem only if it always remains there. But when I refresh my page or remove that row() from the function
function get_item_by_id($table, $id)
{
return $this->db->get_where($table, array('id' => $id))->row();
}
it returns a black result and when I add it back, the problem gone, and it starts working fine.
I know the above fatal errors you can see above solutions are available. But my problem is a bit complex.
This sounds like a problem with database connections going away. I would recommend looking at debugging this on the application side. In particular I would start logging the following:
Database connection status on all problematic calls. In other words check and see if the database connection has closed or failed.
If the database connection has not failed, then the next thing to check is what the search path is. You can execute the following query to test it:
SHOW search_path;
It is possible that if this is related to multiple schemas, something is messing with that.
I'm currently developing an application in PHP which uses PDO. I'm writing an import which reads in a CSV file, checks the database for a record, and updates, deletes, etc....
Something which I've noticed is the memory being used by this script seems very high and it seems like it could be to do with the way I'm executing the query. see below for example query which is executed for each line in the CSV:
$qry = "SELECT * FROM company WHERE id = 1";
$sth = $this->prepare($qry);
$sth->execute();
$sth->setFetchMode(PDO::FETCH_INTO, new Company());
$sth->fetch();
for the above memory_get_peak_usage() = 6291456
When using the below:
$qry = "SELECT * FROM company WHERE id = 1";
$sth = $this->prepare($qry);
$sth->execute();
$sth->setFetchMode(PDO::FETCH_CLASS, "Company");
$sth->fetch();
for the above memory_get_peak_usage() = 524288
As you can see the difference is fairly big.
I guess I've 3 questions..
Is there a memory leak when using PDO::FETCH_OBJ in PHP 5.3.5?
Is there any difference between using FETCH_CLASS as opposed to FETCH_OBJ?
Has anyone else experienced the same issue?
Company Class is simple:
class Company {
function __construct(){}
/**classvars**/
public $_tablename = 'company';
public $transient;
public $id;
public $name;
/**endclassvars**/
}
Looking at the PHP changelog, there does appear to be a relevant fix in 5.3.4 where a memory leak was fixed in PDO FETCH_INTO.
From what you've said, I suspect that yes, this is the bug you're seeing. The solution, of course, is to upgrade -- there really is no point in sticking with an old patch release.
Even if this isn't the bug you're seeing, there have been a very large number of PDO fixes in the versions between 5.3.3 and now; I'm sure there's a good chance that at least some of them are relevant to you.
Note: the original answer was given before the OP changed PDO::FETCH_OBJ to PDO::FETCH_INTO
After that update I've tried to reproduce the behaviour using PHP 5.3.10-1ubuntu3.4. There where no significant difference in memory cosumption between both fetch modes. I've tested using a large MySQL table and a large SQLite database.
As #SDC mentioned the bug is known and was fixed after 5.3.5. (At least in 5.3.10 as I've seen).
Conclusion: You have to upgrade your PHP version.
Although the behaviour is interesting and should be investigated you are using PDO::setFetchMode() in a wrong way. When $mode - the first param - is PDO::FETCH_OBJ no second param is expected. If you use a second param the call to setFetchMode() will fail (returnin false) and the default fetch mode FETCH_BOTH will be used.
You can see this error when enabling PDO::ERRMODE_EXCEPTION :
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->query('....');
// the following line will trigger an exception
$stmt->setFetchMode(PDO::FETCH_OBJ, new Company());
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: fetch mode doesn't allow any extra arguments'
When you are expecting that result rows should objects of a specific class, then PDO::FETCH_CLASS is the working attempt. PDO::FETCH_OBJ will return objects from type StdClass
FETCH_INTO: Means fetching into an existing Object (that was created with new e.g.)
FETCH_CLASS: Means fetching into an new Object (the constructor is called every row)
Be careful, if the constructor in your Company class has dependencies, they are called for every row. Therefore the constructor should not contain functions or classes that do an DB connect e.g. only simple initializing...
How does your Company class look like?
We are currently using Nginx as our server and memcached for caching mechanism. I was inspecting PHP error logs and lots of PHP Warnings about memcached caught my attention.
PHP Warning: Memcache::get(): Invalid Memcache->connection member variable in {directory}/library/Zend/Cache/Backend/Memcached.php on line 180
At the line it was pointing, there is this piece of code:
$tmp = $this->_memcache->get($id);
I also see many other PHP warnings with the same warning message but different with different function calls of memcache object:
PHP Warning: Memcache::add(): Invalid Memcache->connection member variable in {directory}/library/Zend/Cache/Backend/Memcached.php on line 180
PHP Warning: Memcache::set(): Invalid Memcache->connection member variable in {directory}/library/Zend/Cache/Backend/Memcached.php on line 230
PHP Warning: Memcache::delete(): Invalid Memcache->connection member variable in {directory}/library/Zend/Cache/Backend/Memcached.php on line 323
I did a search through the web but could not find anything that really helped. From time to time, we have some problems with our memcached. Is it possible that this some kind of issue that happens when servers are down because of some problem? I really do not have any idea about what causes these warnings. How can I correct it or at least how can I avoid these warnings?
I found 3 references that might help you
Limit of file system and memcache
Possible memory leaks
Memcache vs Memcached
You need to check key max 250 chars and value max : 1MB
Have you compiled your own php recently? It's possible ther versions are out of sync.
I had the same problem.
when i called memcache object in __destruct to update the state of my object i goot the error.
and here is my solution.:
call object in your class function where you change the state and be sure to send an instance of memcache to this class.
While from the warning message itself, it may not be obvious, but the error may be happening when you're trying to serialize/deserialize memcache connection object itself.
For example:
class a {
private Memcache $mc;
private $name = 'glen';
public function __construct(Memcache $mc) {
$this->mc = $mc;
}
}
$a = new a($mc);
$mc->set('a', $a);
You very likely (as me) ended up here because class having mixed concerns (the object being a model and has as other business logic as well). you can omit the unwanted mc key from serializing using __debugInfo function:
public function __debugInfo() {
return [];
}
https://www.php.net/manual/en/language.oop5.magic.php#object.debuginfo
While writing this note, I'm not able to reproduce with my own example, so there's something else involved, perhaps memory corruption. But removing $mc property solve the problem for me.
This question already has answers here:
Closed 10 years ago.
Can i call admin panel controller from account controller?
I mean in account controller i set acessible parts of admin panel and i want to transfer that variable with accessible place to admin panel controller.
and now can i do sth like:
<?php
// Code here
$this->panel = new Admin_Panel();
$this->panel->accessibleparts = $this->data['accessible'];
?>
Or is it disallowed in mvc rules?
Stuff like this:
public function connect(){
try {
$db = new PDO('mysql:host=localhost;dbname=radiolev_db', 'radiolev_user', 'ceowwyso1');
is all fine and dandy, but you're not actually storing that database connection object anywhere in your object. It's just a local variable in that particular method, and will be destroyed when the function exits. e.g. you're connecting, then as soon as your connct() method returns, the local $db variable goes out of scope, and your brand new database connection is closed and destroyed.
You need to store that $db in your OWN object, so it'll be preserved for later use, e.g:
$this->db = new PDO(...);
instead.
And as everyone else above has said, you cannot mix mysql_(), mysqli_(), and PDO connections with each other. Each is a completely distinct and separate library (even though they all use the same underlying mysql low-level library). A connection established in one of those is completely distinct/separate/unusuable by the other libraries. Since you're using PDO to connect, you cannot use mysql_ functions, because mysql_ has no knowledge of anything going on in PDO.
The answer is read about how it works in the manual: http://php.net/oop5
Answer to your previous question:
You get the following errors:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'radiolev'#'localhost' (using password: NO) in /home/radiolev/public_html/top/toplist.class.php on line 10
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/radiolev/public_html/top/toplist.class.php on line 10
You then ask:
I don't understand why it appears cause the mysql passwords are good.
No worries. You just made a little mistake. The mistake is that you make use of the function mysql_real_escape_string while not using a connection of the mysql_* extensions (note: extension, not database server).
In case you're calling that function without establishing a mysql_* extension database connection, PHP will automatically create one based on the settings provided in php.ini. That is normally only the host set to localhost - but wihout username and password.
This is why you see the first error that the connection fails and the second error is the result of the failed connection - there is no link to the databse, so ?mysql_real_escape_string can not work.
To solve the problem, just do not use mysql_real_escape_string when you're using mysql via PDO. Prepared statements is all you need.
Your problem is that mysql_real_escape_string() expects a connection (which you have made, just not using the mysql_* subset of commands).
Use PDO, and actual prepared statements, not whatever it is you're doing now.
$pdo = $conn->prepare('SELECT * FROM myTable WHERE theColumn = :myParam');
$pdo->bindParam(':myParam', $_GET['data']);
$pdo->execute();
By 'call' I assume you mean use it.
Just add a return value, return $db; -- This would be at the end of your connect(), after the error mode was set.
Now
$db = new mysql();
$conn = $db->connect();
$conn->prepare('SELECT * FROM myTable WHERE myColumn = ?');
$conn->execute(array('test'));
Replace mysql_real_escape_string with PDO's quote or bindValue
You are getting a bunch of errors because mysql_real_escape_string is trying to use the last open connection used by mysql_connect (as explained in the PHP Manual). Since you are using PDO instead of the mysql_* functions, there is no connection and mysql_real_escape_string is throwing an error.