Objective: I am in the process of creating a php login script.
Problem: I can't seem to be able to make my includes recognize the $connection variable even though it should be clearly defined in connection.php. As a result the value of my variable is nothing / NULL.
What I tried: I started with mysql but quickly noticed that it was the wrong approach and converted my code to mysqli. I checked for typos in all the $connection variables I have. I made sure the paths are correct. As a last resort I did a Google search but didn't find an answer or any useful hint to my scenario.
Problem: What is the reason for my variable not being defined?
Error Messages:
All those messages are related to this single variable no being defined for some reason:
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 5
// INITIALIZER
<?php
session_start();
// error_reporting(NULL);
include 'Connection.php';
include 'Common.php';
include 'Functions/Members.php';
?>
**// ERROR MESSAGES **
<?php
$connection_error = 'Our website is experiencing technical issues, please come back later.';
$wrong_login = 'Password and name are wrong.';
$member_registered = 'Access has been denied. You do not seem to be a registered user.';
?>
**// CONNECTION **
<?php
include 'Errors.php';
$connection = mysqli_connect('localhost', 'root', '', 'project') or exit ($connection_error);
?>
**// COMMON **
<?php
error_reporting();
function sanitize($connection, $data) {
global $connection;
global $data;
return mysqli_real_escape_string($connection, $data);
}
?>
**// MEMBERS **
<?php
function member_registered($connection, $name) {
$name = sanitize($connection, $name);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
?>
**// LOGIN **
<?php
include 'Php/Core/Initializer.php';
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($connection, $name) == false) {
echo $member_registered;
}
}
?>
UPDATE:
Now what I get: existseee;
The conditional doesnt work now even though its all set up right. Username doesnt exist so it should'nt echo "exists:
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
In your case, the $connection variable inside your sanitize function isn't reachable.
Try to pass the $connection variable into your function, like this:
function sanitize($data, $connection) {
return mysqli_real_escape_string($connection, $data);
}
Read more about it here: http://php.net/manual/en/language.variables.scope.php
UPDATE
In **// MEMBERS ** you need to include the new parameter as well:
function member_registered($name, $connection) {
$name = sanitize($name, $connection);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
and because of that your **// LOGIN ** should be updated as well:
include 'Php/Core/Initializer.php';
if (member_registered('ee', $connection)) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($name, $connection) == false) {
echo $member_registered;
}
}
And make sure that the $connection variable is reachable everywhere where you need it.
UPDATE #2
Answer to your update:
it should be like this:
if (member_registered('ee', $connection)) {
echo "exists";
}
and not like this:
if (member_registered($connection, 'ee')) {
echo "exists";
}
the $connection is the second parameter.
Related
i have this code
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dabname = "tutorial";
$login = mysqli_connect($host, $user, $pass, $dabname) or die('Could not connect to mysql server.');
mysqli_select_db($login, $dabname) or die('Could not select database.');
$nama_karyawan = $_POST['nama_karyawan'];
$umur_karyawan = $_POST['umur_karyawan'];
function proses_hoby($id_karyawan) {
if (isset($_POST["rincian_hoby"])) {
$hoby = $_POST["rincian_hoby"];
reset($hoby);
while (list($key, $value) = each($hoby)) {
$rincian_hoby = $_POST["rincian_hoby"][$key];
$jenis_hoby = $_POST["jenis_hoby"][$key];
$sql_hoby = "INSERT INTO tbl_hoby(rincian_hoby,jenis_hoby,id_karyawan)
VALUES('$rincian_hoby','$jenis_hoby','$id_karyawan')";
$hasil_hoby = mysqli_query($login, $sql_hoby);
}
}
}
$sql = "INSERT INTO tbl_karyawan(nama_karyawan,umur_karyawan)
VALUES('$nama_karyawan','$umur_karyawan')";
$hasil = mysqli_query($login, $sql);
$id_karyawan = mysqli_insert_id($login);
if ($hasil) {
proses_hoby($id_karyawan);
echo "Data berhasil diinput";
} else {
echo "Data Gagal diinput";
}
?>
But i do get this error
Notice: Undefined variable: login in C:\xampp\htdocs\2\proses.php on
line 23
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\2\proses.php on line 23
Notice: Undefined variable: login in C:\xampp\htdocs\2\proses.php on
line 23
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\2\proses.php on line 23
Data berhasil diinput
I know there are lot of similiar Thread name but i dont found that match my problem
Here is the source code https://drive.google.com/file/d/16FNr5SJeO_53_-XUJo7RIV1rLqgZwagV/view?usp=sharing
please help
any help would be very appreciated
thank you
You should learn about variable scopes inside php. $login is declared outside the function proses_hoby so proses_hoby can't access this var. To access $login inside the function, you need to make it global (the unclean way..) or pass $login as an function parameter.
Modern approaches would be to move the whole thing inside a class and make $login a class var. So every member of the class could access the var.
Btw. your code is prone to sql injections. You should use prepared statements.
I´m trying to create a simple login script for my Website (with PHP & Mysql). Created the original script with plain php & mysql commands and everything worked just fine. Now i wanted to exchange the old mysql commands with mysqli commands. Somehow i´m now getting the error "Trying to get property of non-object *** on line 11" when I test my script. Could somebody explain exactly to me what causes that problemn and how to solve it (because I dont really understand the error here)?
Login Script:
<?php
session_start();
?>
<?php
include_once "db_connect.php";
$username = $_POST["username"];
$password = md5($_POST["password"]);
$abfrage = "SELECT username, password FROM login WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysqli_query($verbindung,$abfrage);
$row = mysqli_fetch_assoc($ergebnis);
if ($row->password === $password) { <--- Line 11
$_SESSION["username"] = $username;
if ($username != "admin") {
echo "Login erfolgreich. <br> Geschützter Bereich";
}
else {
echo "Login erfolgreich. <br> Geschützter Bereich";
}
}
else {
echo "Benutzername und/oder Passwort sind falsch.";
}
?>
$row is an associative array, because you have used $row = mysqli_fetch_assoc($ergebnis); but you are treating $row as an object i.e.
$row->password
So try:
if ($row['password'] === $password)
<?php
session_start();
include_once "db_connect.php";
// either use require_once + bail-out code in db_connect.php
// or check the connection resource/object here.
if ( !$verbindung || $verbindung->connect_errno ) {
die('sorry, db error. try again later');
}
$password = md5($_POST["password"]); // md5, unsalted ...not secure anymore. see http://docs.php.net/password_hash
// see http://php.net/security.database.sql-injection
$abfrage = sprintf( // password is a reserved word in mysql -> backticks around the field id
"SELECT `username`, `password` FROM login WHERE username LIKE '%s' LIMIT 1",
mysqli_real_escape_string($verbindung, $_POST["username"])
);
$ergebnis = mysqli_query($verbindung,$abfrage);
// mysqli_query may fail at any time -> error handling required
if ( !$ergebnis ) {
echo 'db query failed'; // $verbindung->error should contain more information
}
else if ( !($row = mysqli_fetch_assoc($ergebnis)) ) {
echo 'no result'; // you probably shouldn't make a distinction between "no such record" and "wrong password" - just for illustration
}
else if ($row['password'] === $password) { // fetch_assoc returns an array, not an object
$_SESSION["username"] = $username;
}
use that like this
$row = mysqli_fetch_assoc($ergebnis);
if ($row['password'] === $password) {
Try with $row["password"]==$password
If it still shows the same thing, then var_dump $row and see if it returns a result.
I have an ajax posting of a form so that I can return values from PHP exactly as it shows here: https://jonsuh.com/blog/jquery-ajax-call-to-php-script-with-json-return/ .
There's a slight difference though, my response.php script is like this:
<?php
session_start();
$email = $_SESSION['email'];
?>
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) {
$action = $_POST["action"];
switch($action) {
case "test": test_function(); break;
}
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
$x = $return["Profile"];
define('DB_NAME', 'STUDENTS');
define('DB_USER', 'STUDENTS');
define('DB_PASSWORD', 'PASSWORD');
define('DB_HOST','HOST');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = "UPDATE `STUDENTS`.`Students` SET `Fbprofile` = '$x' WHERE `Students`.`StudEmail` = '$email' ";
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
As you can see, the only difference is that I'm updating an SQL database. The problem is that I want to update the Fbprofile column where StudEmail equals the email session variable. This session variable works perfectly in all other pages, but I can't seem to retrieve it in my response.php. What actually happens is that the SQL update works but only updates all rows that have no email value in them, so I'm guessing it's not reading the $email variable.
Thank you very much for your help.
It's a variable scope problem. You set $email outside of test_function, so it's not visible inside the function. If you had error reporting enabled, you would have seen a notice about the undefined variable.
You should pass it as an argument to the function:
case "test": test_function($email); break;
...
function test_function($email) {
...
}
So I'm trying to check if a user already liked a post.
Code:
function previously_liked($id) {
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$user = "";
}
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `likes` WHERE `id` = '$id' AND `user_id` = '".$connection->escape_string($user)."'");
while ( $row = $query->fetch_object()->count ) {
if ( $row->count == 0 ) return false;
else return true;
}
}
The thing is, it's not returning false or true. On my other PHP page I'm trying to run this function like this:
if (previously_liked(70) === true) {
$aliked = "You've already liked this!";
}
echo $aliked;
The only error I'm seeing is Notice: Undefined variable: aliked in profile.php on line 391
Any help is welcome! Thanks!
You can do this things to finds error in your code:
echo $user; //before MySQL query
Query your MySQL statement in MySQL console or app like PHPmyAdmin after replacing ".$connection->escape_string($user)." to your user_id. If it fetch row than your MySQL statement is correct and there is something wrong with $_SESSION["user_login"] value.
Optionally, you can also echo the returning rows to check the output data.
Otherwise check your query statement as column names, table name, database etc.
Hope, it helps you...
Your query is fine, your problem is something else: You're defining $aliked inside the scope of the if-statement, so you can't use it outside. You need to change your code, one possibility is this:
if (previously_liked(70) === true) {
echo "You've already liked this!";
}
or this:
$aliked = "";
if (previously_liked(70) === true) {
$aliked = "You've already liked this!";
}
echo $aliked;
This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 1 year ago.
I'm tryin to build some functions for a website of mine and some of them consist in
fetching data from the mysql database. When I test the code outside of the function
it seems to work properly. So here it is, The first page:
require('db.php');
require('functions.php');
$email = 'sample#gmail.com';
if (user_exists($email) == true){
echo "Good news, this exists";
}
Now db.php :
$db = new MySQLi("localhost","test","test","test");
if ($db->connect_errno){
echo "$db->connect_errno";
}
And the functions.php file:
function sanitize ($data){
$db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}
And the error I'm getting when accessing the first file is:
Notice: Undefined variable: db in C:\xampp\htdocs\auctior\inc\functions.php on line 6
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\auctior\inc\functions.php on line 6
SO I've required/included the db.php where $db is the mysqli connect. And within the same file(first file) I call the functions located at functions.php
Thank you in advance,
I'd appreciate your help as this is pissing me off......
You probably need to use the global keyword, otherwise $db is considered a var in local scope.
function sanitize ($data){
global $db;
$db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
global $db;
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}
Try to connect inside the function, and connection needs to be included before you include functions.
Something like this:
function user_exists($usermail){
$db = new MySQLi("localhost","test","test","test");
$usermail = sanitize($usermail);
$query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
$check = $query->num_rows;
return ($check == 1) ? true : false;
}