I am been trying to connect my android application with my 000Webhost account's MySql Database using PHP.
My Webhost server details are:
saravananoct14.web44.net
username: xxxx
HomeRoot: /home/xxxx
ServerName: server10.000webhost.com
IPAdress: "ipaddress"
MySQL database name:xxxx_sara
MySQL user name:xxxx_sarav
password for mysql:xxxx!4
my table name is ms.
column names:EMAIL_ID,Q1,Q2,Q3.
I have saved my .php files under public_html folder in phpmnMyAdmin.
config.php file is:
<?php
define ('DB_USER',"xxxx_sarav");
define('DB_PASSWORD',"xxxxx!4");
define('DB_DATABASE',"xxxx_sara");
define('DB_SERVER',"mysql1.000webhost.com");
?>
add.php file:
<?php
$res=array();
if(isset($_POST['EMAIL_ID']) && isset($_POST['Q1']) && isset($_POST['Q2']) && isset($_POST['Q3'])){
$EMAIL_ID=$_POST['EMAIL_ID'];
$Q1=$_POST['Q1'];
$Q2=$_POST['Q2'];
$Q3=$_POST['Q3'];
require_once __DIR__.'connect.php';
$db=new DB_CONNECT();
$result=mysql_query("INSERT into ms (EMAIL_ID,Q1,Q2,Q3) values ('$EMAIL_ID','$Q1','$Q2','$Q3')");
if($result){
$res["success"]=1;
$res["message"]="success";
echo json_encode($res);
}else{
}
}
else
{
$res["success"]=0;
$res["message"]="Required field(s) missing";
echo json_encode($res);
}
?>
I have used the same android program to connect it with my local wamp server and it worked.
I have given the following string as Url to parsed using JSON parser is:
http://"ip address"/add.php .
I am getting errors as Error Parsing the data. Cannot be converted into !Doctype...
I am pretty sure that I must make a change in the url. But could not find what changes I need to implement so that I can connect with the database.
Help me pls....
So after we discussed your Problem a long way I will write an Answer:
Please do not call your webservice via IP, always take the URL (especially when you have a webhoster)
Always check your PHP Script via a Browser on your PC, you will see the errors directly.
Debug the errors shown by your php script
Related
Good day,
I have created an IFTTT receipe that if a "myfox" alarm system is armed, a php script is executed on my NAS (192.165.x.x). The php script is supposed to trigger a stored procedure in my mysql database.
The following PHP script has been tested by other means and I'm sure that it works :
<?php
/*
php_update_mode_armed.php
*****************************************************************************************
* This script updates the value of the components in the table tbl_eedomus_current_mode
* It calls the stored procedure 'sp_tbl_eedomus_current_mode_armed'
*****************************************************************************************
Version 1.00, 09.06.2017, Initial version of the script
*/
mainProcess();
function mainProcess()
{
$ServerIP = "192.165.x.x";
$sqlUser = "domoos";
$sqlDatabase = "domoos";
$pw = "myPass";
// Connect
$mysqli = new mysqli($ServerIP, $sqlUser, $pw, $sqlDatabase);
if(!$mysqli) {[![enter image description here][1]][1]
header('Location: error.php?error=DbConnectionFailure');
die();
}
// Call stored procedure sp_tbl_eedomus_current_mode_armed
if(!$mysqli->query("CALL sp_tbl_eedomus_current_mode_armed ()"))
{
echo "OK";
if($mysqli) $mysqli->close(); // Close DB connection
//header('Location: error.php?error=QueryFailure');
die();
}
if($mysqli) $mysqli->close(); // Close DB connection
}
?>
Below, also, a screen shot of my "then" part of the IFTTT receipe.
Am I doing something wrong here or is the use of IFTTT not fit for the purpose I'm trying to achieve here?
Many thanks for your help on this matter and have a great day.
Most likly IFTTT can't access your NAS from the internet due to home router firewall etc. Also the ip address used in IFTTT shouldn't be a local ip like 192.168.* but your public ip address. You can figure this out by googling for "whats my ip".
Best way to test your setup using your laptop is to disconnect from local wifi network, tether your phone to your laptop and try visiting the NAS ip url to see if it still works. You can use chrome postman app to send out POST requests.
If that's all fine, get PHP to log incoming connections by writing to a file. file_put_contents("log.txt", print_r($_REQUESTS, true));
I would suggest trying with a GET request first with default content type. Good luck!
I need to access a remote database from my iPhone. I have an account on iPage, but as far as i know it does not support remoteMySql. I wrote a php script that will connect to the remote database. Currently i run it on localhost and this makes it of no use on the phone. Can someone tell me what is the best solution to my problem. Is there a way to use remote access on iPage, the database is on another server not iPage. Or can i write an api or something that will run on iPage ? The best thing would be if i can find a free webpage that can host my php script. Had one but its not working anymore. Any suggestions ?
<?php
$username = "qqqq";
$password = "qqqq";
$hostname = "qqq.qqq.qqq.qqq";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("ttbus",$dbhandle)
or die("Could not select examples");
$result = mysql_query("SELECT stations.name, stations.lon, stations.lat, station_display_rows.minutesToArrival,routes.number FROM stations,station_display_rows,routes WHERE stations.id = station_display_rows.stationId AND routes.routeId = station_display_rows.routeId");
while ($row = mysql_fetch_array($result)) {
echo "<h1>";
echo $row{'name'}."<h2>";
echo $row{'lon'}."<h3>";
echo $row{'lat'}."<h4>";
echo $row{'minutesToArrival'}."<p>";
echo $row{'number'};
}
mysql_close($dbhandle);
?>
I am not familiar with iPage, but if you want to access data from a web site, then you should create a REST endpoint that will return your data in JSON format. Your iOS app will then make this connection, grab the data and you can use it in your app. You can store this data in a a local database using Core Data, save it as a file or just use it in memory.
If you need help creating the REST endpoints in PHP, that should be directed to the PHP section or search for some tutorials, there are plenty.
To read the data from your iOS app, you should read this tutorial: NSUrlSession Tutorial DON'T try and use AFNetworking, its overkill for what you need to do.
If you are in shared hosting platform, remote MySQL is not supported in it. It is supported in their VPS/Dedi platform.
I have a php file which retrieves some important data from my database, for now if anybody access the php file via URL, it directly displays the data which i don't want to happen.
Is it possible create a password input box which will prompt for the database password and assign its value to $password variable (see the code below) , so that only if the user inputs the correct password, only then the file will interact with the database?
UPDATE TO THE EXAMPLE CODE :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>`
When this php file is accessed via a browser, it displays :
Peter Parker
Glenn Forbes
I don't want people to see the output directly! I want them to first input the password, so that php file interacts with the database and displays the output!
Hope you people got me this time!
If I were you (and if I'm understanding your problem correctly) I would use an htaccess file. Basically, you will create two files in the directory you want to protect. The first, you will name .htaccess. That's all you need in the file name. Open the file in an editing program (e.g: Notepad++) and insert the following code:
AuthType Basic
AuthName "restricted area"
AuthUserFile "the/path/to/the/directory/you/are/in/.htpasswd"
require valid-user
The .htpasswd you see is the file name of the second file you will create. Create that file (with the name .htpasswd), and open it to edit it. In that file, type in the username of the person who is to enter the directory.
JohnDoe
Followed by a colon.
JohnDoe:
Now, go to a website like http://www.htaccesstools.com/htpasswd-generator/ and type in the Username (just put in "test") and password you want in the fields provided. Submit the information.
After you do that, it will pop up with a formatted line of information. Copy the mess of letters after the colon and paste them after the colon in your .htpasswd file. Save your work.
JohnDoe:$apr1$eBsB98Mg$93ckYxSmT5BBfPqOS5a/6.
Now that you have done all that, when someone goes to the directory on your website, they will be prompted to give the username and password. If they know it, it will let them in, and then display what is in your PHP file (you will need to make sure the file is named index.php.
I hope that helps!
There are many ways...
<?php
if($_GET['token'] != 'a1a2a3a4a5') {
die('Wrong request!');
}
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Then access your page from:
http://www.example.com/readdata.php?token=a1a2a3a4a5
Apache (or any other server) will execute files based on the file extension it sees and that it has been told what to do with. If that isn't told specifically, it will display it simply as text.
If your server is running PHP files fine, you can include any filename you like - that includes the extension and PHP will assume it is simply PHP. If you try to get tricky however and call it a .php5 or a .include and you haven't set up your server to run these file types as PHP, it will be output to the user as simply text.
Set up the file types properly on your server or call them all by the default extension.
Based on the code you provided:
<?php
$host = "localhost";
$db_name = "NAME_OF_THE_DATABASE";
$username = "root";
$password = "PASSWORD_OF_THE_DATABASE";
?>
A user entering this exact URL will see a grand total of NOTHING. That is because when the file is being executed as PHP, it simply assigns the variables values - it doesn't ever display them.
If the file isn't associated as a PHP executable file, your server will send the contents to the user as they are - showing all your code as you wrote it.
From your question what i understood is you don't want any body to see the password, so i think
you can encrypt you php code and still run it on the server
user the following tools
you can definitely hide/encode/encrypt the php source code and 'others' can install it on their machine. You could use the below tools to achieve the same.
Zend Guard
IonCube
SourceGuardian
phpSHIELD
You should not see the code in the screen unless your file add .php, check extension.
I suggest you separate database detail in a new php file, and move it in up level directory
HTML CODE:
<form action="{your url}">
Please enter you password:<input name="password" type="password" />
<input type="submit" value="Submit" />
</form>
PHP code:
$password=$_GET['password'];
if($password=="1234"){
echo 'correct password';
//and add your code here
}
I'm getting a connection timed out when I try to connect to an external (not on the same server as this code is on) database through the following code. I know the settings of the database is set up right, and the login info is good, 'cause I can login fine from my computer with HeidiSQL. If anyone can see a problem with this code, thanks.
function database_connect(){
$link = #mysql_connect("xx.xxx.xxx.xx:3306","root","pass");
$sql_error = mysql_error();
if (!$link) {
echo "Connection with the database couldn't be made.<br>";
echo "$sql_error";
exit;
}
if (!#mysql_select_db("databasename")) {
echo "The database couldn't be selected.";
exit;
}
return $link;
}
database_connect();
have you tried adding the IP address of where that script is hosted to "Remote Database Access Hosts"?
If you're on cPanel, you need to allow the IP address who can remotely access the datase(mysql).
If you're not, then this is just an idea of what to do.
Problem known now.
My webhost does not allow connections to an external database.
This is my first time transferring my local dev site to another local site to test out, and can't access the database in the new site. Both computers are running XAMPP on Macs. The test site has successfully installed XAMPP, and has placed database files under Applications/XAMPP/xamppfiles/var/mysql. The test user is able to start Apache and MySQL, and see database files in PHPMyAdmin. The test user is also able to access the local web site with no error messages.
EDIT: The database files were copied over by copying/zipping the file on my end, and unzipping/dropping the copied files on the test end.
However, the local web site does not seem to see the database. Pages that are supposed to return data just show the default "sorry, we're sold out" message or show "image not found" graphics, and the admin is unable to log in.
The index page calls
include_once "common/base.php";
which consists of
<?php
// Set the error reporting level
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Start a PHP session
session_start();
$_SESSION['docroot'] = $_SERVER['DOCUMENT_ROOT'] . '/mysite/';
// Include site constants
include_once $_SERVER['DOCUMENT_ROOT'] . "/inc/constants.inc.php";
if ( !isset($_SESSION['token']) )
{
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['token_time'] = time();
}
// Create a database object
try {
$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
$_db = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
?>
If there was a connection problem, I would expect to see an error message returned, which I can verify by changing the constants in inc/constants.inc.php to bogus values. So I don't believe there's a connection problem.
If you were in my position, what would you check?
EDIT: I just found out about the Export function in PHPMyAdmin. I'm going to try deleting the db files that were copied over, exporting the files from PHPMyAdmin, and then importing them in the test machine.
EDIT: I just had the test machine do a simple
$sql = "SELECT FirstName From users";
$stmt = $_db->prepare($sql);
$stmt->execute();
$aaData = array();
while($row = $stmt->fetch(PDO::FETCH_NUM)){
$aaData[] = $row;
}
$stmt->closeCursor();
print_r($aaData);
on the index page, it shows the correct list of users. So the connection is good,
and there's an issue elsewhere. Would y'all say that I still need to delete the copied db and use the "correct" way (export/import), or is that a waste of time?
FINAL EDIT: I did redo the move using Export/Import and everything is working well now. Thanks to all.
First off, zipping files in the mysql data directory and moving them is not the best way to go. It can work if you have completely flushed/shut down the mysql server before moving them. You are better off using mysqldump or a similar tool to move entire databases at a time.
It sounds to me like you moved over your app's database files, but you probably forgot to add the user/password credentials to the new MySQL setup. You mentioned you use phpMyAdmin, so when you login on the other machine click the "Privileges" tab and make sure it matches up with the Privileges tab on your dev machine.
If it's not that, then it is entirely likely that by zipping and copying the files some/all of the tables were corrupted. Try using phpMyAdmin's Export and Import capabilities to move the database over. If the data is very large let me know and I can give you some command line entries to run.
Hope this helps.