Inserting data into a remote database - php

I'm trying to make a web/login page, where if a user is in certain location then they can be able to insert data in the database based on their location.
For example, if we have two users bob and max, one in A(bob) and the other in B(max).
If bob logs into the system username... bob password... 123 location.. A, he should be able to to insert his data on the database located on his PC same as max but they should use a single application.
Now my question is how can I achieve this. For example I've a login script below which is communicating with my localhost (A) and i also want to include a remote connection to my other PC on the LAN (B), using Mysql database installed on both computers, I can connect to Mysql database using Mysql workbench but how can I do it using a script in PHP?
login page
<?php
if(isset($_POST['login'])){
include 'includes/config.php';
$uname = $_POST['uname'];
$pass = $_POST['pass'];
$query = "SELECT * FROM admin WHERE uname = '$uname' AND pass = '$pass'";
$rs = $conn->query($query);
$num = $rs->num_rows;
$rows = $rs->fetch_assoc();
if($num > 0){
session_start();
$_SESSION['uname'] = $rows['uname'];
$_SESSION['pass'] = $rows['pass'];
echo "<script type = \"text/javascript\">
alert(\"Login Successful.................\");
window.location = (\"admin/index.php\")
</script>";
} else{
echo "<script type = \"text/javascript\">
alert(\"Login Failed. Try Again................\");
window.location = (\"login.php\")
</script>";
}
}
?>
connection.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "cars";
$conn = new mysqli($host, $user, $pass, $db);
if($conn->connect_error){
echo "Failed:" . $conn->connect_error;
}
?>
Configuring two connection scripts is what i have in mind, but i don't
think it will work.
Any suggestions would be appreciated.
Thanks

Related

Openshift mysql write access from php

I have an issue with my mysql database that I can't resolve : I have a scalable application with mysql and php. I can access the database but I can only read ('SELECT') the data but I don't seem to have the permission to write ('INSERT INTO...').
Here is the php file for SELECT command which is working :
<?php
$cnx = mysql_connect("domain:port","username","password");
$db= mysql_select_db( "application_name" );
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM `User` where `userName`='$username' AND `password`='$password'";
$requete = mysql_query($sql ,$cnx);
if(mysql_num_fields($requete)==0){
echo "0";
}
else {
$result = mysql_fetch_assoc( $requete );
echo $result["userKey"];
}?>
And the php file for INSERT INTO command which is not working :
<?php
$con=mysql_connect("domain:port","username","password","application_name");
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$sql="INSERT INTO User(userName,emailAdress,password) VALUES ('$username','$email','$password')";
if (mysqli_query($con,$sql))
{
echo "0";
}
?>
Thanks for your help !
Install PHPMyAdmin, and then create a new schema. You should be able to carry out all usual executions into that schema you created.
Alternatively, SSH into your gear, type 'mysql'. This will give you access to the database. Create a schema from there and then in your PHP script, when you connect to the db, specify the schema as the one you created.

MySQL connection works on Localhost but not on webserver

Good day Everyone..
I have an issue that is puzzling me and I can not seem to find a way to solve it. Even the tech support in my hosting service can not solve it.
I have created a small script to do a simple task. I require the employees to log in to perform any said task.
I have tested the application on a development server and the login script works perfectly, but when I place it on the webserver the connection is never established.
I use the same username and passowrd in the dbcon.php file to log in using phpMyAdmin and it works, and I run the queries and they also work.
Here are the files:
1: dbcon.php
<?php
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
?>
2: login.php:
<?php
session_start();
require "../../_dbcon/_dbcon.php";
//Timezone settings:
$timezone = "Asia/Kuwait";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
// check the username has only alpha numeric characters
if (ctype_alnum($_POST['username']) != true)
{
//if there is no match
$message = "Username must be alpha numeric";
}
//check the password has only alpha numeric characters ***/
if (ctype_alnum($_POST['password']) != true)
{
//if there is no match ***/
$message = "Password must be alpha numeric";
}
else
{
// if we are here the data is valid and we can insert it into database
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
//SQL Injection Precaution:/
$username = stripslashes($username);
$password = stripslashes($password);
try
{
//Select Statement:
$stmt = $db->query("SELECT *
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
$result = $stmt->rowCount();
}
catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
some_logging_function($ex->getMessage());
}
// If result matched $username and $password, there will be one row
if($result==1){
// check if the account is active:
$stmt = $db->query("SELECT id_status
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id_status= $row['id_status'];
}
$stmt = $db->query("SELECT employee_id
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$employee_id= $row['employee_id'];
}
//Check if account is active:
if($id_status == "A"){
// Create Session ID:
$session_id = "";
$_SESSION['sid'] = "";
$session_id = mt_rand(100000, 999999);
$sid_update = $db->query("UPDATE dms_gt_users
SET `session_id`='$session_id'
WHERE username='$username' and password ='$password'");
$_SESSION['sid'] = $session_id;
//Get last login details:
$current_login = date("Y-m-d H:i:s");
$stmt = $db->query('SELECT `last_log_in`
FROM dms_gt_users
WHERE `employee_id` = '.$employee_id);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$last_log_in = $row['last_log_in'];
}
$_SESSION['last_log_in'] = $last_log_in;
//get IP address:
$ip = getenv('REMOTE_ADDR');
//Add login details to Activity Log:
$stmt = $db->query("INSERT INTO dms_activity_log
(`employee_id`, `activity_date_time`, `activity`, `ip_address`)
VALUES ('$employee_id', '$current_login', 'Logged in', '$ip')");
//Add login details to users table:
$stmt = $db->query("UPDATE dms_gt_users
SET `last_log_in`='$current_login'
WHERE username='$username' and password ='$password'");
//update session login
$_SESSION['login']= 1;
//save employee id to session
$_SESSION['employee_id'] = $employee_id;
// redirect to portal home:
header ("Location:../../../home.php");
}
//Account is not Active:
else{
header ("Location:../../../index.php");
}
}
//Username or password are incorrect
else {
header ("Location:../../../index.php");
}
}
?>
What am I doing wrong? and if my code is ok, what should I tell the hosting Tech Support to look for?
Thanks!!
EDIT
#noc2spam: I have updated the connection string as you have advised, I get no errors logged. I var_dump the $db, and I get object(PDO)#1 (0)
It is pretty hard to tell why this is happening without looking into the server itself. I suggest that you enable the Exception mode so that you can see what the problem is. For example:
try {
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}
It would be much easier to troubleshoot now. Check if you are getting any error and update the original question with the message if possible. I will edit this answer after that.
IF Roger Ng's answer doesn't solve it, then you may have a firewall blocking your connection. Check your mysql server port... typically 3306.
Check your database's url. Generally, in shared/dedicated hosting environment, DB server and App Server are on different machines. Also, many service providers do not provide mysql cluster services on port 3306. So, please get the correct URL and port of the database from your hosts CPanel or tech support team.
Also, add the App server's IP address to the permitted IP addresses list in Remote MySQL Cpanel interface.

Registration script.php does not work

I have a registration script that doesn't work. It used to work but then suddenly it stopped working. I dont know what I've done or what happend. I have tried for like an hour now to find out where the problem is, but I can't seem to find it.
What happens? When I click register I don't get any errors but it doesn't upload to the database:
When I type: $res = mysql_query($query) or die ("ERROR"); it displays ERROR so I think it's related to that code:
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
$country = mysql_real_escape_string($_POST['country']);
$rights = '0';
$IP = $_SERVER['REMOTE_ADDR'];
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$query = mysql_query("SELECT username FROM users WHERE username = '".$username."'");
if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use.';
}
else{
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country',$rights,$IP,NOW())" ;
$res = mysql_query($query);
header("location:load.php");
}
}
I think you are getting the error because you are missing some quotes in your query for two columns wich really looks like not integers
'$email','$country',$rights,$IP,NOW())" //$rights and $ip doesn't have quotes
so your query would look like
"insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country','$rights','$IP',NOW())"
Use mysql_error() in order to see what the error message is. If you haven't changed anything in the script then it's either your database structure has changed or your rights have.
Update:
You don't have quotes around your IP value, which is surprising because you said that query worked until now. Anyway you should also consider saving IPs the RIGHT way. Good luck!

SQL Server log in system

Hello i am having trouble connecting to sqlserver 2008 i am trying to create a simple log in system and this is what i have:
<?php
session_start();
if(!isset($_SESSION["user_id"])){
header("location:../../login.html");
}
?>
<?php
$username = $_POST[txt_usernmae];
$user_id = $_POST[txt_password];
mysql_connect($server, $username, $password) or die("No Server Found");
mysql_select_db($schema) or die("No Connection");
?>
I think you mispelled username
$username = $_POST[txt_usernmae];
Instead use
$username = $_POST['txt_usernmae'];
Remember to use '' when you handle POST or GET
Change this
$username = $_POST[txt_usernmae];
$user_id = $_POST[txt_password];
to
$username = $_POST['txt_usernmae'];
$user_id = $_POST['txt_password'];

Connect a different database on the log-in process only

The codes I'm working on are a bit confusing since I didn't make this one. But what I want to do is get the login information from a different database. I can't just modify the config.php of the database connection cause it will mess up the whole system.
I tried the trick to connect 2 databases by storing different variables on mysql_connect. But in this case, its a bit confusing.
Is there another way to just change the database connection only once in the logging in process?
login.php (the php file once the login info is submitted)
include("inc/config.php");
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM clients WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$client_accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('client_accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$client_accesslogin = $_SESSION['client_accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
session_register("client_company");
list($clientid, $name,$first_name,$last_name, $pass, $email, $company) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$fname=$first_name;
$lname=$last_name;
$client_email = $email;
$client_company = $company;
$cisloggedin = 'Yes';
session_register("cisloggedin");
session_register("fname");
session_register("lname");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM admins WHERE name = '$name' AND password = '$password'";
$result = mysql_db_query($database, $query, $connection);
$date_in = date("Y-m-d");
$time_in = date("H:i:s");
$accesslogin = $name;
if (mysql_num_rows($result) == 1)
{
session_start();
session_register('time_in');
session_register('date_in');
session_register('accesslogin');
session_register('remoteaddr');
$_SESSION['time_in']=$time_in;
$_SESSION['date_in']=$date_in;
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$accesslogin = $_SESSION['accesslogin'];
session_register("client_id");
session_register("client_name");
session_register("client_email");
list($clientid, $name, $pass, $email) = mysql_fetch_row($result);
$client_id = $clientid;
$client_name = $name;
$client_name = "admin";
$client_email = $email;
$isloggedin = 'Yes';
session_register("isloggedin");
header("Location: menu.php");
mysql_free_result ($result);
mysql_close($connection);
}
else
{
mysql_free_result ($result);
mysql_close($connection);
header("Location: index.php");
exit;
}
?>
That works. But If I remove the included config.php and just add the connection:
$database = "invoices";
$user = "root";
$pass = "";
$hostname = "localhost";
It doesn't login. I don't get it. the inc/config.php has some codes with the connection but why can't i just add the connection itself without using include?
I'm doing to assume that there's a dedicated page for login processing?
In which case you can just make a new config.php and connect to that db only on the login page?
A bit of your code or structure would help.
mysql_select_db() function sets the active MySQL database.
Syntax
bool mysql_select_db ( string database_name [, resource link_identifier])
mysql_select_db() attempts to select existing database on the server associated with the specified link identifier.
Returns TRUE on success, or FALSE on failure.
We can select database in mysql server by using mysql_select_db function. mysql_select_db() selects the current active database on the server that is associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to set a link as if mysql_connect() was called without arguments.
Made a function to connect to your database, also to close your connection.
function connect(user, pass, location)
function disconnect()
then you connect to your first db, do your operations. Close it and then open a new connection to the other db and do also your operations.
If you want to maintain 2 connections at the time, you could save your instances to variables
and do:
mysqli_select_db($instance1, 'SELECT ...');
mysqli_select_db($instance2, 'SELECT ...');
Also escape your variables in your query :)

Categories