Database connect undefined - php

I'm getting an error saying Undefined variable: con,
the connection of the database is on the other php file, (include() is already on top of the code). I just don't know how to call the $con
if (isset($_POST['update_profile']))
{
if (isset($_POST['first_name']))
{
$first_name = mysqli_real_escape_string($con, $_POST['first_name']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET fname = '$first_name' WHERE email = '$email_to_connect'");
}
if (isset($_POST['last_name']))
{
$last_name = mysqli_real_escape_string($con, $_POST['last_name']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET lname = '$last_name' WHERE email = '$email_to_connect'");
}
if (isset($_POST['contact']))
{
$contact = mysqli_real_escape_string($con, $_POST['contact']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET contact = '$contact' WHERE email = '$email_to_connect'");
}
}
here is the other php file
class Users {
public $table_name = 'tbl_fbusers';
function __construct(){
//database configuration
$dbServer = 'localhost'; //Define database server host
$dbUsername = 'root'; //Define database username
$dbPassword = ''; //Define database password
$dbName = 'db_zalian'; //Define database name
//connect databse
$con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
if(mysqli_connect_errno()){
die("Failed to connect with MySQL: ".mysqli_connect_error());
}else{
$this->connect = $con;
}
}
Thanks!

Defining $con as a GLOBAL variable is a terrible idea...
I suggest to make a file (eg. connection.php) that will contain the $con variable that is not in a function, and then include the connection.php to your other php files. It's more secure and easier, and you won't get to any troubles.

Since you have a class you need to initialize user class.
$user = new Users();
and then
$con = $user->connect;
Here you can run your sql like:
$contact = mysqli_real_escape_string($con, $_POST['contact']);
$sql = mysqli_query($con, "UPDATE tbl_fbusers SET contact =......... etc.

you need to define $con as global:
global $con
$con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);

Related

Sql Statement from PHP isnt inserting into Database but doesnt give an error

Thanks to this site i could manage to solve my problems, but my statement isnt going through on my database, but when i copy it and paste it directly to my database, it inserts without any problem. Here my code:
<?php
$ip = "***"; //MySQL Server IP
$user = "***"; //MySQL user
$pw = "***"; //MySQL password
$db = "***"; //Database
$sql_filter = "";
$con = mysqli_connect($ip, $user, $pw, $db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function register()
{
$username = $_POST[username];
$vorname = $_POST[vorname];
$nachname = $_POST[nachname];
$geschlecht = $_POST[geschlecht];
$geburtsdate = $_POST[geburtsdatum];
$password = $_POST[password];
$email = $_POST[email];
if($email!="" and $password!="" and $username!="" and $password==$_POST["password_confirm"])
{
$sql_filter = "INSERT INTO `tblUser`(`UserID`, `UserName`, `Vorname`, `Nachname`, `EMail`, `Geschlecht`,`Password`) VALUES ('','$username','$vorname','$nachname','$email','$geschlecht','$password')";
$_SESSION['filter'] = $sql_filter;
$page_query = mysqli_query($con, $_SESSION['filter']);
$page_nums = mysqli_num_rows($page_query);
//header('Location: index.php');
echo $sql_filter;
echo $_SESSION['filter'];
}
else
{
header('Location: 404.html');
}
}
if(isset($_POST['submit']))
{
register();
}
mysqli_close($con);
?>
I think the problem is your $con is undefined in the function register(). So add this in the beginning of your function :
function register()
{
global $con;
... // the rest of your function
}

Rehashing a password being changed PHP

I am currently having problems with hashing. Heres a bit of background;
The user creates an account, and their password is hashed using password_hash($password, PASSWORD_BCRYPT). Then, when they login, the password is checked via password_verify and if it is correct, they will be logged in.
However, when the user goes to their profile and edit's their details, changing their password, they can never login again. As well as this, if an employee changes the users password, they still cannot login.
I've been trying to look around and solve this but can't find anything, and what is the most wierd thing is that when an employee (lets say the admin account) changes another employees password, they can login fine with their new password? I've done pretty much the same code as the working changing password and rehashing code, but it still does not work.
Sign Up:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
$clienttitle = $_POST["clienttitle"]; /*Retrieves the ClientTitle input from the user.*/
$clientforename = $_POST["clientforename"]; /*Retrieves the ClientForename input from the user.*/
$clientsurname = $_POST["clientsurname"]; /*Retrieves the ClientSurname input from the user.*/
$phonenumber = $_POST["phonenumber"]; /*Retrieves the PhoneNumber input from the user.*/
$clientusername = $_POST["clientusername"]; /*Retrieves the Username input from the user.*/
$clientpassword = $_POST["clientpassword"]; /*Retrieves the ClientPassword input from the user.*/
$emailaddress = $_POST["emailaddress"]; /*Retrieves the EmailAddress input from the user.*/
$billingaddress = $_POST["billingaddress"]; /*Retrieves the BillingAddress input from the user.*/
/*Here, each of the inputs are put through the 'stripslashes' function, which stops a MySQL injection attack.*/
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$clientpassword = stripslashes($clientpassword);
$emailaddress = stripslashes($emailaddress);
$billingaddress = stripslashes($billingaddress);
/*The use of mysql_real_escape_string also stops a MySQL injection attack.*/
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$clientpassword = mysql_real_escape_string($clientpassword);
$emailaddress = mysql_real_escape_string($emailaddress);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "INSERT INTO $tablename (ClientID, ClientTitle, ClientForename, ClientSurname, PhoneNumber, Username, EmailAddress, ClientPassword, BillingAddress, SignUpDate)VALUES(NULL, '$clienttitle', '$clientforename', '$clientsurname', '$phonenumber', '$clientusername', '$emailaddress', '$hashedclientpassword', '$billingaddress', CURRENT_TIMESTAMP)";
$result = mysql_query($query);
if($result){
echo "Successful";
header("location:Index.php");
} else {
echo ("Unsuccessful : " . mysql_error());
}
mysql_close();
?>
Check Login:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the user entered.*/
$userusername = $_POST["Username"];
$userpassword = $_POST["ClientPassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$userusername = stripslashes($userusername);
$userpassword = stripslashes($userpassword);
$userusername = mysql_real_escape_string($userusername);
$userpassword = mysql_real_escape_string($userpassword);
$sql = "SELECT ClientPassword FROM $tablename WHERE Username = '$userusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hasheduserpassword = $datarow['0'];
if (password_verify($userpassword, $hasheduserpassword)) {
session_start();
$_SESSION['Username'] = $userusername;
$_SESSION['ClientPassword'] = $hasheduserpassword;
header("Location:IndexUserLogin.php");
} else {
header("location:WrongPU.php");
}
?>
user editing their details:
<?php
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "clientinformation";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$clientid = $_POST["clientid"];
$clienttitle = $_POST["clienttitle"];
$clientforename = $_POST["clientforename"];
$clientsurname = $_POST["clientsurname"];
$phonenumber = $_POST["phonenumber"];
$clientusername = $_POST["clientusername"];
$emailaddress = $_POST["emailaddress"];
$clientpassword = $_POST["clientpassword"];
$billingaddress = $_POST["billingaddress"];
$clientid = stripslashes($clientid);
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$emailaddress = stripslashes($emailaddress);
$clientpassword = stripslashes($clientpassword);
$billingaddress = stripslashes($billingaddress);
$clientid = mysql_real_escape_string($clientid);
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$emailaddress = mysql_real_escape_string($emailaddress);
$clientpassword = mysql_real_escape_string($clientpassword);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET ClientTitle = '$clienttitle', ClientForename = '$clientforename', ClientSurname = '$clientsurname', PhoneNumber = '$phonenumber', Username = '$clientusername', EmailAddress = '$emailaddress', ClientPassword = '$hashedclientpassword', BillingAddress = '$billingaddress' WHERE ClientID = '$clientid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:UserCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Edit employees details (works)
<?php
session_start();
if($_SESSION['EmployeeUsername'] !== "Admin") {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "employeelogin";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$employeeid = $_POST['employeeid'];
$employeeusername = $_POST['employeeusername'];
$employeepassword = $_POST['employeepassword'];
$employeename = $_POST['employeename'];
$employeesurname = $_POST['employeesurname'];
$employeeid = stripslashes($employeeid);
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeename = stripslashes($employeename);
$employeesurname = stripslashes($employeesurname);
$employeeid = mysql_real_escape_string($employeeid);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$employeename = mysql_real_escape_string($employeename);
$employeesurname = mysql_real_escape_string($employeesurname);
$hashedemployeepassword = password_hash($employeepassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET EmployeeID = '$employeeid', EmployeeUsername = '$employeeusername', EmployeePassword = '$hashedemployeepassword', EmployeeName = '$employeename', EmployeeSurname = '$employeesurname' WHERE EmployeeID = '$employeeid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:EmployeeCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Check employees login (work)
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "employeelogin"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the employee entered.*/
$employeeusername = $_POST["EmployeeUsername"];
$employeepassword = $_POST["EmployeePassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$sql = "SELECT EmployeePassword FROM $tablename WHERE EmployeeUsername = '$employeeusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hashedemployeepassword = $datarow['0'];
if (password_verify($employeepassword, $hashedemployeepassword)) {
session_start();
$_SESSION['EmployeeUsername'] = $employeeusername;
$_SESSION['EmployeePassword'] = $hashedemployeepassword;
header("Location:IndexEmployeeLogin.php");
} else {
header("location:WrongPU.php");
}
?>
Cheers for all and any responses
Remove all calls to stripslashes() and mysql_real_escape_string() for password input, the functions password_hash() and password_verify() accept even binary input and are not prone to SQL-injection. I assume this already solves your problem.
Escaping should be done as late as possible and only for the given target system, so the function mysqli_real_escape_string() should only be called to build an SQL query.
Check wheter in both tables (clientinformation and employeelogin), the password-hash field is declared with 60 characters or more.
If this doesn't solve your problem, i would use UTF-8 for all your pages. You can check your pages with this W3C checker, every page should be stored in the UTF-8 file format and define the UTF-8 header.
Test with isset whether a variable exists: if(!isset($_SESSION['Username']))
The password hash should not be stored in the session, but maybe this is only for testing purposes.
Setting the userid is not necessary: "UPDATE $tablename SET EmployeeID = '$employeeid', ... WHERE EmployeeID = '$employeeid'";
And it is a good habit to always call exit after a redirect:
header('Location: Index.php', true, 303);
exit;

I can not update database using php

For some reason I am can not update my database. Can anyone spot what I am doing wrong ?
Here is the code.
.......
session_start();
$user = mysql_real_escape_string($_POST['user']);
$email = mysql_real_escape_string($_POST['email']);
.......
if ($errorMessage == "") {
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ----- CHECKING SERVER
include('connect.php');
if (isset($user)) {
$sql = "UPDATE hookers ".
"SET user= ´$user´".
"WHERE email= ´$email´" ;
mysqli_query($con, $sql) or die("Can´t find user". mysql_error());
print "user updated";
mysqli_close($con);
}
}
connect.php file
$host = 'localhost';
$username = 'root';
$password = '';
$db = 'putas';
$con = mysqli_connect($host, $username, $password) or die("Can´t connect to server");
mysqli_select_db($con, $db) or die("Can´t connect to database");
Whenever I run the script it prints "Can´t find user". The variables $user & $email have the right data as I have checked it.
I would appreciate any help you guys can provide me.
Thanks in advance.
Oliver Tangari
You need to change all instances of ´ to '.
Your Sql Query Will Be like this:--
$sql = "UPDATE hookers ".
"SET `user`= '$user'".
"WHERE `email`= '$email'" ;
Hope it helps you...
Use ' single quote not `
$sql = "UPDATE hookers ".
"SET user= '$user'".
"WHERE email= '$email'" ;
As already mentioned the problem is ´
Why don't you use PDO and parameter binding instead? This won't give you this type of errors in the future.
<?php
// configuration
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$user = 'Belén Esteban';
$email = 'belenesteban#telecinco.es';
// query
$sql = "UPDATE hookers
SET user=?
WHERE email=?";
$q = $conn->prepare($sql);
$q->execute(array($user,$email));
?>

New $_SESSION variable not created after query?

I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";
I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>

Fatal error: Call to a member function prepare() on a non-object in pdo

Im getting " Fatal error: Call to a member function prepare() on a non-object " Error the script worked fine on my other hosts but now ive moved hosts its showing this error and donno why because the coding is fine.
include 'functions/functions.php';
global $db;
$db = mysqlconnect();
$password = md5($_POST['mypassword']);
$mod = '1' ;
$statement = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ? And mod = ?");
$statement->execute(array($_POST['myusername'],$password, $mod));
$count = $statement->rowCount();
if($count == 1){
$db = mysqlconnect();
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['user'] = $_POST['myusername'] ;
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$sqll = "UPDATE users SET lastip=? WHERE username=?";
$q = $db->prepare($sqll);
$q->execute(array($ip,$_SESSION['username']));
$_SESSION['user'] = $_POST['myusername'] ;
$sqlll = "INSERT INTO user_log (username,ip) VALUES (?, ?)";
$qq = $db->prepare($sqlll);
$qq->execute(array($_SESSION['username'],$ip));
header("Location: home.php");
} else {
echo "Wrong Username or Password";
}
Has you can see its saying the prepare is wrong on this line
$statement = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ? And mod = ?");
when there is nothing wrong with the code which i can see....
Here is my function file which inculdes the mysqlconnect
function mysqlconnect(){
global $db;
$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = '';
$username = '';
$password = '';
// Construct the DSN, or "Data Source Name". Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it. As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";
// Connect!
$db = new PDO($dsn, $username, $password);
}
I have toke my connect info out just so everyone knows...
When stating $db = mysqlconnect();, you expect mysqlconnect() to return a PDO object. Change the function to this to make it working:
function mysqlconnect(){
$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = '';
$username = '';
$password = '';
// Construct the DSN, or "Data Source Name". Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it. As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";
// Connect!
$db = new PDO($dsn, $username, $password);
// Return PDO object
return $db;
}

Categories