I post data to remote php file and there using post method am saving data to remote mysql database as simple as it is.
But my worry is am getting data every 30sec to 1minute and sending to server via http post from android mobile i.e from 'N' no of mobiles so, will data collide? is there a chance of loosing data? ex: from 100mobiles
currently am using 000webhost.com free hosting, am planning to move for paid one.
But do I need to buffer all incoming data and then save will it avoid data loss? or continue with my same approach and have high speed server?
I dont have much knowledge about maximum at what speed server can process incoming data. what if many data comes from many mobiles at same time? do I need to manually buffer or server does for me.
if manual buffer please share some code so that I can understand better.
(battery of android mobile I have taken care and am using gps and network provider)
<?php
$longitude = $_POST['lon'];
$latitude= $_POST['lat'];
$imei= $_POST['imei'];
$speed = $_POST['sp'];
$date = $_POST['date'];
if($longitude != "" && $latitude != "")
{
$mysql_host = "xxx";
$mysql_database = "xxx";
$mysql_user = "xxx";
$mysql_password = "xxx";
$con=mysql_connect($mysql_host,$mysql_user,$mysql_password ) OR DIE ("Unable to select db".mysql_error());
if($con)
{
mysql_select_db($mysql_database);
//check if imei number already exists
$sql="select emp_name from mob_reg where imei='$imei'";
$result=mysql_query($sql);
if((mysql_num_rows($result))== 0)
{
echo "invalid";
}
else
{
$sql="insert into details(imei,lon,lat,speed,date) values('$imei','$longitude','$latitude','$speed','$date');";
mysql_query($sql) or die("couldnt insert");
}
}
else{
echo 'invalid';
}
}
?>
I don't think you need to worry about buffering in your code.
Your code should deal with each request as efficiently as possible.
Your infrastructure should be set up according to how much traffic you expect.
If your service is going to be very busy, then you can think about load-balancing (having more than one web-server and/or database server handle the incoming requests, depending on where the bottlenecks are)
Related
I am trying to send two values to my server to be input into a database in the same row, the problem I have is that it isn't possible to send both values in one request. So what I want to do is send both the values in separate requests but handle them on the server at once so I can add the values into a database as one entry. My php isn't very strong, and I have no idea how to go about doing this. Is it possible? How would I do it?
Here's what I have so far:
<?php
$user = "user";
$pass = "pass";
$table = "database";
if(isset($_POST['currentUser']))
{
$userID = 'currentUser';
}
if(isset($_POST ['e.regid']))
{
$regid = 'e.regid';
}
if ($regid && $userID != null)
{
$con = mysqli_connect("localhost", $user, $pass);
mysqli_select_db($con, $table);
if (mysqli_connect_errno$con))
{
echo "Error connecting to the DB: " . mysqli_connect_errno());
}
else
{
"INSERT INTO gek_devices('regid', 'pin') VALUES ($regid, $userID)";
}
}
No, due to network latency and unreliability there's not even any guarantee that both requests will ever arrive at the server, let alone within a minute apart, let alone that you could run code once handling both requests. In practice chances are over 90% that both requests will not even be handled by the same Apache process on the server, given that a default Apache install on *nix will prefork 10 'spare' instances.
If you need to process the data 'simultaneously` you need to send them in the same request, that's the only way to guarantee atomicity.
Your intended solution is completely impossible, but also a glaring XY problem. Solve why you can't send the values simultaneously right now instead of focusing on hacky workarounds following that.
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.
My first post, because I haven't found answer to this problem anywhere! And i looked way beyond Google.. :)
DESCRIPTION:
So I have a set-up where an arduino device is connected to a laptop via USB serial cable and the laptop is connected to internet.
Like this: http://postimg.org/image/cz1g0q2ib/
arduino ---USB---> laptop (transit.py) ---WWW---> server (insert.php)-> mysql DB
There is a python script (transit.py) on the pc running continuously and listening to the COM port, analyzing received data and forwarding it to a file (insert.php) on a remote server (a free hosting site)
See code to learn how that works...
Then there is the insert.php script that receives this data (still almost every second), analyzes it and stores it in the mySql database.
This, however, is not the only file that requires mySql connection, therefore i include connect.php at the beginning of every such file.
PROBLEM:
Warning: mysqli::mysqli() [mysqli.mysqli]: (42000/1226): User 'user' has exceeded the 'max_connections_per_hour' resource (current value: 1500) in /server/connect.php on line 8
As a result of all this data travel and it's frequency (and cheapness of the hosting) i run into a "maximum connections per hour exceeded" error. The limit is 1500 per hour and i can't change it (it's a remote server). And no, i don't want to pay for hosting to get a bigger allowance - that's not the point- the issue is inefficiency of my code. Can i have one, persistent connection? Like a service?
Sending data from python script straight to remote mysql is not an option, because i don't have access to this feature.
CODE:
transit.py:
try:
ser = serial.Serial('COM4',9600,timeout=4)
except:
print ('=== COULD NOT CONNECT TO BOARD ===')
value = ser.readline()
strValue = value.decode("utf-8")
if strValue:
mylist = strValue.split(',')
print(mylist[0] + '\t\t' + mylist[1]+ '\t\t' + mylist[2])
path = 'http://a-free-server.com/insert.php'
dataLine = {"table": mylist[0], "data": mylist[1], "value": mylist[2]}
toServer = requests.post(path, params=dataLine, timeout=2)
insert.php:
<?php
include 'connect.php';
//some irrelevant code here...
if (empty($_GET['type']) && isset($_GET['data'])) {
$table = $_GET['table'];
$data = $_GET['data'];
$value = $_GET['value'];
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
else
{
date_default_timezone_set("Asia/Hong_Kong");
$clock = date(DATE_W3C);
if (isset($_GET['time'])) {
$time = $_GET['time'];
}
else{
$time = $clock;
}
echo "Received: ";
echo $table;
echo ",";
echo $data;
echo ",";
echo $value;
echo ",";
echo $time;
if ($stmt = $mysqli->prepare("INSERT INTO ".$table." (`id`, `data`, `value`, `time`) VALUES (NULL, ?, ?, ?) ON DUPLICATE KEY UPDATE time='".$time."'"))
{
$stmt->bind_param('sss', $data, $value, $time);
$stmt->execute();
$stmt->free_result();
$stmt->close();
}
else{
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
}else{
echo " | DATA NOT received!";
}
?>
connect.php:
<?php
define("HOST", "p:a-free-host.com"); // notice the p: for persistence
define("USER", "user");
define("PASSWORD", "strongpassword1"); // my password. don't look!
define("DATABASE", "databass");
$GLOBALS["mysqli"] = new mysqli(HOST, USER, PASSWORD, DATABASE, 3306);
$count = intval(file_get_contents('conns.txt'));
file_put_contents('conns.txt', ++$count); //just something i added to monitor connections
?>
P.S. Everything works fine and all data is handled in a rather desirable manner, except for exceeding the limit and perhaps some other hidden caveats.
Any suggestion on how to decrease the connection count but still receive data every second?
If I have understood your issue correctly, your web host sucks. If you are limited to 1500 connections / hour, and each page requires a connection, that means you can never exceed 1500 page views per hour; that's not very much.
Many programming languages support connection pooling; in this model, the server opens one or more connection at start-up, and individual page requests get one of those connections when they need them. This reduces the overhead of opening and closing connections. See here for a discussion of connection pooling and PHP. You may be able to use one of the answers without too much trouble.
The alternative - and probably better - solution is to batch up data in your Python scripts so you don't have to connect to the web server so often. The classic waty to do this for applications that aren't time critical is to use a message bus. I'm not a Pythonist, but this should do the job...
Did you try to create a script that is all the time alive(here you make the connection)(S1) and then the rest?
(S2)
In the script that you are doing the operations first check if the connection is alive and if is not redo connection.
Close the connection in S1 at the end of the script.
I have to build an android app which connects to a remote MYSQL webserver and retrieve information for display purpose.
So I did research coz I had no idea where to start. I read an article it mentions the better approach for that is to use php script. And didn’t know anything about how server, database and php works, so I studied php from here “http://www.homeandlearn.co.uk/php/php12p1.html” to understand and downloaded WhampServer to do some testing. On local machine everything worked fine.
But main thing I don’t understand is “HOW TO CONNECT TO REMOTE SERVER/DATABASE”.
It’s obvious that I’m doing something really stupid, I just need help to find out what am I doing wrong.
When we test php script on local machine in webrowse we use "localhost/some.php." But when I want to test same php script on remoter server from my local machine then what and how should I do? Do I need to make some changes in configuration file on server side?
I have done more research before asking this question here to understand remote server connection in php but I still don’t understand. I have gone through almost all the pages within the link below:
https://www.google.co.uk/search?q=connect+to+remote+mysql+webserver+php&rlz=1C1AVSX_enGB447GB448&oq=connect+to+remote+mysql+webserver+php&aqs=chrome.0.69i57j69i62l3.19724j0&sourceid=chrome&ie=UTF-8#fp=5a2359cf96dc5f79&q=how+to+connect+to+remote+mysql+web+server+php
And help would be much appreciated.
If my question is not clear please let me know I'll try to explain more. or think of it as if you have to connect to a remote MySQL server how would you do , means what is the process and steps involved in that.
Thanks everyone.
Edit
I have created a database "dealt3_raj_test" on remote server. and when I type "examplewebserver.CO.UK/myphpscriptname" in my web browser.
It gives me error "An error occurred , You have reached the error page"
<?PHP
$user_name = "dealt3_raj";
$password = "5dN5nh&eMd(vCR$dzk";
$database = "dealt3_raj_test";
$server = "examplewebserver.CO.UK";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_handle)
{
print "Connected";
}
else
{
print "Can not connect to server";
}
if ($db_found)
{
print "DataBase found";
}
else
{
print "DataBase not found";
}
?>
Adding onto #user4035's comment, after opening the connection, use JDBC in your Android/Java code to interact with the database.
That said, it is not good practice. Rather create a web service
Your application may experience latency/connectivity issues. This will impact performance.
Your MySQL server will have to be open to remote connections which is strongly advised against
If your Android App is intended for public usage, it means the database username and password of your MySQL server reside on everyone's phone using your app. Encrypted or not this makes your database server a "step less" secure
Well answered here on SO (JDBC vs Web Service for Android)
use this code to connect with data base
$username = "database user name";
$password = "DB password";
$hostname = "hostname";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("data base name",$dbhandle) or die("Could not select examples");
I am EXTREMELY new to the html/php scene but I have been working at this for hours. I am stumped.
I am trying to connect to a sql database that will store username and password information. I use fortune city for hosting and I have already used their phpAdmin to setup up all of the necessary stuff (db, tables, etc..).
I am using Eclipse with Zend on the side. I am also running Sql Server and Apache 2.2.
I believe my issue is the following:
I have a db located at a certain ip address (remote fortunecity server) and I am testing my project on the local server. Fortune city offers two different host names, one for internal connections and one for external connections. I get different results from each one:
If I connect to the internal site it doesn't make any connection, I know this because of my die statement. If I connect to the external host it connects, but doesn't allow me to connect to the database. (see cases below code)
Currently my process is as follows. (PLEASSSSE TELL ME A BETTER WAY IF I'M DOING THINGS THE INEFFICIENTLY, I feel dirty every time I do it!!)
Create or edit my index.php, login.php, etc... in eclipse.
Copy the files that I edit into my Apache root.
Go back to eclipse and run the project in a browser "firefox."
repeat n to the n times.
Keep in mind my sql database is located on the net
Can this be done? Testing locally while accessing a db on the net?
Here is the code:
<?php
if (!isset($_POST['username']) || !isset($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
elseif (empty($_POST['username']) || empty($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
else{
$user = addslashes($_POST['username']);
$pass = md5($_POST['password']);
$dbHost = "mysql3341.dotsterhost.com";
$dbUser = "*********";
$dbPass = "******";
$dbDatabase = "**********";
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
$result=mysql_query("select * from userInfo where username='$user' AND password='$pass'", $db);
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
session_start();
session_register('username');
echo 'Success!';
header( "Location: checkLogin.php" );
}
}
else {
echo 'Incorrect login name or password. Please try again.';
}
}
?>
Again, I have never made it past
Case :1 $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
Case :2 mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
Thanks for reading my novel!
Can this be done? Testing locally while accessing a db on the net?
Yes you can, but be aware if you are storing anything sensitive in your database you probably wouldn't want to be sending that data unencrypted over the net. (Unless you are connecting over a VPN or another type of secure network connection.)
Usually you'd want to setup a development environment on your local box or you can edit your files locally in something like Aptana (http://www.aptana.com/) and have it automatically deploy your files to the server every time you save.
Also, as suggested in the comments, using a framework to develop on usually give you a powerful database library without the need to reinvent it on your own. (That is unless you feel like wrapping your own!)