I am trying to start a pgsql connection in php but i get pg_last_error(): No PostgreSQL link opened yet Please forgive my amateur question as i am a bit new to php.
Here is my php code:
<?php
$connect = pg_connect("host=xxx.xx.xxx.21 dbname=d106 user=b16 password=bran") or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
In your pgsql connection you have missed the port number.
Try this way.
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" ) or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
You can store PgSQL connection code in one PHP file to reuse
pgsql_db_connection.php file
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" );
if(!$connect){
echo "Error : Unable to open database\n";
}
?>
Call pgsql_db_connection.php file in other php files to use your database connection.
<?php
require_once('pgsql_db_connection.php');
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo pg_last_error($connect);
exit;
}
while($row = pg_fetch_array($result))
{
$coor = $row[0];
echo $coor;
}
?>
When pg_connect fails, it returns FALSE and produces a PHP warning with the detailed information on why it couldn't initiate the connection. If you can see the other message:pg_last_error(): No PostgreSQL link opened yet that you're reporting, I'd expect you should be able to see the previous one too, which is the one normally telling the reason of the failure.
If the display_errors configuration setting is set to 0, the first message would not show up on the browser/screen but the second would not either.
Anyway, assuming you can't have access to pg_connect warnings for whatever reason such as custom error handler, what's wrong with your code is that pg_last_error() must have an already opened connection to work.
To access the detailed error message from a failed pg_connect, the built-in PHP function error_get_last() (returning an array) could be used.
<?
$connect= pg_connect("your-connect-string");
if (!$connect) {
print_r(error_get_last());
// for only the message:
// echo error_get_last()['message']
}
die("DB connection failed");
?>
See also how to catch pg_connect() function error? if you prefer exceptions.
Related
I am trying to access a database on my web host with a php file that is on the same server. When trying to load the page I get the following error: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111. I cannot find a good answer what it going wrong. Below is my php that I am using. I have my IP address of my database set as my host name.
<?php
$con = mysql_connect("10.123.0.209:3306","username", "password");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("matmac78_macy", $con);
$sql = "SELECT * FROM countries";
$mydata = mysql_query($sql, $con);
while ($record = mysql_fetch_array($mydata)){
echo $record['country'] . " " . $record['population']
echo"<br/>";
}
mysql_close($con);
?>
Any help would be greatly appreciated!
You should switch to using PHP's PDO connection protocol.
$username = 'username';
$password = 'password';
$dbName = 'matmac78_macy';
$host = '10.123.0.209:3306';
try {
$this->database = new \PDO( "mysql:host={$this->host};dbname={$this->dbName}", $this->username, $this->password );
$this->database->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$this->database->setAttribute( \PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC );
return $this->database;
} catch (\PDOException $e) {
throw new \Exception( "Could not establish database connection. \n" ); #Push error message
}
I'm trying to connect my PHP webpage with my MS SQL database. I've got this code from the internet, but have tried others. All seems to come back with a problem with "mssql_connect".
I have tried (I think) everything and can not find out why it won't work.
My code is:
<?php
$myServer = 'SQL5008.Smarterasp.net,1433';
$myUser = '*****';
$myPass = '*****';
$myDB = '*****';
//connection to the database
$dbhandle = mssql_connect($myServer, $myuser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT id ";
$query .= "FROM tblEmployees ";
$query .= "WHERE CompanyID=3";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
Why dont you try using PDO. I use it with SQL SERVER daily. You will need the php sqlsrv extenstion though.
// instantiate the pdo object
try {
$Server = "localhost";
$User = "username";
$Pass = "password";
$Database = "mydb";
$this->conn = new PDO("sqlsrv:Server=$Server;Database=$Database", $User, $Pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//allow for SQL query errors
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Check using phpinfo() if mssql extension is loaded. According to PHP Manual:
This extension is not available anymore on Windows with PHP 5.3 or later.
If you find out mssql is unloaded, try to connect using sqlsrv extension. Here you can find a few examples http://php.net/manual/ru/function.sqlsrv-connect.php
Anyway it's a good idea to post here an error message you get from PHP.
i'm trying to use mysqli module for PHP5 and it doesn't work. The module is activated in php.ini. What could be the problem?
<?php
require_once("class/guestbook.php");
$host = "localhost";
$user = "root";
$pass = "";
$db = "guestbook";
//Connect
$c = new mysqli($host, $user, $pass, $db);
//Check connection
if (mysqli_connect_errno()) {
printf("Connection failed! %s\n", mysqli_connect_error());
exit();
}
//Return the name of current database
if($result = $c->query("SELECT_DATABASE();")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
//Close connection
$c->close();
?>
Thank you!
The only thing wrong with your neat code, most probably, is your query itself.
SELECT_DATABASE(); // returns an error for obvious reasons
Means nothing to mysql. This does
SELECT DATABASE();
You don't see the error message because you don't check for errors on query execution. You are only looking for connection errors. Try an else{} block for $c->query and print the error message to see it.
I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements
I have a simple project and that is to create a function that will check for mysql and odbc connection. I'm already done in creating the function for mysql, here's my sample code:
function check() {
$serverName = 'localhost';
$userName = 'root';
$password = '123';
$db = 'sample';
$conn = mysql_connect($serverName, $userName, $password);
mysql_select_db($db, $conn);
$trans = 'SELECT * FROM Labels';
$trans_result = mysql_query($trans, $conn);
if(!$trans_result) {
die(mysql_error());
} else {
echo "connected";
}
}
Well this one works for me when checking for the mysql connection. Now, my question is, is it possible to create something like this for checking my odbc data source connection? So that would be like
$conn = odbc_connect("spmuse1","" ,""); # Open connection.
$trans = "SELECT French FROM Labels";
$trans_result = odbc_exec($conn, $trans);
if(!$trans_result) {
echo "error?";
} else {
echo "connected";
}
You know what I mean? When I use this code, I always have 2 this error
Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect
Warning: odbc_exec(): supplied argument is not a valid ODBC-Link resource
Please help! Thanks.
First you need to decide vendor of odbc driver, I hope below example will works for you
<?php
// Configure connection parameters
$db_host = "server.mynetwork";
$db_server_name = "Dev_Server";
$db_name = "Dev_Data";
$db_file = 'c:\dbstorage\dev.db';
$db_conn_name = "php_script";
$db_user = "dbuser";
$db_pass = "dbpass";
$connect_string = "Driver={Adaptive Server Anywhere 8.0};".
"CommLinks=tcpip(Host=$db_host);".
"ServerName=$db_server_name;".
"DatabaseName=$db_name;".
"DatabaseFile=$db_file;".
"ConnectionName=$db_conn_name;".
"uid=$db_user;pwd=$db_pass";
// Connect to DB
$conn = odbc_connect($connect_string,'','');
// Query
$qry = "SELECT * FROM my_table";
// Get Result
$trans_result= odbc_exec($conn,$qry);
if(!$trans_result) {
echo "error?";
} else {
echo "connected";
}
?>
I spent several days looking for a simple answer, and came up with this, which works for me:
if (#odbc_connect("DBName","un","pw",SQL_CUR_USE_ODBC) == FALSE){
echo "Database does not exist";
} else {
$connection=odbc_connect("DBName","un","pw",SQL_CUR_USE_ODBC);
echo "Database exists";
}
The # suppresses the basic error if the database does not exist, so the connection try will just return false. Of course if the connection is good, then it creates the connection object.