I have a problem regarding my mysql connection. I need to access the connection inside a class. How do I do it? Even if I try to include the connection file, or the connection variable $con0 inside the class, it has no value so I get an error.
Connection.php
<?php
$username = " ";
$password = "";
$hostname = " ";
$con = mysql_connect()
?>
model.php
<?php
include(connection.php);
class model{
function needTheConnection($uid){
$q = "SELECT x from DB.table WHERE id = '" . $uid . "'";
$res = mysql_query($q);
}
}
?>
This gives me the "mysql_query(): supplied argument is not a valid MySQL-Link resource".
What is wrong?
Thanks, tinks
You're missing part of your code. We know this based on the error message. This line:
$res = mysql_query($q);
Probably actually looks like this in your code:
$res = mysql_query($q, $con);
Am I right? If that's the case, the issue is that $con
isn't accessible from within that function or class instance. The easy way to fix this in your case is to simply remove it. The MySQL client will automagically use the last connection made from your script.
Really though, you should consider a different design pattern. For what its worth, I often just stick my DB resource in $GLOBALS['db']
. This is not considered a pure OOP way to do things, but for many applications, it is suitable.
Finally, $5 says you are wide open to SQL injections. Learn how to do prepared queries with PDO, or at least escape your data before someone steals your entire database and brings havok to your site.
class model {
function __construct(&$db) {
$this->db=$db;
}
function needTheConnection($uid){
$q = "SELECT x from DB.table";
$res = mysql_query($q,$this->db);
}
}
$model = new model($conn);