I installed postgresql in my ubuntu 20.04
I enabled the pg extension in the php.ini file
I tried connecting to my local installation of postgres via console to check if i can connect
e.g
psql -h localhost -U root -d test
then I got prompted with password... then I input my password
then I got inside and can see test=#
then I ran
\d
and I was able to see the existing tables inside the test database and was
able to do some simple select query..
moving forward....I tried this php snippet in my index.php file
$host = "localhost";
$user = "root";
$pass = "root*";
$db = "test";
$con = pg_connect("host=$host port=5432 dbname=$db user=$user password=$pass");
$query = "SELECT * FROM person LIMIT 5";
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
$row = pg_fetch_row($rs);
echo $row[0] . "\n";
pg_close($con);
when I ran in browser e.g localhost/pg/index.php
I encountered this error
Cannot execute query: SELECT * FROM person LIMIT 5
any idea why my code can't seem to connect to postgres?
Check if the PG server is listening the port 5432. To do it, run netstat -na and search the record 0.0.0.0:5432, as described here
You could also use PDO instead of pg_connect:
$myPDO = new PDO("pgsql:host=$host;dbname=$db", $user, $pass);
Related
These days I'm switching from a Windows system to Linux. I installed the LAMP stack, and apparently there seems to be no malfunctions.
To be sure I wrote a trite script that connects to the database and performs a simple select query.
phpconnect.php:
<html>
<head>
<title>Test PHP Connection Script</title>
</head>
<body>
<h3>PHP Connect Test</h3>
<?php
$dbname = 'test';
$dbuser = 'my_user';
$dbpass = 'my_password';
$dbhost = 'localhost';
// connection to db
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// check connection
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
exit();
}
$sql = "SELECT * FROM user";
$result = $conn->query($sql);
$row = $result->fetch_array();
printf("%s %s (%s)\n", $row["firstname"], $row["lastname"], $row["age"]);
output:
I checked log file in /var/log/apache2/error.log and this is the error that comes up:
PHP Fatal error: Uncaught Error: Call to a member function fetch_array() on bool in /var/www/html/phpconnect.php:28\nStack trace:\n#0 {main}\n thrown in /var/www/html/phpconnect.php
I answer my question in case someone with the same problem is looking for the solution. Thanks to #ADyson for his help finding a solution, read his comments for details.
The problem arose from the fact that the new user created in mysql did not have the required privileges to access the database tables.
For this reason, when the statement that launched the query was reached, it returned a boolean value, that is false.
It was enough to modify the user's privileges in relation to the database to be queried.
You can do this by running the following command:
mysql> GRANT ALL ON database.table TO 'username'#'localhost';
Where:
database is the database name; you can write * to refer to all databases (not recommended)
table is the table name; you can also write * to refer to all tables in the selected database
After that, running the command FLUSH PRIVILEGES; will reload the grant tables in the mysql database enabling the changes to take effect without reloading or restarting mysql service.
mysql> FLUSH PRIVILEGES;
I have a linux server that I'm trying to use php adodb to connect to a MSSQL server.
include('adodb5/adodb.inc.php');
$conn =& ADONewConnection('odbc_mssql');
$dsn = "Driver={SQL Server};Server=MSSERVER;Database=Northwind;";
$conn->Connect($dsn,'sa','password')or die("Unable to connect to server");
I've install mssql through yum etc and I know the server can connect to it as I've tried the following:
$db = #mssql_connect("MSSERVER","sa","password") or die("Unable to connect to server");
mssql_select_db("Northwind");
// Do a simple query, select the version of
// MSSQL and print it.
$version = mssql_query('SELECT ##VERSION');
$row = mssql_fetch_array($version);
echo $row[0];
// Clean up
mssql_free_result($version);
Any ideas why my adodb wont connect, or any examples on how I can connect would be much appreciated.
I've solved this by looking at this forum: http://ourdatasolution.com/support/discussions.html?topic=4200.0
The correct code is:
<?php
include("adodb5/adodb.inc.php");
//create an instance of the ADO connection object
$conn =&ADONewConnection ('mssql');
//define connection string, specify database driver
$conn->Connect('xxx.xxx.x.xxx:1400', 'user', 'password', 'DbName');
//declare the SQL statement that will query the database
$query = "select * from table";
$rs = $conn->execute($query);
//execute the SQL statement and return records
$arr = $rs->GetArray();
print_r($arr);
?>
Hope that helps somebody else.
With php 5.3 of above the php_mssql modul is no longer supported for windows.
A Solution is to download the MicroSoft PHP Driver from http://www.microsoft.com/en-us/download/details.aspx?id=20098.
This installer will extract the modul dll files to you php extension directory.
Include the correct version in you php ini (e.g. like this for php 5.3 ThreadSafe):
extension=php_sqlsrv_53_ts.dll
After this you can use adboDb again, but you have to use mssqlnative as adodbtype.
And the connection with ip and port didnt work for me, but ipaddress\\SERVERNAME worked (see examplecode)
<?php include("adodb5/adodb.inc.php");
//create an instance of the ADO connection object
$conn =&ADONewConnection ('mssqlnative');
//define connection string, specify database driver
// $conn->Connect('xxx.xxx.x.xxx:1400', 'user', 'password', 'DbName');
$conn->Connect('xxx.xxx.x.xxx\\SERVERNAME', 'user', 'password', 'DbName');
//declare the SQL statement that will query the database
$query = "select * from table";
$rs = $conn->execute($query);
//execute the SQL statement and return records
$arr = $rs->GetArray();
print_r($arr); ?>
For PHP 7.4 you can download the drivers here:
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver15
Copy the files to the ext directory of your php installation.
In the php.ini file then add the extensions as follows:
extension=php_pdo_sqlsrv_74_ts_x64
extension=php_sqlsrv_74_ts_x64
The extension also requires the ODBC driver for SQL Server to be installed:
https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15
SO, I'm trying to insert some registers to PostgreSQL table using PHP.
I have a career table and registers are into school_careers.sql. So I've tried this:
$host = "localhost";
$user = "user";
$pass = "passw0";
$db = "school";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server $server\n");
$query = "\\i ./school_classes.sql";
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
echo $rs . " done\n";
pg_close($con);
But I just get:
Cannot execute query: \i ./school_classes.sql
You're getting an error because pg_query expects a literal query, not a file name.
This post discusses loading and running sql from a file in PHP: Loading .sql files from within PHP
The accepted answer by Jeremy Privett seems to recommend that you "build out a PHP file that contains your queries in a variable [from which you] can just run them".
This doesn't work because "\i" is a psql client program command, not a valid query. There's no way for this command as-is to work in PHP as a pg_query. If you want to do it this way, you can invoke a shell and run this command:
psql -c "\i ./school_classes.sql" -U <username> -h <hostname> <dbname>
This has a drawback in that I do not believe that you can simply pass the password to the psql client, it will prompt for one. You can set up a .pgpass file containing the username/password pair that it can then use to connect without prompting (this is detailed in the PostgreSQL documentation as "libpq-pgpass").
Also, I'm not a PHP person so I don't know how to run a shell command, but it's a common enough operation that it should be in the documentation. You'll also need to determine how to capture the output from the shell command in order to validate that your script can correctly.
I have this query:
mysql_select_db('scanner');
$query = "SELECT * FROM scanner.proxy ORDER BY RAND() LIMIT 20";
$result = mysql_query($query) or die(mysql_error());
it tells me:'scanner.proxy ' doesnt exist.. even though I do have it the table with the database. It is weird, cause my other queries work..but this one doesnt.
UPADTE:
Event when I put this:
$user='root';
$user='root'
$password='<removed_password>';
$dbname = 'scanner';
$host = 'localhost';
$link = mysql_connect($host, $user, $password) or die (mysql_error());
mysql_select_db($dbname, $link) or die (mysql_error());
it gives me this...
Unknown database 'scanner'
But I can see the scanner database in the phpmyadmin
Even when I type in phpmyadmin the sql statement
SHOW TABLES FROM 'scanner'
it says it cant find scanner
We solved this problem which occurred when connecting to multiple remote MySQL databases within the same script by adding a re-connect method before every mysql_query statement. The re-connect method invoked both mysql_connect and mysql_select_db functions. We had previously tried setting the new link parameter to true in the connect statement(s) but We still got database errors and all kinds of funny behavior.
make sure the user you use to connect has enough rights to query that table. Perhaps that table was created by another user.
EDIT: Perhaps you need to grant access to scanner from a remote location. Running this sholud help on that.
GRANT ALL ON scanner.* TO your_user#'IP_ofServer_where_PHP_runs' IDENTIFIED BY 'PASSWORD';
You have set the $dbname = 'aws_backlinks', but you are trying to connect to a different database within your query. Change your connection string to include this db instead or just connect to the server and set your database at the time of the query.
$db_host = 'localhost:Port';
Specify port for localhost.
I was facing the same problem and specifying the port solved the problem.
You're missing the argument that specifies the connection (result of mysql_connect()) in your mysql_select_db() call:
$db_host = 'localhost';
$db_username = 'root';
$db_password = 'whatever';
$db_name = 'scanner';
$link = mysql_connect($db_host, $db_username, $db_password);
mysql_select_db($db_name, $link);
I have PHP sample code which will fetch the data from the MYSQL database through ODBC driver on Linux(CentOS) machine.
I have created DSN and same able to connect through following command
isql -v
But when i try to same DSN through PHP code i am getting "No tuples available at this result index" due to which unable to read the data from database through PHP APACHE configuration.
If anyone provides the solution,It will more helpful for me to proceed further.
Below are my sample code and other details,Please correct if anything wrong on below configuration details-
Below is sample PHP code:
<?php
$conn = odbc_connect("DSN", "username", "password");
$sql = 'select * from tablename';
$rs = odbc_exec($conn,$sql);
echo "<table><tr>";
echo "<th>User Name</th></tr>";
while(odbc_fetch_row($rs)) {
$user = odbc_result($rs,"fieldname");
echo "<tr><td>$user</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
Below is odbc.ini file:
[DSN]
Description = MySQL ODBC Database
DRIVER = MySQL
TraceFile = /tmp/odbcerr.log
SERVER = 127.0.0.1
PORT = 3306
USER = username
PASSWORD = password
DATABASE = database
OPTION = 3
SOCKET = /var/lib/mysql/mysql.sock
Below is odbcinst.ini file:
[MySQL]
Description = ODBC for MySQL
Driver = /usr/lib/libmyodbc5.so
Setup = /usr/lib/libodbcmyS.so
FileUsage = 1
UsageCount = 3
The comments in the documentation for odbc_connect suggest that this can be caused by using an incorrect cursor type. Try each of the three possible values as the fourth argument: SQL_CUR_USE_IF_NEEDED, SQL_CUR_USE_ODBC, or SQL_CUR_USE_DRIVER.
I am very curious as to why you're using ODBC to connect to MySQL. PHP has many better ways to read from MySQL, including the excellent PDO class (which itself can connect via ODBC if needed).