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
Related
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!
I am using the external authentication system. Therefore, there are a lot of user data, which is not available in Phorum.
I am using the last post module, although I want to get the information from the last post user, from my own user table (I have some data, like avatar, birth info etc). I want to show in my Phorum. How can I achieve this?
I've tried to simply connect via a: mysql_query(); but then I just get No database selected error.
I've searched for hours - I cannot find any documentation regarding getting custom data from your own user table.
I would recommend using mysqli, as mysql is deprecated. First make sure that your connection is correct. No database selected means you probably do not have your connection included at the top.
$con = mysqli_connect("localhost","username","password","database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error());
}
Make sure that your sql statement looks like so (Notice the $con in the mysqli_query()):
$sql = "select * from TableName";
if ($que = mysqli_query($con, $sql)) {
// Query has ran
}
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?
I am trying to use the mysqli to access a mysql database and a table called phptest, with the code below. I am trying to check if row is = 0 or something else but it does not echo anything. What is wrong with the code?
$mysqli = new mysqli("localhost", "root", "", "phptest");
if (!$mysqli) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$query = "SELECT `id` FROM `test` WHERE `email`='example#hotmail.com' AND `password`='5f4dcc3b5aa765d61d8327deb882cf99'";
$query_run = $mysqli->query($query);
$row_cnt = $query_run->num_rows;
if ($row_cnt==0) {
echo 'wrong..';
} else {
echo 'correct!';
}
EDIT: edited the variable in the if statement. I have runned the query directly in the mysql panel in the tabel. I get the right row count then. Why doesnt it work in php ?
Although you are checking for an undefined variable $row_count (which should be $row_cnt, that isn't your immediate problem (you should still fix this). You are getting a fatal error either because:
Your query is failing. Your query may be failing because of a missing field on the table or indeed you are missing the actual table in the database. The query will return FALSE if it fails, but you aren't checking for that, instead you try to access a property of the result. If the query fails, there is no result object, it is a boolean FALSE and will produce a fatal error something like Fatal Error: Trying to access a property of a none object.
You don't have the MySQLi library configured for your PHP installation
To further debug you should turn on error reporting as below, or consult your server's error log.
error_reporting(E_ALL);
ini_set('display_errors', '1');
One thing is that you defined $row_cnt and then checked for $row_count, but that's just a quick look at your program, so there might be something else wrong too.
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().