I followed the steps at this website to create a background service using Android Studio that sends GPS data to a PHP script, that then posts to a MySQL database.
However, I am wanting to post to a Postgres database. I tried several things, but I have not had any success. These are the two PHP scripts from the website tutorial:
config.php script:
<?php
class DB{
private $dbHost="localhost";
private $dbUsername="USER";
private $dbPassword="PASS";
private $dbName="locationdb";
public $db_con;
public function __construct(){
if(!isset($this->db)){
try{
$pdo=new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db_con=$pdo;
}catch(PDOEXCEPTION $e){
die("Failed to connect with mysql :".$e->getMessage());
}
}
}
public function addGPSData($lat, $lon)
{
$sql="INSERT into tblgpslocation(latval, lonval) VALUES (:lat, :lon)";
$stmt=$this->db_con->prepare($sql);
$stmt->bindParam(":lat", $lat);
$stmt->bindParam(":lon", $lon);
$stmt->execute();
$newId=$this->db_con->lastInsertId();
return $newId;
}
}
?>
Script 2:
<?php
include "config.php";
$db= new DB();
if(isset($_POST['gpsdata']) && $_POST['gpsdata']=='true'){
$result=$db->addGPSData($_POST['latitude'], $_POST['longitude']);
if($result>0){
echo "OK";
}else{
echo "error";
}
}
?>
What changes do I need to make in order to make this connect to my postgresql database and post the incoming data?
Related
I have a project which has been developed in php 4 now it has to be upgraded to php 7.
The database is connected via odbc connection. When i try to connect to the database and run the index file nothing seems to pop up.
What i have done is i have converted my database into mysql and tried to connect to the database and it is connecting .
How do i change the complete odbc to mysql?
Please find below the odbc dataconnection file and let me know how to i connect it with mysqli.
<?php
//##################### ODBC CONNECT #######################
class DBConnectionManager{
var $DB;
function DBConnectionManager(){
$this->DB=$this->DBConnect();
}
function DBConnect()
{
//connection to database
// $dbconnect = odbc_connect(DB_SOURCE_NAME,DB_USERNAME,DB_PASSWORD)
$dbconnect = new mysqli("localhost",DB_USERNAME,DB_PASSWORD);
or die("Unable to Connect to SQL SERVER on ".DB_SOURCE_NAME);
return $dbconnect;
}
function DBexecute($query='')
{
$result = odbc_exec($this->DB,$query);
return $result;
}
function DBRows($query='')
{
$result=$this->DBexecute($query);
$num_row = 0;
while ($row = odbc_fetch_array($result))
{
$num_row++;
}
odbc_free_result($result);
return $num_row;
}
function mysqlFetchArray($arry){
return odbc_fetch_array($arry);
}
function closeConnection(){
if(isset($this->DB)){
odbc_close($this->DB);
unset($this->DB);
}
}
}
?>
What are the other changes i have to make?
Thanks in advance,
Renu
I'm a learning programmer and I'm trying to learn PHP.
Now the point is that I use alot of db connections in my new project. This are alot of different DB's an require different connection.
Does anybody a way where I can create a function what makes me use my code like this? Getdata($User, $beerbrand, $sales); and use these variables in my code? I use the same way to get the data out of the database everytime. But it's alot of code, where I think it should be possible to make that a little easier.
The way I use now:
mysql_connect($host, $user, $password) or die ("cannot connect");
mysql_select_db("$db_name");
$stuff = mysql_query("SELECT * FROM beers ORDER BY ID");
while($frontstuff = mysql_fetch_array($stuff)){
$us = $frontstuff['Beer'];
}
If you think this is a stupid question, please be gentle and explain it to me in a easy way.
Best regards
<?php
class Database {
private $connection; //Database Connection Link
private $userName; //Database server User Name
private $password; //Database server Password
private $database; //Database Name
private $hostname; //Name of database server
public function __construct() {
$this->hostname=your servername
$this->userName=yourusername
$this->password=yourpasswrod
$this->database=your bb name
try {
$this->connectlink = mysql_connect($this->hostname,$this->userName,$this->password);
if(!($this->connectlink)) {
throw new Exception("Error Connecting to the Database".mysql_error(),"101");
}
if(!mysql_select_db($this->database, $this->connectlink)) {
throw new Exception("Error Connecting to the Database1".mysql_error(),"101");
}
}catch(Exception $e){
//print_r($dbConfig);
echo $e->getMessage();
}
}
public function __destruct() {
#mysql_close($this->connectlink);
}
}
you can crete a database file like this for specifying connnection
and you can use this file in processing your query in another pages.Eg
<?php
include_once("database.php");
function __construct(){
$this->db = new Database;
}
public function getstuf($parameter){
$stuff = mysql_query("SELECT * FROM beers ORDER BY ID");
while($frontstuff = mysql_fetch_array($stuff)){
$us = $frontstuff['Beer'];
}
return stuff;
}
}
In a particular PHP - MySQL application i have been following a practice of creating and destroying the PDO connections from with in the public methods.
For Example:
public function updateCustomerNumber($customer_id, $customer_number){
$conn = new database_class();
$sql = "UPDATE customers set number = :CUSTOMER_NUMBER where id = :CUSTOMER_ID";
$query = $db->prepare($sql);
$query->execute(array(':CUSTOMER_NUMBER' => $customer_number, ':CUSTOMER_ID'=>$customer_id));
$conn->disconnect();
if($query->rowCount()>0){
return true;
} else {
return false;
}
}
So i have connected and disconnected the PDO Connection within the method. Database connect method:
public function connect() {
if (!$this->con) {
try {
$this->db = new PDO("mysql:host=$this->db_host;dbname=$this->db_name;charset=utf8", $this->db_user,$this->db_pass);
$this->db->exec("SET CHARACTER SET utf8");
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con = true;
return $this->db;
} catch (PDOException $e) {
$error = $e->getMessage();
echo $error;
}
} else {
return $this->db;
}
}
Database disconnect method:
public function disconnect() {
if ($this->con) {
unset($this->db);
$this->con = NULL;
return true;
} else {
return false;
}
}
I haven't come across any issue so far except that a in a couple of method i forgot to disconnect the PDO connection at the end of the script. However, I am not sure if there are any drawbacks of following this approach.
Reason i started questioning this method is when i check the MySQL global status values.
Aborted_clients: 32560
Aborted_connects: 128080
Going by the definition, Even If we don't close connection explicitly, PHP will automatically close the connection when your script ends.
What could be the cause behind these numbers? and is this approach of opening and closing a PHP PDO connections correct ?
I'm rewriting my php code for mysql database access (now using a class definitions). While I had the old code (using old style functions) working I struggle to get the code for creating tables right - I think the problem relates in particular to the right definition of the sql statement, pls see code below. The new aspect (for me) compared to the old code is that the sql table creation command now must include the name of a database different than the master_database for which the PDO connection is set up (within the class constructor).
I looked at http://dev.mysql.com/doc/refman/5.6/en/create-table.html (I use mysql v5.6) - the part starting with "The table name can be specified as db_name.tbl_name to ..." but I cant get the sql syntax right. If I'm right the sql syntax is wrong what should be the right syntax in the code below for $sql (using the construction with various variables)?
Thnx for your help in advance.
Simplified code:
<?php
define('DB_HOST', '***');
define('DB_NAME', 'MASTER_DATABASE'); //different name
define('DB_USER', 'root');
define('DB_PASS', '*****');
//class definitions
class Database {
private $_db = null; //databasehandler
public function __construct() {
try {
$this->_db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS, array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
));
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_db->query('SET CHARACTER SET utf8');
} catch (PDOException $e) {
exit('Error while connecting to database.'.$e->getMessage());
}
}
private function printErrorMessage($message) {
echo $message;
}
public function createDBTable($dbname,$dbtable,$tablestructure) {
try {
$sql = "CREATE TABLE `".$dbname."'.'".$dbtable.$tablestructure; //NOT CORRECT YET
$success = $this->_db->exec($sql);
return ($success > 0) ? true:false;
}
catch(PDOException $e){
$this->printErrorMessage($e->getMessage());
}
}
}//class
//code using class defs
$dbname = 'Mydatabase'; //just an existing database
$dbtable = 'Persons';
$tablestructure = '(FirstName CHAR(30),LastName CHAR(30),Age INT)';
$mydb = new Database();
if($mydb->createDBTable($dbname,$dbtable,$tablestructure)){
echo 'table creation success';
}
else{
echo 'table creation failure';
}
?>
You can replace you create table line as:-
$sql = "CREATE TABLE ".$dbname.".".$dbtable."".$tablestructure; //NOT CORRECT YET
Also instead of:-
$success = $this->_db->exec($sql);
Use the below lines:-
$stmt = $this->_db->prepare($sql);
$success = $stmt->execute();
Without the above 2 lines, the $succes variable will have value of 0 and although the table can be created, it would echo table creation failed.
Hope this helps.
Hi i am trying to move from MySQL to MySQLi in my PHP script, i had this system class with the function that connects to the database that i call whenever i need, with a simple method like this:
Sys::database_connect();
the actual code of the function is:
function database_connect(){
require 'conf.php';//configuration file with database variables (sql_)
mysql_connect($sql_serv, $sql_user, $sql_pw) OR die('ERRO!!! não ligou a base de dados');
mysql_select_db($sql_bd);
}
after calling the function i can query the database without problem.
But I cant do the same with mysqli if I put this in the sys class:
function database_connect(){
require 'conf.php';
$mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
if (mysqli_connect_errno()) {
printf("Ligação à Base de dados falhou: %s\n", mysqli_connect_error());
exit();
}
}
When I call
Sys::database_connect();
it connects to the database but i can't query has i used to what i would like would be a simple method as I have done with normal MySQL, if somebody can explain what am I doing wrong or why exactly I cannot do it like that...
Thank you in advance;
Fernando Andrade.
Your later queries have to use the mysqli connection identifier, you create when connecting to the database. So save this to a property of your system class and use it later on.
function database_connect(){
require 'conf.php';
$mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
if (mysqli_connect_errno()) {
printf("Ligação à Base de dados falhou: %s\n", mysqli_connect_error());
exit();
}
Sys::$dbConn = $mysqli;
}
and then later on
function query( $sql ) {
Sys::$dbConn->query( $sql );
// error handling etc.
}
I wrote an extend for the mysqli database class
class database extends mysqli {
function __construct() {
parent::__construct('host', 'user', 'password', 'database');
if(mysqli_connect_error()) {
die('Connect error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
parent::query("SET NAMES 'utf8'");
}
function query($query) {
$result = parent::query($query);
if(!$result) {
echo "<strong>MySQL error</strong>: ".$this->error."<br />QUERY: ".$query;
die();
}
if(!is_object($result)) {
$result = new mysqli_result($this);
}
return $result;
}
}
So connecting to database is $db = new database()
Executing a query is $db->query(YOUR QUERY);