I am trying to sent data to the server database, i implement it using wamp server it was working fine but when i installed the db on my domain and switched it to my domain its giving the following error.
I have kept my files inside a folder in root directory
Unknown MySQL server host 'DB_HOST' (0)
Below is my config file i am using to connect to the db
<?php
// Database configuration
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'xxxx');
define('DB_HOST', '192.210.195.245');
define('DB_NAME', 'tabanico_userlogin');
?>
here my code connecting db, config.php file contains the code pasted above
<?php
class DbConnect {
private $conn;
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
include_once dirname(__FILE__) . './Config.php';
$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
// returing connection resource
return $this->conn;
}
// Close function
function close() {
// close db connection
mysql_close($this->conn);
}
}
?>
and my file receiving data
<?php
include_once './DbConnect.php';
function createNewPrediction() {
$response = array();
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$db = new DbConnect();
// mysql query
$query = "INSERT INTO login(id,name,email,password) VALUES('$id','$name','$email','$password')";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
$response["error"] = false;
$response["message"] = "Prediction added successfully!";
} else {
$response["error"] = true;
$response["message"] = "Failed to add prediction!";
}
// echo json response
echo json_encode($response);
}
createNewPrediction();
?>
I have seen related post but didn't find useful answers. Can anyone help me in getting out of this. Thanks in advance.
Please post the code where you try to connect to the server. I guess you tried to connect using the following function:
mysql_connect('DB_HOST', 'DB_USERNAME', 'DB_PASSWORD');
Since you defined the host using define('DB_HOST', 'localhost');, you do not have to use apostrophes. DB_HOST is a constant here. So try to use to
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
instead. If you use apostrophes like in 'DB_HOST', it is interpreted as a string instead of the value of the constant DB_HOST containing localhost. That's a possible reason why you get the error that DB_HOST is an unknown host.
But please post the connection part of your code to see if that's really the mistake.
Related
I'm trying to connect to my Azure sql database using following code:
<?php
//Constants to connect with the database
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'xyz-server.database.windows.net');
define('DB_NAME', 'xyz_db');
<?php
//Class DbConnect
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
I'm getting this error
Type: ErrorException
Code: 2
Message: mysqli::__construct(): (HY000/9002): The connection string may not be right. Please visit portal for references.
File: /home/site/wwwroot/blingoo/include/DbConnect.php
Line: 22
I'm just beginning with Azure. Maybe I'm missing something. If you could simply point how to connect my database and web app(where I'm using php files to connect to the database), that will be great.
Seems to me that your code is trying to connect to MySQL rather than MSSQL.
To connect to MSSQL use the following:
<?php
$serverName = "your_server.database.windows.net"; // update me
$connectionOptions = array(
"Database" => "your_database", // update me
"Uid" => "your_username", // update me
"PWD" => "your_password" // update me
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql= "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
FROM [SalesLT].[ProductCategory] pc
JOIN [SalesLT].[Product] p
ON pc.productcategoryid = p.productcategoryid";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
echo (sqlsrv_errors());
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);
}
sqlsrv_free_stmt($getResults);
?>
source: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-php
Since you are trying to connect to Azure SQL you can use PDO_DBLIB driver, if you have this extension installed. See php -m.
$config = [
'dsn' => 'dblib:host=xyz-server.database.windows.net;dbname=xyz_db',
'user' => 'username',
'pass' => 'password',
];
$connection = new PDO($config['dsn'], $config['user'], $config['pass']);
$sth = $connection->prepare('Your query comes here;');
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_CLASS);
foreach ($rows as $row) {
// Do the processing here
}
I am trying to setup a connection to my MySql database via a php page which is hosted on 123-reg. The PHP page is "http://domainName.biz/android_connect/get_all_bars.php" which at the moment the page comes up blank?
The code for that page is as follows:
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM pubbar");
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["pubbar"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$pubbar = array();
$pubbar["Pubbar_ID"] = $row["Pubbar_ID"];
$pubbar["Pubbar_Name"] = $row["Pubbar_Name"];
$pubbar["Pubbar_AddressLine1"] = $row["Pubbar_AddressLine1"];
$pubbar["Pubbar_AddressLine2"] = $row["Pubbar_AddressLine2"];
$pubbar["Pubbar_LocationID"] = $row["Pubbar_LocationID"];
$pubbar["Pubbar_Postcode"] = $row["Pubbar_Postcode"];
$pubbar["Pubbar_Latitude"] = $row["Pubbar_Latitude"];
$pubbar["Pubbar_Longitude"] = $row["Pubbar_Longitude"];
$pubbar["Pubbar_TypeID"] = $row["Pubbar_TypeID"];
$pubbar["Pubbar_DateCreated"] = $row["Pubbar_DateCreated"];
$pubbar["Pubbar_DateModified"] = $row["Pubbar_DateModified"];
// push single product into final response array
array_push($response["pubbar"], $pubbar);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No bars found";
// echo no users JSON
echo json_encode($response);
}
This code works on my local WAMP server on my PC
As you can see at the top it connect to another PHP page called "db_connect.php" and the code for that is below:
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
Again this work on my local WAMP server database. This also connects to another PHP page called "db_config.php" and the code for that is below:
<?php
/*
* All database connection variables
*/
define('DB_USER', "<USER>"); // db user
define('DB_PASSWORD', "<PASSWORD>"); // db password (mention your db password here)
define('DB_DATABASE', "<DATABASE>"); // database name
define('DB_SERVER', "cust-mysql-X-X"); // db server
?>
As mentioned I have a wamp server setup for testing usage and all this functions as expected through that. However now I wish to put it on my server here, so it is all permanently accessible for my portfolio Android application and the get_all_bars.php page is coming up blank. I've messed around and changed code where I thought it might need changing but unfortunately the page still comes up blank. I have spoke with them before and the config data i.e username, password etc is all correct but I cannot figure out what might be wrong in the rest of this code.
I am getting this message in my site all of a sudden without making any changes in the config file. I will post my config code to see if there are any issues with it.
define('DB_SERVER', 'www.victorexoticagoa.com');
define('DB_SERVER_USERNAME', '******');
define('DB_SERVER_PASSWORD', '********');
define('DB_DATABASE', 'victor');
define('USE_PCONNECT', 'false');
define('STORE_SESSIONS', 'mysql');
define('CFG_TIME_ZONE', 'Asia/Kolkata');
The above code is from the configure.php file.
The below code is the connection:
tep_db_connect() or die('Unable to connect to database server!');
And the code below is the function which does the connection:
function tep_db_connect($server = DB_SERVER, $username = DB_SERVER_USERNAME, $password = DB_SERVER_PASSWORD, $database = DB_DATABASE, $link = 'db_link') {
global $$link;
if (USE_PCONNECT == 'true') {
$server = 'p:' . $server;
}
$link = mysqli_connect($server, $username, $password, $database);
if ( !mysqli_connect_errno() ) {
mysqli_set_charset($$link, 'utf8');
}
return $$link;
}
Any help will be gladly appreciated. Thanks
Check if your database is up by using the following command in a command shell:
mysql --host=www.victorexoticagoa.com --port=yourport --user=youruser --pass=yourpass
If it cannot connect, the problem is the server, not your code.
Have you checked if that is the way you need to connect or the port to connect? I dont see the port (thats not supposed to be port 80 most times). Please check docs of the host and ask for details. It should be documented.
I am new to php development.I have created a database using phpmyadmin.Now i want all the data to be displayed on the page.But when ever i try to run the file nothing is showing up.I dont know why this is happening.
db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesreview"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error($con));
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error()) or die(mysqli_error($con));
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
Code
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$con=new db_connect();
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
while($row=mysqli_fetch_array($result)){
$row_array['movies_id']=$row['movies_id'];
$row_array['movies_name']=$row['movies_name'];
$row_array['movies_description']=$row['movies_description'];
$row_array['movies_time']=$row['movies_time'];
$row_array['movies_release_date']=$row['movies_release_date'];
$row_array['movies_youtube_link']=$row['movies_youtube_link'];
$row_array['recent_upcoming']=$row['recent_upcoming'];
$row_array['movies_image']=$row['movies_image'];
$row_array['movies_actors']=$row['movies_actors'];
array_push($response,$row_array);
}
echo json_encode($response);
?>
Error what i am getting
There are a few things wrong with your code.
The space between <? and php
A missing tick for your table, and a missing semi-colon for your query.
A missing DB connection link.
Your code:
<? php
^ space
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails WHERE `recent_upcoming` =0"
^ ^
$result=mysqli_query($strQuery);
^ no DB connection
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$strQuery="SELECT * FROM `moviesdetails` WHERE `recent_upcoming` =0";
$result=mysqli_query($con,$strQuery);
Using error reporting http://php.net/manual/en/function.error-reporting.php would have signaled that, including or die(mysqli_error($con)) to mysqli_query()
You've edited your question. You are mixing mysqli_ and mysql_ functions. They do not mix.
All mysql_error should be mysqli_error($con) and mysql_close() to mysqli_close($con)
Edit:
Replace the entire contents of db_connect.php with the following:
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "moviesdetails"); // database name
define('DB_SERVER', "localhost"); // db server
$con = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
Edit #2:
while($row=mysqli_fetch_array($result)){
$response[] = $row;
$row['movies_id'];
$row['movies_name'];
$row['movies_description'];
$row['movies_time'];
$row['movies_release_date'];
$row['movies_youtube_link'];
$row['recent_upcoming'];
$row['movies_image'];
$row['movies_actors'];
}
echo json_encode($response);
You have missing connection link as parameter in your mysqli_query() function. Should be:
$result = mysqli_query($connection_link, $strQuery);
http://php.net/manual/en/mysqli.query.php
$connection_link will have in this case following format:
// include db connect class
require_once __DIR__ . '/db_connect.php';
$connection_link = new DB_CONNECT();
But as #Fred -ii- said in comments, you have some syntax errors in PHP and SQL query too.
Your DB class is badly designed, you should store connection link in property and making queries through this class.
I am having difficulty getting my Android application to transmit the input it has received to myphpadmin server.
I am wondering what do i need to add to my Andriod coding so that my application is able to get the php script to run and transmit the information to the server.
What i have done so far is creating php scripts for configuration and connection purpose.
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', "password"); // db password (mention your db password here)
define('DB_DATABASE', "Wifi"); // database name
define('DB_SERVER', "http://andy-009.dlink.net/"); // db server
?>
and
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();}
// destructor
function __destruct() {
// closing db connection
$this->close();}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con; }
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
} }
as well as a insertion php script
update_product.php
<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['WifiMacAddress']) && isset($_POST['WifiSSID']) && isset($_POST['WifiLatitude']) && isset($_POST['WifiLongtitude']) && isset($_POST['WifiLocation'])) {
$WifiMacAddress = $_POST['WifiMacAddress'];
$WifiSSID = $_POST['WifiSSID'];
$WifiLatitude = $_POST['WifiLatitude'];
$WifiLongtitude = $_POST['WifiLongtitude'];
$WifiLocation = $_POST['WifiLocation'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE Wifi SET WifiSSID = '$WifiSSID', WifiLatitude = '$WifiLatitude', WifiLongtitude = '$WifiLongtitude' , WifiLocation = '$WifiLocation' WHERE WifiMacAddress = $WifiMacAddress");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
i think communicating between android and php, JSON would be helpful.
you can parse the data into JSON at both ends and transmit them over internet using web-services