i'm currently trying to start using MySQLi instead of MySQL, but for some reason that I don't understand this is working for the first part of changing the password, but then failing on the error message. Can anyone tell me why? Cheers
$sql1 = <<<SQL
SELECT *
FROM Users
WHERE UserID = '$UserID'
&& Password = '$hashedPW'
SQL;
if ($db->query($sql1)) {
$sql2 = $db->query("UPDATE Users SET Password = '$NEWhashedPW' WHERE UserID=$UserID");
if($db->affected_rows === 0) { echo $_SESSION['changepass'] = 'error'; header('Location:'.$_SERVER["HTTP_REFERER"]);
} else {
$_SESSION['changepass'] = 'success'; header('Location:'.$_SERVER["HTTP_REFERER"]);
}
} else {
echo 'error';
}
$result1->free();
$db->close();
Question, why are you looping through the data if only 1 result is being returned?
$sql1 = "SELECT * FROM `Users` WHERE `UserID` = ".$UserID." AND `Password` = '".$hashedPW."'";
$result = $db->query($sql1);
if($db->num_rows($result)) { // Assuming you have a num_rows() function
$db->query("UPDATE `Users` SET `Password` = '".$NEWhashedPW."' WHERE `UserID` = ".$UserID);
$_SESSION['changepass'] = !$db->affected_rows() ? 'error' : 'success';
header('Location:'.$_SERVER["HTTP_REFERER"]);
} else
echo "User not found";
$result1->free();
$db->close();
This is also assuming that your query() function has some form of debugging ability and that you have a num_rows() function
If not, write one!
The num_rows() function should work similar to this (procedural style):
function num_rows($res) {
return mysqli_num_rows($res);
}
Simply whack that into your database class and you should be good to go.
May need edits, I don't know how your DB class is set up
Related
I'm working on this project and I need help with something. I am trying to check if someone is already in the database upon logging in and if they are not, they will be added. However, my code always adds them to the database...
Login code:
<?php
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE '$emaillogin' = `emailadress`
AND '$passwordlogin' = `password` LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
echo "E-mail or password incorrect! <br>";
}else{
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
header("location:home.php");
die();
}
}
?>
The function in functions.php:
function check_firstest($accnr){
$query = mysql_query("SELECT count(*) AS 'num' FROM `VRIENDEN` WHERE `accnr` = '$accnr' AND `vriendnr` = '$accnr'");
if($result > 0){
return true;
}
else{
return false;
}
}
The login on its own works just fine, so thats no problem.
Thank you!
Your first query is somewhat odd and you do not capture the values from $_POST into the variables that you are using in the query either
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE `emailadress` = '{$_POST['emaillogin']}'
AND `password` = '{$_POST['passwordlogin']}'
LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
// something went REALLY WRONG, report it
echo mysql_error();
exit;
}
if ( mysql_num_rows($result) == 1 ) {
// found user and password matches
header("location:home.php");
exit;
}else{
// new user, create the account
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
// and go to home page
header("location:home.php");
die();
}
}
?>
And of course the fix for the check_firstest() is also required
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
But I have to add
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
And
You should not be using the mysql_ database extension, it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
You have to count the resulting rows:
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
Here the mysql_num_rows() function gives the number of rows in the result set. If it is greater than 0 then it means that there is some data.
I was getting the fatal error while trying to run mysql delete transaction so i searched for similar issues and it became obvious using mysqli_fetch_assoc is the way to fix this. Tried a couple of times but am obviously doing something wrong, would appreciate any help.
Here's my code
<?php
$selected_admin = find_admin_by_id($_GET["admin"]);
if (!$selected_admin) {
redirect_to("sadmin.php");
}
while ($admin = mysqli_fetch_assoc($selected_admin)) {
$admin_id = $selected_admin["admin_id"];
}
$sql = "delete from admin where admin_id = {$admin_id} limit 1";
$result = mysqli_query($connection, $sql);
if ($result && mysqli_affected_rows($connection) == 1) {
$SESSION["message"] = "Admin successfully deleted.";
redirect_to("sadmin.php");
} else {
$SESSION["message"] = "Admin was not deleted successfully.";
redirect_to("sadmin.php?admin={$admin_id}");
}
?>
And the function am calling is this
function find_admin_by_id($admin_id) {
global $connection;
$query = "select * from admin where admin_id = {$admin_id} LIMIT 1";
$current_admin = mysqli_query($connection, $query);
confirm_query($current_admin);
return $current_admin;
}
You are using wrong variable in while loop and my other mate also mentioned one hour ago, here is the correct code with minor changes:
<?php
$selected_admin = find_admin_by_id($_GET["admin"]);
if (!$selected_admin) { redirect_to("sadmin.php");
}
while ($admin = mysqli_fetch_assoc($selected_admin))
{
$admin_id = $admin["admin_id"];
}
if( intval($admin_id) > 0 ){
$sql = "delete from admin where admin_id = {$admin_id} limit 1";
$result = mysqli_query($connection, $sql);
if ($result && mysqli_affected_rows($connection) == 1)
{
$SESSION["message"] = "Admin successfully deleted.";
redirect_to("sadmin.php");
}
else {
$SESSION["message"] = "Admin was not deleted successfully."; redirect_to("sadmin.php?admin={$admin_id}");
}
}
?>
What I change:
Change $selected_admin as $admin.
And add if condition before executing DELETE STATEMENT.
So I'm making a usergroup function that allows me to block off pages to lower user levels. This is my function for grabbing info:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result-fetch_assoc()){
$info = $row[$requested_info];
return $info;
}
}
Right here:
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
is where something is going wrong. This is my method for grabbing the info:
$id = $_SESSION['user_id'];
$rank = grab_info($id, 'rank');//Gets rank from our id
$meets = can_access($rank, 4, true);//We're saying our user has a rank of 1 to access this page you need a rank of 3 and only 3 hence strict
if ($meets == false){//user cant access page
header("Location: index.php");
die();
}
Basically, it just keeps giving me the "There as a query error for some reason handle your query error" and I'm stuck. New to php so sorry if it's messy.
Using prepared statements and cast the variable as an integer.
$stmt = $con->prepare("SELECT * FROM `users` WHERE `id` = ?");
$stmt->bind_param("i",$id);
$id = (int) $_SESSION['user_id'];
$stmt->execute();
$result = $stmt->get_result();
Check to make sure that $id is actually set. If it's null that will cause your query to explode.
$sql = "SELECT * FROM `users` WHERE `id`='{$id}'";
Try this :)
$query=mysql_query("SELECT * FROM user WHERE user_email='$user_email');
Please try this:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM users WHERE id =". $id;
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result->fetch_assoc()){
$info = $row;
return $info;
}
}
I am trying to rewrite the following function in different way but it seems that I missed something and I do not get the intended functionality?
Could anyone suggest anything?
Thanks in advance.
Function 1
function user_exists($email) {
$email=mysql_real_escape_string($email);
$query=mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `email` = '$email'");
return(mysql_result($query, 0) == 1) ? true : false;
}
Rewritten Function 1
function user_exists($email) {
$email=mysql_real_escape_string($email);
$query=mysql_query("SELECT user_id FROM users WHERE email='$email'");
$count=mysql_num_rows($query);
if ($query !=0) {
return(true);
} else{
return(false)
}
function user_exists($email)
{
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT user_id FROM users WHERE email='$email'");
if (mysql_num_rows($query) > 0)
{
return true;
}
else
{
return false;
}
}
function user_exists($email) {
// Escape to prevent sql injection
$email = mysql_real_escape_string($email);
// Query to see if the email exists in the DB
if(false === ($query = mysql_query("SELECT user_id FROM users WHERE email='$email'"))){
// handle error
$result = false;
}
else{
// Find a row? Email exists, otherwise does not
$result = (mysql_num_rows($query) > 0);
}
return $result;
}
The DB query itself could be more efficient (select a count, or at least limit to 1 result max), but this is the general idea.
function user_exists($email) {
$email=mysql_real_escape_string($email);
$query=mysql_query("SELECT user_id FROM users WHERE email='$email' LIMIT 1");
return mysql_num_rows($query) == 1;
}
LIMIT 1 is a good practice since the engine stop searching on the first match and does not continue for the next rows
<?php
function user_exists($email)
{
// Perform database query
$email = mysql_query("SELECT user_id FROM users WHERE email='$email'");
if (!$email) {
die("Database query failed: " . mysql_error());
}
// Use returned data
while ($row = mysql_real_escape_string($email)) {
if ($row !=0) {
return(true);
}
}
}
?>
This is a really simple thing, but it's not working for some reason. Heres my code.
I am making function (its part of a class) which checks if a username or email exists:
public function exists ($what, $who)
{
$sql = "SELECT * FROM users WHERE $what = $who";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 0)
{
return true;
}
else
{
return false;
}
}
The function returns nothing. In fact if I run that query through regular PHP it returns nothing also. I don't understand why.
This following piece of code returns news entries perfectly:
function fetch($id = '')
{
if (empty($id))
{
$query = 'SELECT * FROM news ORDER BY id desc';
}
elseif (is_numeric($id))
{
$query = "SELECT * FROM news WHERE id = $id";
}
else
{
$route->to(SITE_URL);
}
$result = mysql_query($query);
if (mysql_num_rows($result) > 0)
{
return $result;
}
}
I am confused.
The problem is that you are missing quotes in your query:
$sql = "SELECT * FROM users WHERE $what = $who";
//SELECT * FROM users WHERE username = Mario is not a valid query
should be:
$sql = "SELECT * FROM users WHERE $what = '$who'";
the other queries are working because you are checking against an id, in this case against a string (and in this case you need quotes)
maybe the query execution failed and you have error turned off on screen in your php.ini
Try to add an intermediate check on the correct execution of the query:
$query = mysql_query($sql);
if ($query === FALSE) {
// log error with mysql_errno($conn) and mysql_error($conn);
} else {
if (mysql_num_rows($query) != 0) {
return true;
etc. etc.