Checking if email address exists in SQL database with php - php

I am doing a school assignment which has to contain a page for users to register. I am getting an error with checking if their email address is already in the database, but I can't figure out why. The error is:
Notice: Undefined variable: kapcsolat in /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php on line 39
Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/hallgatok/jyhv6c/www/wf2/php_bead/database.php:9 Stack trace: #0 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(9): lekerdezes(NULL, 'SELECT * FROM `...', Array) #1 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(39): letezik(NULL, 'koostamas199753...') #2 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(53): validate(Array, Array, Array) #3 {main} thrown in /home/hallgatok/jyhv6c/www/wf2/php_bead/database.php on line 9
My database.php, where I connect:
database.php
<?php
function kapcsolodas($kapcsolati_szoveg, $felhasznalonev = '', $jelszo = '') {
$pdo = new PDO($kapcsolati_szoveg, $felhasznalonev, $jelszo);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function lekerdezes($kapcsolat, $sql, $parameterek = []) {
$stmt = $kapcsolat->prepare($sql);
$stmt->execute($parameterek);
return $stmt->fetchAll();
}
function vegrehajtas($kapcsolat, $sql, $parameterek = []) {
return $kapcsolat
->prepare($sql)
->execute($parameterek);
}
$kapcsolat = kapcsolodas(
'mysql:host=localhost;dbname=****;charset=utf8',
'****', '****');
?>
And the page which does the work:
register.php
<?php
include('database.php');
///////////////////////////////////
function letezik($kapcsolat, $felhasznalonev) {
$felhasznalok = lekerdezes($kapcsolat,
"SELECT * FROM `felhasznalok` WHERE `felhasznalonev` = :felhasznalonev",
[ ":felhasznalonev" => $felhasznalonev ]
);
return count($felhasznalok) === 1;
}
function regisztral($kapcsolat, $teljes_nev, $felhasznalonev, $jelszo) {
$db = vegrehajtas($kapcsolat,
"INSERT INTO `felhasznalok` (`teljes_nev`, `felhasznalonev`, `jelszo`)
values (:teljes_nev, :felhasznalonev, :jelszo)",
[
":teljes_nev" => $teljes_nev,
":felhasznalonev" => $felhasznalonev,
":jelszo" => password_hash($jelszo, PASSWORD_DEFAULT),
]
);
return $db === 1;
}
function validate($post, &$data, &$hibak) {
if (trim($post['nev']) === '') {
$hibak[] = 'Teljes név kötelező!';
}
else {
$data['nev'] = $post['nev'];
}
if (trim($post['email']) === '') {
$hibak[] = 'E-mail cím kötelező!';
} else if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
$hibak[] = "Hibás e-mail cím!";
} else if (letezik($kapcsolat, $post['email'])) { <========This is line 39, but $kapcsolat was defined in database.php
$hibak[] = "Ehhez az e-mail címhez már tartozik felhasználói fiók!";
}
else {
$data['email'] = $post['email'];
}
$data['jelszo'] = $post['jelszo'];
return count($hibak) === 0;
}
$hibak = [];
if ($_POST) {
if (validate($_POST, $data, $hibak)) {
regisztral($kapcsolat, $data['nev'], $data['email'], $data['jelszo']);
header("Location: index.php");
exit();
}
}
?>
The error only occurs when that part of the if statement runs. I just can't figure out what the problem is.What am I doing wrong?

As I said in a comment, your variable $kapcsolat is defined in your file database.php, but is used in the function validate.
When you create a function, all variables used in it are supposed to be local variables.
I suggest to take this variable as parameter instead of using the global variable, it's more flexible. But if you really want to use this variable, you have to declare $kapcsolat as global.
In register.php you should use:
<?php
function validate($post, &$data, &$hibak) {
global $kapcsolat; //IMPORTANT IS HERE
//...Some code
}
See the global keyword

Related

Fatal error: Uncaught TypeError: getUserDataForUsername(): Argument #1 ($username) must be of type string, null given

I`m trying to build a login form with E-Mail and Minecraftname. I want to check if
there`s an E-Mail
there`s an Minecrafname
the Minecraftname is in our database
If all 3 are the case the next step would take part. (send E-Mail etc.)
function getUserDataForUsername(string $username): array
{
$sql = "SELECT unique_id FROM kype.cloud_players WHERE username=:username";
$statement = getDB()->prepare($sql);
if (false === $statement) {
return [];
}
$statement->execute([
':username' => $username
]);
if (0 === $statement->rowCount()) {
return [];
}
$row = $statement->fetch();
return $row;
}
if (strpos($route, '/login') !== false) {
$isPost = strtoupper($_SERVER['REQUEST_METHOD']) === 'POST';
$username = "";
$mcname = "";
$errors = [];
$hasErrors = false;
if ($isPost) {
$username = filter_input(INPUT_POST, 'username');
$mcname = filter_input(INPUT_POST, 'password');
if (false === (bool) $username) {
$errors[] = "E-Mail is empty";
}
if (false === (bool) $mcname) {
$errors[] = "Minecraftname is empty";
}
$userData = getUserDataForUsername($username);
if ((bool) $username && 0 === count($userData)) {
$errors[] = "test";
}
if (
(bool) $mcname &&
isset($userData['mcname']) &&
false === password_verify($mcname,
$userData['mcname'])
) {
$errors[] = "This player hasn`t been on the server yet";
}
if (0 === count($errors)) {
$_SESSION['userID'] = (int) $userData['id'];
}
}
$hasErrors = count($errors) > 0;
require __DIR__ . '/templates/login.php';
exit();
}
I expected one of my error messages but it gave me following error:
Fatal error: Uncaught TypeError: getUserDataForUsername(): Argument #1 ($username) must be of type string, null given, called in C:\xampp\htdocs\kypemc\shop\routes.php on line 65 and defined in C:\xampp\htdocs\kypemc\shop\functions\user.php:16 Stack trace: #0 C:\xampp\htdocs\kypemc\shop\routes.php(65): getUserDataForUsername(NULL) #1 C:\xampp\htdocs\kypemc\shop\includes.php(6): require_once('C:\\xampp\\htdocs...') #2 C:\xampp\htdocs\kypemc\shop\index.php(7): require('C:\\xampp\\htdocs...') #3 {main} thrown in C:\xampp\htdocs\kypemc\shop\functions\user.php on line 16

Delete row of MySQL database with $_GET parameter

So I have a table named recept_felhasznalok_pending with four columns one of which is email. I want to be able to delete a row from the table using a link I can send anyone. I have the following PHP code in deny.php:
<?php
include('database.php');
///////////////////////////////////
function azonositott_e() {
return ($_SESSION["email"] === "This is the email address of the person I want to be able to use the link.");
}
session_start();
if (!azonositott_e()) {
header("Location: login.php");
exit();
}
function db($kapcsolat, $email) {
$torol = vegrehajtas($kapcsolat,
"DELETE FROM `recept_felhasznalok_pending` WHERE `email` = :email",
[ ":email" => $email ]
);
}
if ($_GET['email']) {
db($kapcsolat, $_GET['email']);
header("Location: index.php");
exit();
}
?>
The database.php file has the connection and execute parts of the code:
<?php
function kapcsolodas($kapcsolati_szoveg, $felhasznalonev = '', $jelszo = '') {
$pdo = new PDO($kapcsolati_szoveg, $felhasznalonev, $jelszo);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function lekerdezes($kapcsolat, $sql, $parameterek = []) {
$stmt = $kapcsolat->prepare($sql);
$stmt->execute($parameterek);
return $stmt->fetchAll();
}
function vegrehajtas($kapcsolat, $sql, $parameterek = []) {
return $kapcsolat
->prepare($sql)
->execute($parameterek);
}
$kapcsolat = kapcsolodas(
'mysql:host=*********;dbname=************;charset=utf8',
'********', '***********');
?>
When I open domain.com/deny.php?email=example#example.com (logged in) that row should be deleted from the table, but it doesn't, I just get redirected to index.php. What am I doing wrong?
EDIT: There is no mistake in database.php as it works everywhere else in my project. Also, I don't get any error messages.

Variable $connection is undefined. Impossible, what is happening there?

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.

Undefined variables errors

So i'm working on a project and i am running to to a few mysql & php errors.
First Error :
This is all code associated with First Error
// Database Class
class Database {
public $_link, $_result, $_numRows;
public function __construct($server, $username, $password, $db){
$this->_link = mysql_connect($server, $username, $password) or die('Cannot Execute:'. mysql_error());
mysql_select_db($db, $this->_link);
}
public function disconnect(){
mysql_close($this->_link);
}
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result);
}
public function numRows() {
return $this->_numRows;
}
public function rows(){
$rows = array();
for($x = 0; $x < $this->numRows(); $x++) {
$rows[] = mysql_fetch_assoc($this->_result);
}
return $rows;
}
}
// Setup.php
$is_set = 'false';
global $company_name, $ebay_id;
if( isset($_POST['ebay_id'], $_POST['company_name']) ){
$_ebay_id = $_POST['ebay_id'];
$_company_name = $_POST['company_name'];
$is_set = 'true';
} else {
// Silence is Golden!
}
$_service_database = new Database('localhost', 'root', 'password', 'chat-admin');
$_service_database->query("SELECT * FROM installs WHERE `identity` = '$mysqldb' AND `db_name` = '$mysqldb'");
if ($_service_database->numRows() == 0){
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
} else {
// header("Location: index.php");
}
$_service_database->disconnect();
?>
<form name="setup" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input placeholder="eBay Username" type="text" name="ebay_id">
<input placeholder="Company Name" type="text" name="company_name">
<input type="hidden" name="insert" value="true">
<input type="submit">
</form>
So what this does is checks if the variables defined are in the database if they are not then when the form is submitted it inserts our values, if they are in the database it redirects to index.php, ok so i am receiving the all mighty MySQL num_rows* expects parameter 1 to be resource, boolean given ..., now i have searched everywhere and only found that the die error should solve, that is why you can see it on line 16 in the function query, now although i get the error everything still works its not really good for me to turn error reporting off so any help would be great. Also if you see undefined variables like $mysqldb they are actually set but on a different page and they are valid
Second Error : = function made for simplicity of a templating system
This is all associated with Second Error
function get_content_type($value){
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}
if($value == $title[1]){
echo '<title>'.$value.'</title>';
} else if ($value == $css[1]) {
echo '<link rel="stylesheet" href="'.$value.'">';
} else if ($value == $javascript[1]) {
echo '<script src="'.$value.'"></script>';
}
}
// Calling
get_content_type('title: Welcome to my site');
get_content_type('css: http://something.com/style.css');
get_content_type('js: http://code.jquery.com/jquery-latest.min.js');
everything works as this outputs
<title>Welcome to my site</title><link rel="stylesheet" href="http://somesite.com/style.css"><script src="http://code.jquery.com/jquery-latest.min.js"></script>
Only when i set error_reporting(0);
The errors i get are undefined variables because obviously i'm setting one, then im unsettling that one and setting the other so eventually only 1 is true although its already outputted all of them correctly.
UPDATE
Second Error : Errors =
Notice: Undefined variable: css in C:\Server\www\hidie\libs\test.php on line 19
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
First Error : Errors =
ERROR: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Ok so here's your problem:
First, as mentioned in the comment, mysql_num_rows only works on select and show. You have it in your query method, which is called by an insert. You can't do that.
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result); // <- BAD!
}
You call it on this line:
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
You could make a second method for database and call it for all calls that write to the db:
public function execute($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
}
which would be called like so:
if($is_set == true){
$_service_database->execute("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
Second, you need to implicitly define the variables $css and $title outside of those conditionals. Otherwise you are attempting to call undefined vars as indicated by the message...
$title = "";
$css = "";
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}

MySQL Query: Trying to get property of non-object

I'm getting following error message.
Notice: Trying to get property of non-object in
C:\xampp\htdocs\my\include\user_functions.php on line 34
Here is my Code
$conn = db_connection();
if($conn == false) {
user_error('Unable to connect to database');
return false;
}
$query = "UPDATE user SET passwd = '".$new_passwd."'
WHERE username = '".$username."' ";
$result=$conn->query($query);
if($result == false) {
user_error('Query Error'.$conn->error);
return false;
}
if($result->num_rows == 1) {
echo 'Password changed';
} else {
echo 'Failed ';
}
here is my db_connection
function db_connection() {
$db = new mysqli('localhost','root','','php_login');
if(!$db) {
echo 'Could not connect to database server';
} else {
return $db;
}
}
The UPDATE statement doesn't return a result set. What are you trying to get from fetch_array?
UPDATE
class mysqli{
public $aff_num_rows;
//some properties
//some properties
//some methods
//some methods
public function query($sql)
{
$resultset = mysql_query($sql); //after query instantiate the $aff_numrows
//property with function
$this->aff_num_rows = mysql_affected_rows(); //guess you are using sqlite
//so you might have different function
//and you can use this property
}
}
And in you code you have
if($conn->aff_num_rows == 1) {
echo 'password changed';
} else {
echo 'error changing pasword';
}

Categories