"Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource" - php

I am getting this error:
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource
Here's my Connection.php :
$userDB_server = "";
$userDB_user = "";
$userDB_password = "";
$userDB_database = "";
$connection = mysql_connect("$userDB_server","$userDB_user","$userDB_password") or die ("Unable to establish a DB connection");
$userDB = mysql_select_db("$userDB_database", $connection) or die ("Unable to establish a DB connection");
$gameDB_server = "";
$gameDB_user = "";
$gameDB_password = "";
$gameDB_database = "";
$gameDB_connection = mysql_connect("$gameDB_server","$gameDB_user","$gameDB_password", true) or die ("Unable to establish a DB connection");
$gameDB = mysql_select_db("$gameDB_database", $gameDB_connection) or die ("Unable to establish a DB connection");
Here's my function :
require_once('Connection.php');
$findQuery = sprintf("SELECT * FROM `Keys` WHERE `ID` = '$gID'");
$findResult = mysql_query($findQuery, $connection) or die(mysql_error());
$resultRow = mysql_fetch_assoc($findResult) or die(mysql_error());
The error is on "$findResult = mysql_query($findQuery, $connection) or die(mysql_error());"
But I don't see a problem anywhere.
What I've tried :
I've tried with and without the "true" on the second connection,
didn't seem to make a difference anywhere.
Echoing the $connection and $gameDB_connection shows nothing,
Using var_dump on $connection shows "resource(9) of type (mysql link)"
Removing the $connection from the mysql_query has it connect to the
other DB (gameDB_connection) and I get an error that the table
doesn't exist (its not on that DB).
Adding / changing / removing the backquote ( ` ) from the query seems
to have no effect on the error
The variable $gID echo's correctly, so it's not null (its 1001 in
this case)
If I run the SELECT part in the actual sql form (instead of via php),
it lists them all correctly
The Connection.php is used in other places (one page reads
from both databases at the same time) successfully. No errors anywhere else
Anyone have any idea what's wrong?

Based on the comments, it sounds like the problem is caused by using require_once() inside a function.
One of two thing is happening. Either:
You've already included Connection.php somewhere else, so when you get to the function, it's not actually included.. because of the once part of require_once.
or...
It is working the first time you call the function, but the second time you call it, the file has already been included and does not get included again.
The problem is that when the file is first included (assuming that's from within this function), the $connection variable is created in the function scope, and like any other function variable, is gone at the end of the function. When you call the function a second time, the include doesn't happen because you're using require_once.
You could probably fix this by calling require() instead of require_once(), but that will end up reconnecting to the database every time you call the function - which is a lot of unnecessary overhead. It's much cleaner to just move the include outside of the function, and either pass the connection into the function, or use it as a global variable.
That would look like this:
require_once('Connection.php');
function getResult() {
global $connection;
$findQuery = "SELECT * FROM `Keys` WHERE `ID` = '$gID'";
$findResult = mysql_query($findQuery, $connection) or die(mysql_error());
$resultRow = mysql_fetch_assoc($findResult) or die(mysql_error());
}
All that being said, there's 2 major problems with this code.
You're using the mysql_* functions which are deprecated and will soon be removed from new versions of PHP. See this question for more details: Why shouldn't I use mysql_* functions in PHP?
It's not actually that hard to switch to something like the mysqli_* functions instead - there's a non-object set of functions that are almost identical to what you're using now.
You're including a variable in your query without properly escaping it. At the very least you should be calling mysql_real_escape_string() (or mysqli_real_escape_string()), but a better solution is to look into prepared statements. You can find more information on prepared statements here: How can I prevent SQL injection in PHP?

Related

Fatal error: Call to a member function query() on a non-object Error

I have a small problem. I'm trying to make a simple register/login system with sessions and I got this error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\members\includes\login.inc.php on line 9
This is the relevant line of code:
$result = $conn->query($sql);
The first time I tried it was working.
The rest of the code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $_POST['email'];
$password = md5($_POST['password']);
$sql = "SELECT email, password FROM member WHERE email = '$email' AND password = '$password'";
$result = $conn->query($sql);
I also have db.php, which is used to connect the MYSQL and everything inside it is fine.
I cannot understand why, the first time I tried it was working I guess and now this kind of error.
I'm also having the db.php which is used to connect the MYSQL and everything inside is fine.. could someone explain me why I keep facing this error ?
I'm going to speculate. I'm speculating that you have a separate file (probably called db.php) which "handles" the setting up of the database connection. I'm further going to speculate that you've a chain of files which are require() (or include())'d into your web app.
I've seen this more times than I care to recall. It's a very old fashioned way of separating code into logical chunks inside PHP - which needs to be left in the past.
I'm speculating that you were previously defining $conn in another script which was included (or required) before this code. A global variable, which had was dependency later in the code execution. Invisible to the file it was declared in.
That's the problem. The quick/hack fix is to rename $conn or the restore the original declaration of it and make sure it's global and make sure it is included before this code is ran.
The proper fix (IMHO) is to look at using a framework (Laravel, Lumen, CodeIgniter, Yii, there are many - take your pick) and read up on the topics of dependency injection, autoloading and namespacing. Think about why global variable declarations make for unmaintainable code.
If you're really reluctant to go with a full framework, at the very least have a look at some database-abstraction libraries like doctrine (and it's sub-library dbal) which can easily be auto-loaded into your project via composer.
As Sascha already pointed out, $conn might be either not defined at all, or it's not an object (hence the error message).
From the code sample you have provided, it's actually a bit hard to tell what kind of connection object you might be using, but I think it's save to say that in your case it might be either PDO or mysqli.
For the sake of simplicity, let's stick with mysqli. A working code sample based on mysqli would look like this (shortened example taken from the docs cited above):
$conn = new mysqli("localhost", "my_user", "my_password", "world");
$result = $conn->query($sql);
Though you really should go for so-called prepared statements, as your code right now is prone to SQL injection as wally already stated.
I would have linked wally's answer and provide you with a link to the PHP docs relating to prepared statements, but apparently, my lack of reputation points don't allow me to, so just do a quick Google search for PHP & prepared statements.
The database connection file has to be added at the beginning of the file.
The present format is easy.
<?php $mysqli = new mysqli("localhost", "Userid", "password", "database name"); if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; }
?>
At the beginningļ¼š
require 'db.php';
$conn = new db();

PHP MySQL Get Connection From Require() File

I usually am immersed in the Microsoft Stack but dabble in PHP from time to time. A long standing question I've had with PHP that I've never seem to be able to find the answer to is how do you apply your already declared require("dbConnect.php") database connection to your mysql_query()? For clarification please see my code example below:
require("dbConnect.php");
$db_host = 'localhost';
$db_user = 'UserName';
$db_pwd = 'Password';
$database = 'DbName';
$table = 'tblQuote';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT QuoteID, FirstName, LastName, PhoneNumber, Email, QuoteDate FROM tblQuote ORDER BY QuoteDate DESC");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
So in looking at this you can see the standard require() declaration at the top... which already holds my connection info. But every single MySQL Query example I've ever found always creates it's own connection... which I get for demonstration purposes... but I've never been able to figure out how I can use my already existing connection thereby bypassing rewriting the exact same connection info over and over again when it comes to writing queries. I know for you PHP developers this question is like 101 but I've not been able to find an answer to this seemingly basic question... admittedly I may be asking the question wrong so any help would be appreciated!
From the PHP documentation: http://php.net/manual/en/function.mysql-query.php
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments.
So since you've already created one in your dbConnect.php, the one you just made will be used (It won't create a new one for every query). To pass it explicitly into your mysql_query function call, you can return the MySQL resource that was returned from your mysql_connect call like so:
dbConnect.php
return mysql_connect(....);
Then in the code you pasted above:
$mysql_conn = require('dbConnect.php');
...
$result = mysql_query('...', $mysql_conn);
Then you will explicitly have the connection and pass it to your query - there will be no mistaking it, regardless of how large your codebase becomes. When you require the file, you'll have access to the connection variable, but in the above example, how you get the connection is more semantically clear.
Also, notice that this function has been deprecated in PHP>=5.5, so you'll want to use PDOs or MySQLi which have future support.
Hope this helps!

PHP Postgres default connection

pg_query and pg_query_params in PHP can be executed without specifying a connection resource in the arguments' list, so PHP will use the last connection opene by pg_connect.
Is there a way to retrieve the default connection string that PHP will use intead of trying to figure out where it is coming from across a couple of PHP files? Something like get_default_dbConnection()?
Thanks.
That doesnt mean that there is a default connection string, but that you dont have to provide a param that references the connection. Check out the example on php: pg_query
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occured.\n";
exit;
}
In this example there is $conn = pg_pconnect("dbname=publisher") and in the call to pg_query they pass a long $conn. That is the connection reference. Now you could also just use
$conn = pg_pconnect("dbname=publisher");
$result = pg_query("SELECT author, email FROM authors");
pg_query will now automatically use the last opened connection (which is $conn)
Update:
You cannot get the resource, PHP uses an internal method php_pgsql_get_default_link to get the default connection but will not return it anywhere (See php-5.4.9\ext\pgsql\pgsql.c in the source).
You can get information on the database name or user using pg_dbname or pg_parameter_status

Why can't i write my MySQL database using a 'required' function?

I'm using a file called "lib.php" in which i have defined many functions.
One of these functions is the following :
function dbconn()
{
$servername="127.0.0.1";
$username="root";
$conn=mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("profit",$conn) or die(mysql_error());
}
In all the .php pages of my website, i've been using this dbconn() function, and it seemed to work fine for reading information from the database. However, when trying to write information, it seems to pose a problem. Specifically, the following code did not function :
<?php
require ("lib.php");
set_time_limit(60);
session_start();
dbconn();
$sql="update `city` set end_dt=now() where city_id='$_POST[killcity]'";
$result=mysql_query($sql,$conn) or die(mysql_error());
header("Location: manipulate.php");
?>
It says that conn is an undefined variable, whereas it should be defined by dbconn() in lib.php.
So, i've found a way around this, by instead creating a new php file called dbconn.php, which contains the exact same thing as dbconn(), and by inserting require ("dbconn.php"); instead of dbconn();.
But i'm still wondering : why did the original way not work ?
You could add a return statement for the function, through you could use global variable in a function, that's not good practice. If you want to, see how global variable works.
function dbconn() {
$servername="127.0.0.1";
$username="root";
$conn=mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("profit",$conn) or die(mysql_error());
return $conn;
}
$conn = dbconn();

my sql query failing and yet returns no mySQL errors

I have been writing php and mySQL functions all day and as I was writing the simplest part of my project I have hit a wall.
The function should simply count how many entries are in the database and return that number (If there is a more simple way please let me know, this is my first php + mysql project)
Here is the code:
function quoteCount(){
global $db;
$totalQuoteNum = array();
$query = "SELECT * FROM Quotes";
$result_set = mysqli_query($db, $query)
or die ("Query $query failed ".mysqli_error($db)); //fails here
$totalQuoteNum = mysql_num_rows($result_set)
or die ('couldnt count rows'.mysqli_error($db));
echo 'COUNTED EVERYTHING!!!';
return $totalQuoteNum;
};
Now when the die statement prints I get the string but not the mysqli error.
Things I have tried and ruled out:
$db is correct
query works in mysql
I wasnt sure if the database was connected, so I added the connect inside this function and stil nothing.
Any ideas? From what I see it should work and its not giving me any error to work from. Please help!
Based on the comments, it seems as though $db is the database name.
Functions such as mysqli_query() expect a database link (resource), not simply the database name.
This resource is created by constructing a new mysqli object. Following your procedural style, use mysqli_connect().

Categories