I am new to PHP. I want to use the database stored in pgSQL from my PHP file. Please tell how to integrate pgSQL and PHP, so that I can use pgSQL in PHP using pg_connect(). My php.info() is showing MySQL, pgSQL, SQLite enabled under PDO support. But when I use pg_connect() it says:
Warning: pg_connect(): Unable to connect to PostgreSQL server: FATAL: role "postgres" does not exist in /Users/username/Sites/index.php on line 3
Warning: pg_last_error(): No PostgreSQL link opened yet in /Users/username/Sites/index.php on line 4
Warning: pg_last_error(): supplied resource is not a valid PostgreSQL link resource in /Users/username/Sites/index.php on line 4
Could not connect:
I have used this tutorial to run PHP on Mac. But I couldn't find a tutorial clearly showing how to integrate PHP and pgSQL.
https://www.dyclassroom.com/howto-mac/how-to-install-apache-mysql-php-on-macos-mojave-10-14
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=ipl user=postgres password=password")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT * FROM player';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
I got the problem. My username is not postgres but my name. I must have set it while installing Postgres. Therefore it is saying no role as 'postgres' exist.
Related
I am trying to fetch from the database data and to generate a graph. I am using phpgraphlib, http://www.ebrueggeman.com/phpgraphlib/documentation/tutorial-mysql-and-phpgraphlib. I downloaded the libgd from https://github.com/libgd/libgd/releases
and also the phpgraphlib. I have PHP 5.5 and the php_gd2.dll extension I think it is enabled by default in the php.ini file.
I get 2 errors:
Warning: require_once(phpgraphlib.php): failed to open stream: No such
file or directory in C:\XAMPP\htdocs\graph.php on line 3
Fatal error: require_once(): Failed opening required 'phpgraphlib.php'
(include_path='.;C:\XAMPP\php\PEAR') in C:\XAMPP\htdocs\graph.php on
line 3
I also undertsand that something goes wrong the path and the directories. Any help? Thanks in advance!!!
<?php
require_once("phpgraphlib.php");
$graph=new PHPGraphLib(400,300);
//connection to MySQL database
$link =mysql_connect('localhost','root','') or die('Could not connect :'. mysql_error());
//select db
mysql_selected_db('mynewdb') or die('Could not select database');
$dataArray=array();
//get data from database
$sql="SELECT year1,year2 * FROM scores WHERE crit='interesting semester' AND sid='13'";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$crit=$row["crit"];
$year1=$row["year1"];
$year2=$row["year2"];
//add to data array
$dataArray[$crit]=$count;
}
}
//configure graph
$graph->addData($dataArray);
$graph->setTitle("Interesting Semester");
$graph->setGradient("lime", "green");
$graph->setBarOutlineColor("black");
$graph->createGraph();
?>
please place your file phpgraphlib.php in ./ or C:\XAMPP\php\PEAR
So I'm not sure as to why PHP is not creating a database. Let me show what my code looks like first, and then I will quote what warning/error it's giving me:
<?php
// Connection
$con = mysqli_connect("localhost", "root", "1monica1");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Creating a database
// The database is called alarm_db
$sql = "CREATE DATABASE alarm_db";
if (mysql_query($sql, $con))
{
echo "Database alarm_db created sucessfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
The error and warning I keep getting is this:
Warning: mysql_query(): A link to the server could not be established in B:\DropBox\Dropbox\EbadlyAgha\Ebad\reminders.php on line 51
Error creating database:
Line 51 is where the if (mysql_query($sql, $con)) is. Also, it won't give me the mysqli_error($con). It is just blank.
My MySQL connection is fine, because I never see the "Failed to connect to MySQL" statement.
It should be in mysqli_* while you executing DB creating query.
if (mysqli_query($sql,$con)) {
echo "Database alarm_db created sucessfully";
}
Try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.
Your connection is being generated by the mysqli library:
$con = mysqli_connect
but you are trying to query it using the mysql library:
mysql_query($sql,$con)
You need to be consistent about which library you use. Stick to mysqli throughout (since mysql is deprecated).
Note that mysqli_query expects the connection before the SQL:
mysqli_query($con, $sql);
You can try this to create a database using PHP:
<?php
$con = mysql_connect('localhost', 'root', '');
$query = mysql_query('create database alarm_db') or die(mysql_error());
if($query)
{
echo 'Database is created';
}
else
{
echo 'Database is not created';
}
?>
I installed easysoft odbc derby driver in windows 7 and try to connect to derby database
after I configure on ODBC Data Source Administrator DSN and connection succeed.
then i tried on php script
//commz is the DSN name ind ODBC data source admin
$connection = odbc_connect("commz",$user, $password);
if ($result = odbc_exec($connection, "SELECT * FROM ADDRESSBOOK"))
print "Command executed successfully<BR><BR>";
else
print "Error while executing command<BR><BR>";
// Print results
while(odbc_fetch_row($result))
print odbc_result($result, 1) . " " . odbc_result($result, 2) . " " . odbc_result($result, 3) . " " . odbc_result($result, 4) . " " . odbc_result($result, 5) . "<BR>";
odbc_close($connection);
print "<BR>Connection closed.";
after i run this script this msg appear
Connected to datasource
Warning: odbc_exec(): SQL error: [Easysoft][ODBC-Derby
Driver][DRDA]General error: unexpected command (dss not returned), SQL
state HY000 in SQLExecDirect in C:\xampp\htdocs\test\index.php on line
36 Error while executing command
Warning: odbc_fetch_row() expects parameter 1 to be resource, boolean
given in C:\xampp\htdocs\test\index.php on line 45
Connection closed.
any advise regarding to this?
Thanks!
Best thing to do, is send a driver log of the operation to support#easysoft.com and we will take a look at whats going on. I will post whatever we find back here.
To get the log, add to your DSN in odbc.ini file:
Logging = Yes
LogFile = /tmp/drb.log
I have a test db on godaddy, I have had a similar issue before but with the help of stackoverflow it was solved.. So I have actually used the same solution however now I am having a host of errors when I try to load my php file from the browser.
Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/97/8603797/html/countryQuery.php on line 14
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/content/97/8603797/html/countryQuery.php on line 14
Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /home/content/97/8603797/html/countryQuery.php on line 16
Warning: mysql_close(): no MySQL-Link resource supplied in /home/content/97/8603797/html/countryQuery.php on line 18
Database Output
I have read what the problem is and some of the things I have read suggest I am not connecting to the DB correctly.. but I am only doing what I have read/been told and dont really know what else I can do to solve the issue I am having...
this is my php code, if anyone has and suggestions or solutions I would greatly appreciate hearing from you.
<?
$hostname = 'mydatabasename.db.6666666.hostedresource.com';
$database = 'mydatabasename';
$username = 'myusername';
$password = 'secretsecret';
// establish a connection
$db = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$query="SELECT * FROM `Countries`";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
$i=0;
while ($i < $num) {
$country=mysql_result($result);
echo "<b>$country<br>";
$i++;
}
?>
the out put should just be a list of the country names I have in the countrys table of my database.. which has values in it.
You are mixing PDO and mysql_* functions.
Try something like this:
$db = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$db->setAttribute(PDO::ATTR_AUTOCOMMIT, true);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="SELECT * FROM `Countries`";
$numRows=$dbh->exec($sql);
echo "There were $numRows selected with:<b> $sql </b><br><br>";
$db=null;
unset($db);
When it comes to getting data from the PDO connection, I normally do something like this using the FETCH_INTO option:
$stmt = $db->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new userStructure);
// I do normally have a class matching the row I wan:
foreach($stmt as $userStructure)
{
$someObject->year=$userStructure->year;
$someObject->month=$userStructure->month;
unset($stmt);
}
Make sure that you include the port as well when using a PDO connection. This is looking like you are doing this in a hosted environment. Check the installation guide regarding the port used.
So a friend of mine and I are using both xampp on ubuntu, if that helps, to connect between each other's website, We both created the same php file to connect, so we use de IP of the other, but then it says an error
Warning: mysql_connect() [function.mysql-connect]: Host 'coke-laptop.local' is not allowed to connect to this MySQL server in /opt/lampp/htdocs/connection.php on line 2
Could not connect: Host 'coke-laptop.local' is not allowed to connect to this MySQL server
We have this code on the connection.php file:
<?php
$link = mysql_connect('10.100.161.37','root','');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_selected = mysql_select_db('Prueba', $link);
if (!$db_selected) {
die ('Can\'t use Prueba : ' . mysql_error());
}
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM Agencia");
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'] . " ";
echo $row['Nombre'] . "\n\r";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
mysql_close($link);
?>
If we use the IP just like that, we can enter each others xampp normal welcome page.
Check you have enabled remote access to the MySQL server. Open the my.cnf file (probably found inside xampp/etc/), go to the [mysqld] section and add the following (using your own ip address instead of the example)
bind-address=192.168.1.100
If there is a line that says skip-networking, comment that out so it looks like this:
# skip-networking
then restart the MySQL server
It looks like your MySQL database isn't allowing you to connect remotely with the credentials you provided. You will need to configure a remote user to connect. Try looking into MySQL Grants.
For Example:
GRANT SELECT, INSERT ON database.* TO 'someuser'#'somehost';