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);
I'm trying to export a csv file from a linux machine to a local PC via a PHP script on a browser.
I've done a good bit of research, but I can't find what I'm looking for (maybe it doesn't exist).
My script connects to the database via php and uses localhost as do my other php scripts that just display data from the database but don't export the data.
Here is my futile attempt:
$user = 'postgres';
$password = 'XXXXX';
$db = 'ltg';
$host = 'localhost';
$conn=pg_connect('dbname ='.$db.' user = '.$user.' password = '.$password.' host = '.$host) or die ("Could not connect: ");
//query for copying/exporting to csv
echo "system(\copy (select lat, lon from ltg_data order by time desc limit 1000) To '~/Downloads/export.csv' CSV HEADER);"
There are two issues, at least, that I'm confused about. The connection to the db works fine for accessing/display data from db. Do I need to use something other than "localhost" to export data?
Second, running the \copy command is problematic. I somehow need to run a psql meta-command to export the data, and I really don't know how to do that via php.
Thanks very much for your time.
The problem is that system runs a shell command (not sure why you're echoing it?), so it doesn't go through $conn at all. And of course there is no shell command called \copy.
If you want you can send a \copy ... to psql with something like system("echo '\copy ....' | psql"), but you'll have to be careful with escaping the parameters etc.
Since your database is on localhost and you're already connecting with the postgres user, you could just use COPY instead of \copy, and send the command via $conn.
Here is documentation about COPY.
i have upload my web application to OpenShift.
my application is using the PHP and MySQL Cartridges.
i have created a few databases using PHPmyAdmin (Through the openshift web interface). each database has it's own unique name obviously.
in my PHP code i initialize the connection to one of my MySQL databases in this fashion:
$mysql_database=<some data base>;
$connection = mysqli_connect(getenv('OPENSHIFT_MYSQL_DB_HOST'), getenv('OPENSHIFT_MYSQL_DB_USERNAME'), getenv('OPENSHIFT_MYSQL_DB_PASSWORD'), "$mysql_database", getenv('OPENSHIFT_MYSQL_DB_PORT')) or die("Error: " . mysqli_error($connection));
mysql_set_charset("utf8", $connection);
then somewhere else i am doing some queries from my PHP code (like select , update and so on) on tables inside the database i connected to. for example:
$query_run=mysql_query("SELECT * from `$some_table` WHERE `id`='$id'")
the connection itself does not fail on anything, however all my queries fail on :
Access denied for user ''#'localhost' (using password: NO)
When i manually issue these commands on the actual machine everything runs fine. so this works: SSHing into my machine using PuTTy , and doing :
mysql -u $OPENSHIFT_MYSQL_DB_USERNAME -h $OPENSHIFT_MYSQL_DB_HOST -P $OPENSHIFT_MYSQL_DB_PORT -p <some data base>
mysql>SELECT * from `<some table>` WHERE `id`='<some id>'
i did not modify the security settings of anything, neither did i change the username / password that were generated for me for the MySQL actions.
also, everything runs perfectly fine on my local application running on a xampp Apache+MySQL server.
any ideas?
You shouldn't really be using mysql_query() like that (see Is this query safe from sql injection?)
You can use a much better abstraction: PHP Data Objects (PDO). e.g.
try {
// Set your connection variables
$host = getenv('OPENSHIFT_MYSQL_DB_HOST');
$port = getenv('OPENSHIFT_MYSQL_DB_PORT');
$username = getenv('OPENSHIFT_MYSQL_DB_USERNAME');
$password = getenv('OPENSHIFT_MYSQL_DB_PASSWORD');
$dbname = 'database_name';
// Create the connection string
$conn_str = "mysql:host=$host;port=$port;dbname=$dbname"
// And create a db handler with PDO
$dbh = new PDO($conn_str, $username, $password);
// Prepare whatever statement, could also be SELECT etc
$stmt = $dbh->prepare("INSERT INTO TABLE_NAME (name, value) VALUES (?, ?)");
// Binding parameters like this prevents SQL Injection
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// Assign values to the variables
$name = 'Random';
$value = 1;
// Finally, execute the statement
$stmt->execute();
}
catch(PDOException $e) {
// Print out whatever error we got
echo $e->getMessage();
}
// Don't forget to close the connection
$dbh = null
Not only this is a better solution for handling MySQL databases with PHP, but hopefully it will also fix your authentication problems (or make them easier to debug, at least).
Stop and Start your application (not a restart). Sometimes apache needs to be restarted to pick up the new mysql environment variables.
I usually connect php to mysql with localhost in my PC..
now i'm trying to put my project in cloud https://c9.io ,but i can't connect to mysql. i already have mysql database in cloud and put my project in same place...
mysql_connect("/lib/mysql/socket/mysql.sock","myUser","") or die(mysql_error());
i use script above to connect but i get Unknown MySQL server host '/lib/mysql/socket/mysql.sock' (1)
what shoul i do ?
Okay, so none of the above answers had worked for me, but fortunately I was able to setup a database and get it up and running my own way and I can now make queries and run them successfully, so I will share my method with you in hopes that anyone else scouring the internet can stumble across this and not have to go through the same head scratching that I did.
If you want the quick rundown, just scroll to Step 3 and read on from there. If you're a complete beginner, keep reading as I'll walk you through it in detail.
Couple things to mention:
You will have to setup a database via a Terminal in Cloud 9. I had no experience prior doing it in a Terminal before, but it's very simple to learn.
You can not use mysql functions, you have to use mysqli, since mysql functions are deprecated and Cloud 9 will not run them.
Step 1: Setup MySQL on Cloud 9 (in Terminal)
In your project, open up a New Terminal (click the plus-sign tab above the text editor space, select "New Terminal"). In the terminal, type mysql-ctl start and hit Enter. MySQL will start up in the back, but you won't get any response back in the terminal.
Next, type mysql-ctl cli and hit Enter. You should see some text that starts off as Welcome to the MySQL monitor.... Congrats, you've setup MySQL on your Cloud 9 project.
Step 2: Create a test database (in Terminal)
You can actually go ahead and create your official database if you like, but for this sake I'll just make a database that holds a table that holds an ID and a username. So here's the steps to setting up a database and a table. If you've used MySQL and databases before, then this should be cake, but I'll explain it in detail for those who might not fully understand MySQL .
Type SHOW DATABASES; and hit Enter. This will show a list of current databases within your project. You can enter this any time you want to see a list of your databases on the current project.
Type in CREATE DATABASE sample_db; and hit Enter. You should get a Query OK, 1 Row affected. which means the query was successful. You can name the database whatever you like, but for this little walk-through, I named it sample_db.
Type in USE sample_db; and hit Enter. This selects sample_db from the list of databases.
Type in CREATE TABLE users (id INT(11), username VARCHAR(20));, and hit Enter. This creates a table named users with two columns: id and username. The number in parentheses represents the character limit the column will store in the database. In this case for example, username won't hold a string longer than 20 characters in length.
Type in INSERT INTO users (id, username) VALUES (1, "graham12");, and hit Enter. This will add the id of 1 and a username graham12 in the table. Since the id column is an INT, we do not put quotes around it.
Type in SELECT * FROM users;, and hit Enter. This will show everything that is in the users table. The only entry in there should be what we inserted from the last step we just did.
Step 3: Get the credentials you'll need to connect to the database from PHP. (in Terminal)
Now we have some data in our table that we can test our mysqli connection with. But first, we have to get the credentials we will need to connect to the database in PHP. In Cloud 9, we will need 5 credentials to connect:
Host name
Username
Password
Database name
Port #
Username, password, database name, and port #, are practically already known to you by now. I'll explain:
Host name - Type in SHOW VARIABLES WHERE Variable_name = 'hostname';, and hit Enter. You'll get a table that has 2 columns: Variable_name and Value. In the Value column you should see something like yourUsername-yourProjectName-XXXXXXX, where the X's are a 7 digit number. Write this number down or save it some where. This is your host name. (If you're getting the quick rundown on this walkthrough, just start a new terminal and start up your mysql and select the database you want to use, then type in SHOW VARIABLES WHERE Variable_name = 'hostname';. Re-read this step from the beginning if you're confused.)
Username - Your username that you use to log in to Cloud 9.
Password - There is NO password for your database in Cloud 9.
Database name - This would be sample_db or whatever you named your database;
Port # - is 3306. In Cloud 9, all of your projects are wired to 3306. This is a universal constant of Cloud 9. It will not be anything else. Write this as you would an integer, not as a string. mysqli_connect() will interpret the port # as a long data type.
Last Step: Connect to the database with PHP! (using PHP)
Open up a PHP file and name it whatever you like.
I'll pretend that my host name is graham12-sample_db-1234567 for this example and that this is what my data looks like:
Host name: "graham12-sample_db-1234567"
Username: "graham12"
Password: ""
Database name: "sample_db"
Port #: 3306
So in PHP, insert your credentials accordingly:
<?php
//Connect to the database
$host = "grahamsutt12-sample_db-1234567"; //See Step 3 about how to get host name
$user = "grahamsutt12"; //Your Cloud 9 username
$pass = ""; //Remember, there is NO password!
$db = "sample_db"; //Your database name you want to connect to
$port = 3306; //The port #. It is always 3306
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
//And now to perform a simple query to make sure it's working
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "The ID is: " . $row['id'] . " and the Username is: " . $row['username'];
}
?>
If you get a result and no error then you have successfully setup a database and formed a connection to it with PHP in Cloud 9. You should now be able to make all the queries you can normally make.
Note: I demonstrated the last part without using parameterized queries for the sake of being simple. You should always use parameterized queries when working with real web applications. You can get more info on that here: MySQLi Prepared Statements.
For starters, the mysql_* functions are deprecated so you shouldn't be using them. Look at PDO or mysqli instead. Next, you'll want to try this per the example docs:
$link = mysql_connect('localhost:/lib/mysql/socket/mysql.sock', 'myUser', '') or die(mysql_error());
To find the ip running you project, create a test file with the code below, run it and put the result as host.
<?php
$ip = getenv("REMOTE_ADDR") ;
Echo "Your IP is " . $ip;
?>
You are using Cloud9 so it's a little different to use. To connect to MySQL you have to first create the MySQL server in C9. Type this in C9's command line:
mysql-ctl start
C9 will create your mysql server.
MySQL 5.1 database added. Please make note of these credentials:
Root User: <username>
Database Name: c9
Next to find your IP address type:
echo $IP
Now use this code with your username, the ip address, no password and the 'c9' database to access MySQL:
mysql_connect("<$IP>","<username>","") or die(mysql_error());
mysql_select_db("c9")
Hope this helps
The documentation show how start, stop, and run the mysql environment.
Start the MySQL shell mysql-ctl start then in yor file.php:
$ip = getenv("REMOTE_ADDR");
$port = "3306";
$user = "YorUsername";
$DB = "c9";
$conn = mysql_connect('$ip', '$user', '', '$db', '$port')or die(mysql_error());
mysql_select_db('$db','$conn')or die(mysql_error());
mysql_query("select * from YourTableName",'$conn')or die(mysql_error());
The line getenv("REMOTE_ADDR") return the same local IP as the application you run on Cloud9.
Ok first off this is not a backup job, and I know about using phpmyadmin and so on.
What I have is a Live server and a TEST server, People work on the live one, constantly modifying it. I want the database on the LIVE server to be copied to the TEST server every night.
Does anyone have a php script I could run either to copy down the whole thing (or at least specific tables)? I'm not that confident with using the command line so if there is a way of doing it that way I could do with some pretty specific instructions :P
I have dug around but everyone seems to be suggesting doing it manually or by using third party tools.
Any help much appreciated.
You could do something like this:
In your mysql host machine:
1- Create a .sh file
2- Inside of this sh, put:
- mysqldump -u myuser -p mypass mydatabasename > mydumpfile.sql
- scp mydumfile.sql user#remote_host:remote_dir
3- Add that sh to a cron Job, to a daily execute
(or something that meets your requeriments)
In the remote machine:
1- One sh script that look for a file(mysqldumpfile.sql) in the specific dir
2- This line : mysql -u remotemysqluser -p remotemysqlpass database < mydumpfile.sql
3- rm mydumpfile.sql
4- Add this sh on a daily cron 1 or two hours past the host cron.
Drop the test tables -
DROP TABLE testdata;
And then recreate them as copies of the live tables -
CREATE TABLE testdata LIKE livedata;
INSERT INTO testdata SELECT * FROM livedata;
This could be done through PHP like this -
<?php
$host = '127.0.0.1';
$dbname = 'database'
$user = 'user';
$pass = 'pass';
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$STH = $DBH->('DROP TABLE testdata');
$STH->execute();
$STH = $DBH->('CREATE TABLE testdata LIKE livedata');
$STH->execute();
$STH = $DBH->('INSERT INTO testdata SELECT * FROM livedata');
$STH->execute();
$DBH = null;
?>
You can add extra tables as required, but in my example it will make a table called testdata that mirrors the table called livedata.
Then set up a cron job to fire the script when required -
php /path/to/script.php