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 :)
Related
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
I am working on a small social web application as a final project for my iOS class. I have a profile view controller where all the info about the user from the database is supposed to be displayed on the labels. The problem is that I don't really know the best way to do this. Here is my php script:
<?
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
//return the json result.
echo '{"users":'.json_encode($arr).'}';
?>
So here I get the info about all the users in the database. I am sure this is not the right way to go, so I guess I need to change the SQL query to retrieve the data for the current user only. But how can I do this? Should I put the username which I enter on the login page into an extra variable and then pass it with JSON to this php script and add the 'WHERE username = 'blabla' statement to the SQL query then? If so, how can I pass the variable to this script with JSON?
Can you please give me some sample code? Or is there a different way to do this?
Thank you so much!
<?php
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
$data = mysql_fetch_array($rs);
foreach($data as $rec){
echo "user: $rec<br>";
}
?>
Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost
i have a button i am trying to get where if i click it it updates the column 'gorg' in the table users to giver according to the current user (session) logged in. Everytime i click the button i get
Access denied for user 'root'#'localhost' (using password: NO)
Here is the top of the php page (BTW i am 100% positive my DB Connection info is correct)
<?php
session_start();
include('src/sql_handler.php'); //this is where my DB Connection info is located
include('src/facebook_handler_core.php');
if(isset($_POST['submitgiver'])) {
$query = "UPDATE users SET gorg='giver' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'";
$result = mysql_query($query) or die(mysql_error());
}
{
if(isset($_SESSION['gorg'])=="Giver")
{
header('Location: picktreetype.php');
}
else if(isset($_SESSION['gorg'])=="Gatherer")
{
header('Location: gatherermap.php');
}
}
?>
and now for the html
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="submitgiver" value="Giver">
</form>
UPDATE:
heres the SQL_HANDLER
<?php
class MySQL_Con {
private $host = 'localhost',
$user = 'fruitfo1_admin',
$pass = 'password',
$db = 'fruitfo1_fruitforest',
$_CON;
function MySQL_Con() {
$this->_CON = mysql_connect($this->host, $this->user, $this->pass);
if(!$this->_CON)
die(mysql_error());
else {
$select_db = mysql_select_db($this->db);
if(!$select_db)
die('Error Connecting To Database'.mysql_error());
}
}
function End_Con() {
mysql_close($this->_CON);
}
}
?>
Apparently your connection setup doesn't include a password. Please post the sql_handler (WITH OBFUSCATED password) to be able to debug further.
If you're 100% positive it's correct, as you're saying, you can try explicitly passing sql handle to mysql_query.
Another note, mysql_* are deprecated, you really should consider switching to either mysqli or PDO.
Also, using root user for ANY kinds of web-applications is a no-no.
Your DB doesn't have a password. Try this
private $host = 'localhost',
$user = 'fruitfo1_admin',
$pass = '',
$db = 'fruitfo1_fruitforest',
$_CON;
i found my issue, it did have to do with exactly what i thought it was. heres my updated code
if(isset($_POST['submitgiver'])) {
$mysql_hostname = "localhost";
$mysql_user = "fruitfo1_admin";
$mysql_password = "password";
$mysql_database = "fruitfo1_fruitforest";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
$query = "UPDATE users SET gorg='giver' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'";
$result = mysql_query($query) or die(mysql_error());
}
basically that IF statement that was attempting to POST wasnt linking back to my handler, so i placed the SAME db connection from the handler and carried it over inside the if isset statement and it worked!
Hey, I already have a view counter coded, but i need help preventing people from just refreshing and refreshing to add more views. Normally, i Would mark this storing the ip, page name and date viewed in a SQL table where in php, i would run a search to see if someone with that ip has viewed the page within 24 hours, but I run a website that is mostly operated in schools and i want each computer in a computer lab to count as a view when they see the page. Again, i could use cookies but my server isn't sending out cookies right. It works fine on my testserver but not on the dedicated web hosting server. Is there any other way to prevent spam?
Heres my code
function connect() {
$domain = $_SERVER['HTTP_HOST'];
$dbhost = 'censored';
$dbname = 'censored';
$dbuser = 'censored';
$dbpass ='censored';
if ($domain == 'localhost'){
$dbhost = 'localhost';
$dbname = 'db1';
$dbuser = 'root';
$dbpass ='';
}
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$con){
trigger_error("Problem Connecting to the MySQL Server.");
}
$db = mysql_select_db($dbname, $con);
if(!$db){
trigger_error("Problem finding the Database!");
}
return $con;
}
function fetchdata($qry){
connect();
$result = mysql_query($qry);
return $fetch = mysql_fetch_assoc($result);
}
function addcounter($id) {
connect();
$counter = fetchdata("SELECT * FROM counter WHERE `path` = '$id';");
$counter = $counter['counter'];
if(isset($_COOKIE["counter_".$id.""])){
}else{
if ($counter === NULL) {
mysql_query("INSERT INTO counter VALUES (0, '" .$id. "');");
}
echo "<!-- submitting query -->";
mysql_query("UPDATE counter SET counter = `counter`+ 1 WHERE path = ".$id."") or die ('failupdate');
setcookie("counter_$id", "Playcookie_".$id."");
}
}
If you cannot use the user's IP address (presumably because they are behind NAT?) and you cannot use cookies, there's really not much you can do.
You could try to use the IP together with the user agent string (which might be different among different computers in the lab), but this would be both slower and of course far from guaranteed to work.
Other than that I think you 're out of options.