php sqlsrv connection by multiple servers to one specific database - php

So I have 3 servers(192.168.0.21 , 192.168.0.22 and 192.168.0.23) and I would like them to connect to a database called Pensions they are all using sql server (UID and PWD)authentication. Is it possible to achieve this using php and sqlsrv_connect()? This the connect.php:
<?php
#first start session
session_start();
// session time out after no activity for 4 minutes
if ($_SESSION['TimeOut'] + (5 * 60) < time()) {
// session timed out
header("Location: ./sessdestroy.php");
exit;
} else {
// store new request time.
$_SESSION["TimeOut"] = time();
}
function getConnection(){
$db = 0;
if(!$_SESSION['Database']){
$db = 0;
}else{
$db = $_SESSION['Database'];
}
$databaseName = 'Pension';
if ($db == 0)
{ // Country A
$serverName ='192.168.0.21';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else if($db ==1)
{ // Country B
$serverName ='192.168.0.22';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
else
{ //Country C
$serverName ='192.168.0.23';
$UID ='sa';
$PWD ='pass!';
$databaseName = 'Pension';
}
//connection string
//echo "test here...";
//echo " S: ".$serverName." u: ".$UID." P: ".$PWD;
$serverName = "serverName";
$connectionInfo = array( "Database"=>"$databaseName", "UID"=>"$UID", "PWD"=>"$PWD");
$conn = sqlsrv_connect($serverName,$connectionInfo);
//exit();
//phpinfo();
if (!$conn)
{
exit("Connection Failed: " . $conn);
//try local server
if ($db == 1) {
$serverName ='192.168.0.20';
$UID ='fund_user';
$PWD ='fund_user';
$databaseName = 'Pension';
$conn = sqlsrv_connect($serverName,$connectionInfo);
if (!$conn) return 0;
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
return 0;
}
else
{
$stmt = sqlsrv_query($databaseName,$conn);
return $conn;
}
}
?>
Then this is the process.php (when a connection is established it leads the user to a homepage depending on the user role )
<?php
//give no error
ini_set("display warning",0);
#include connection
include('Connections/fundmaster.php');
if(!isset($_SESSION))
{
session_start();
}
//temp store for the database session before destory
$db = 0;
$db = $_SESSION["Database"];
if ($db==""){
$db = 0;
}
if (!isset($_SESSION["Database"]))
{
$_SESSION["Database"] = 0;
}
$_SESSION["Database"] = $db;
if($_POST['subLogin'])
{
$nationalID = $_POST['sname'];
$PWD = $_POST['Memberno'];
$conn = getConnection();
$sql = "select * from netlogin where NationalID = '";
$sql .= $nationalID ."' and vcPassword= '" .$PWD."'";
$sql = stripslashes($sql);
$stmt = sqlsrv_query($sql, $conn);
if($row = sqlsrv_fetch_array($stmt)){
$SchemeNo = $row[0];
$MemberNo = $row[1];
$userRole = $row[6];
session_start();
if (!isset($_SESSION["SchemeNo"]))
{
$_SESSION["SchemeNo"] = $SchemeNo;
}
if (!isset($_SESSION["MemberNo"]))
{
$_SESSION["MemberNo"] = $MemberNo;
}
if (!isset($_SESSION["userRole"]))
{
$_SESSION["userRole"] = $userRole;
}
$_SESSION["SchemeNo"] = $SchemeNo;
$_SESSION["MemberNo"] = $MemberNo;
$_SESSION["userRole"] = $userRole;
$_SESSION["Database"] = $db;
if($userRole == "1"){
header("Location:admin/adminarea.php");
}else{
header("Location:membersarea.php");
}
}else{
header("Location: login.php");
}
}else{
header("Location: login.php");
}
?>

Related

Why does my script not return a record from mySQL?

I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];

PHP query not working to check database for username

So I made a function that checks if the data that the user enters is already in my database of users. The function works in a testing environment (but runs on open of the page). For some reason it assigns the user input to the $username function regardless of the outcome of the query. I think I may have to AJAX it but I don't know how.
<?php
function checkIfEntered($data, $conn)
{
$query = "SELECT * FROM users
WHERE username= '" . $data . "'";
if ($result = mysqli_query($conn, $query)) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
}
if (($row_cnt) >= 1)
{
return TRUE;
}
if (($row_cnt) == 0)
{
return FALSE;
}
}
error_reporting(E_ALL);
ini_set('display_errors',1);
// define variables and set to empty values
$servername = "localhost"; $username = "root";
$password = "root";
$dbname = "MyDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = '';
$emailErr = '';
$usernameErr = '';
$UserPasswordErr = '';
$username = '';
$UserPassword = '';
$confirm = '';
$confirmErr = '';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{
$usernameErr = "username is required";
}
else
{
if (checkIfEntered($username, $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
}
You are not even calling the "checkIfEntered" function. Instead, you are calling "isEnteredUsername" function, which I don't see it here. So the code is always going in else and assigning the POST value to $username.
I am not sure why you think AJAXing it will solve the problem, but you can use AJAX call on document ready or some event like this $.ajax({ ... }) as explained here.
http://api.jquery.com/jquery.ajax/
you are forgot return num of record this function "checkIfEntered"
<?php
function checkIfEntered($data, $conn)
{
$query = "SELECT * FROM users
WHERE username= '" . $data . "'";
if ($result = mysqli_query($conn, $query)) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
return $row_cnt;
}
if (($row_cnt) >= 1)
{
return TRUE;
}
if (($row_cnt) == 0)
{
return FALSE;
}
}
error_reporting(E_ALL);
ini_set('display_errors',1);
// define variables and set to empty values
$servername = "localhost"; $username = "root";
$password = "root";
$dbname = "MyDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = '';
$emailErr = '';
$usernameErr = '';
$UserPasswordErr = '';
$username = '';
$UserPassword = '';
$confirm = '';
$confirmErr = '';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{
$usernameErr = "username is required";
}
else
{
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
}
?>
The Problem with this code is the function checkIfEntered() is coming up false because when you pass the $username parameter it has not been assigned. so it is coming up as false.
Code:
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
}
else
{
$username = test_input($_POST["username"]);
}
Correction
$username = test_input($_POST["username"]);
if (checkIfEntered(test_input($_POST["username"]), $conn))
{
$usernameErr = "There is already a user with the username: " . $username;
$username = '';
//set username back to nothing to avoid more errors.
}
else
{
$username = test_input($_POST["username"]);
}

How to check if value in database is same with string in PHP

I want to find out not how to check if exsists, but to check is it same. Here's my code:
$user = $_COOKIE["c_user"];
$ip = $_SERVER['REMOTE_ADDR'];
$salt = $_COOKIE["c_salt"];
$chk_salt = mysql_fetch_array(mysql_query("SELECT * FROM `table1` WHERE `Salt`='$salt'"));
if ($chk_salt == '0') {
die("Get out!");
}
else {
echo "Welcome ".ucwords($user);
}
$host = 'your_mysql_host';
$dbname = 'your_db_name';
$user = 'username';
$pass = 'password';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage().'<br>';
}
$user = $_COOKIE["c_user"];
$ip = $_SERVER['REMOTE_ADDR'];
$salt = $_COOKIE ['c_salt'];
$chckSalt = $conn->prepare("SELECT * FROM table1 WHERE Salt=:salt");
$chckSalt->bindValue(':salt', $salt, PDO::PARAM_STR);
$chckSalt->execute ();
if ($chkSalt->rowCount () == 0) {
die("Get out!");
}
else {
echo "Welcome ".ucwords($user);
}

MySQLI LOOP DATA

I want to get all the records from the while loop. I'm unable to get all the rows from the query. It shows only the first row.
Is there anything I was going wrong in my code.
function Connect($DB_HOST = 'localhost', $DB_USER = 'root', $DB_PASS = '', $DB_NAME = 'bodhilms')
{
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
return $mysqli;
}
function GetCoeficient($coeficient = false, $con)
{
if(!$con)
return 0;
$result = array();
$sql[] = "SELECT * FROM users ";
if($coeficient != false)
$sql[] = "WHERE username = '".$coeficient."' ORDER BY u.id";
//print_r($coeficient);
$query = $con->query(implode(" ",$sql));
//print_r($query);
while($row = $query->fetch_assoc())
{
$result[] = $row;
}
return (!empty($result))? $result : 0;
}
$con = Connect();
$result = GetCoeficient($coeficient,$con);
$username = $result[0]['username'];
$firstname = $result[0]['firstname'];
$lastname = $result[0]['lastname'];
$email = $result[0]['email'];
First of all,to make sure the infomation of mysql is right,like port.
and I wonder the code of you $result = Getcourse($coeficient,$con);, how the var coeficient come from.Then
You can try the code below:
$mysqli=new mysqli("localhost","root","root","123");
$query="select * from test";
$result=$mysqli->query($query);
if ($result) {
if($result->num_rows>0){
while($row =$result->fetch_array() ){
echo ($row[0])."<br>";
echo ($row[1])."<br>";
echo ($row[2])."<br>";
echo ($row[3])."<br>";
echo "<hr>";
}
}
}else {
echo 'failure';
}
$result->free();
$mysqli->close();

Undefined index: userID error

Upon Logging in, I have the userID stored in the SESSION. However when I call updateMarkerlocations.php it says userID is undefined. Not sure what I'm missing.
login.php
session_start();
if (!isset($_POST['submit'])){
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from userinfo WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
$row = $result->fetch_assoc();
setcookie("username", time() +60*60*24*30*365);
$_SESSION['userID'] = $row['userID'];
echo "<p>Logged in successfully!, Please close the window</p>";
}
}
?>
updateMarkerLocations.php
<?php
include 'db_const.php';
function insertMarkerLocations()
{
$markerCount = 0;
if (isset($_POST['markerCount']))
$markerCount = $_POST['markerCount'];
if(isset($_SESSION["userID"]))
{
$userID = $_SESSION["userID"];
}
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$userID = $_POST['userID'];
for($i=0 ; $i < $markerCount; $i++){
$index = $i;
++$index;
$curMarkerID = $_POST["markerID$index"];
$curLang = $_POST["lang$index"];
$curLat = $_POST["lat$index"];
// Now write the current marker details in to the db.
$query = "INSERT INTO userinfo (userID, markerID, lang, lat ) VALUES ('$userID', '$curMarkerID', '$curLang', '$curLat')";
mysql_query($query)
or die(mysql_error());
}
$msg = "SUCCESS";
return $msg;
}
$msg = insertMarkerLocations();
echo json_encode($msg);
?>
Add this at the top of each file:
if(!isset($_SESSION)) session_start();
Also, when you do:
$userID = $_POST['userID'];
you should ensure that $_POST['userID'] exists:
if(isset($_POST['userID'])) $userID = $_POST['userID'];

Categories