PHP isUserAdmin function - php

I want to read from a MySQL table whether it is an admin. In the row "Status" there is a 1 or a 0. Is it greater than 0 then it is an admin.
PHP:
<?php
if($db->isUserAdmin() === TRUE) {
echo 'Admin';
} else{
echo 'Noadmin';
}
?>
MySQLi:
function isUserAdmin() {
$stmt = self::$_db->prepare("SELECT Status FROM users WHERE Session=:sid");
$stmt->bindParam(":sid", session_id());
$stmt->execute();
if($stmt->rowCount() < 1) {
return true;
} else {
return false;
}
}

Just to educate the great folks of Stack Overflow
function isUserAdmin()
{
$stmt = self::$_db->prepare("SELECT Status FROM users WHERE Session=?");
$stmt->execute([session_id()]);
return $stmt->fetchColumn(); // here is what you really need
}
if($db->isUserAdmin()) {
echo 'Admin';
} else{
echo 'Noadmin';
}

You are checking the number of rows returned by the query, not the value of the status.
If it's admin or user and have a session will always return true because there is an entry in users table. If no user exists will always return false.
You need to check the data returned by sql and check if the value of Status > 0
Or change the sql and add there an extra check that Status > 0

Related

Retrieving value from SQL query

It's probably too late, and I'm too tired... but I'm trying to check if a value in my SQL is set to 1 or not. And return true if it is. Been a while since I've done SQL so I'm probably just being stupid...
My code is
$query = mysqli_query($sqlConnect, "SELECT featured FROM al_posts WHERE post_id = {$post_id}");
if ($query->featured == 1) {
return true; }
else {
return false; }
As per the docs:
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You should do:
$query = mysqli_query($sqlConnect, "SELECT featured FROM al_posts WHERE post_id = {$post_id}");
if ($query->fetch_object()->featured == 1) {
return true; }
else {
return false; }
You can read more about mysqli_result here.

Confirming deletion of record in mysql php

I m trying to delete a row in php mysql. The row is deleted quiet ok but mysqli_affected_rows($conn) is not giving a response so I can confirm the deletion for the user.
$sql="DELETE FROM `users` WHERE `memberID`='$id'";
$res=mysqli_query($conn,$sql);
if(mysqli_affected_rows($conn) == 1){
echo 'success'
} else {
echo "The User could not be deleted due to some error";
echo mysqli_affected_rows($conn);
}
You don't need to check by boolean value 0 or 1. But if you want to do it that way, you will need to declare a flag before that and then change the flag value according to condition after that you can do it [as your way]
(mysqli_affected_rows($conn) == 1)
But as default a simple if() conditon will check and return true on pass and false on fail.
So, simply you can do:
if($res)
{
//your codes if query is done
} else
{
//your codes if query fails
}
By default, the mysqli_query() function will return you a true if all went well or a false if there is any error. You can check if your query did not return any error like so:
if($res) {
echo "Delete success";
} else {
echo "Delete error: " . mysqli_error();
}

if row equals parameter from url

my url i have a parameter called uid
in my sql i have
Select * from users Where uid = {$_GET['uid']}
now I have my while loop
while (($row = mysqli_fetch_assoc($result)) != false) {
$uid = $row['uid'];
}
every thing is fine to this point. what i want is if the uid in the database does not equal the $_GET from parameter redirect.
if ($uid == $_GET['uid']) {
return true;
} else {
redirect(ROOT_URI);
}
what i am trying to prevent is modifying uid in the url. that if the uid does not exists it will redirect.
simply you can do like this
$rowcount=mysqli_num_rows($result);
if($rowcount != 0)
{
return true;
}
else
{
redirect(ROOT_URI);
}
since if the uid is in the table mysqli_num_rows doesn't return 0
Use this. I've included some comments as explanation to what I am doing.
$x = 0; //checker
while (($row = mysqli_fetch_assoc($result)) != false) {
if($uid == $row['uid']){
$x = 1; //logic is if there is a match, $x will become 1, else it will stay at 0 value
}
}
//now check the value of $x
if ($x == 1){
//there is a match
return true;
}
else{
//there is no match
redirect(ROOT_URI);
}
To redirect in PHP, you can use the header() function:
header("Location: your_url");
Your sql query is wrong. Try with this one:
Select uid from users Where uid = {$_GET['soldier']}

PHP/MySQL - Prepared Statements - Is the usage in this example correct?

I am creating an part of a website that deals with confirmation of a user subscribing to a newsletter.
I am having trouble with the usage on prepared statements when selecting data.
This is basically a check against information that was sent to the user in an email and retrieved by getting the info from the entered url.
So there is a string or 'key' in the database that is sent to the user in an email as a link to a page on my site with the users details appended to the url. The script checks to see if these keys match
The problem is that when I run the script it will trigger an error. This says "wrong key".
The key in the database ($dbkey) is the same as the key provided in the email link. which is the same key that is made into $key. The problem though, is that in the while loop an error is being triggered and $dbkeyis not being passed the data from the database :
Notice: Trying to get property of non-object in C:\wamp\www\site\script.php on line 35
The sql statement when run in phpmyadmin does return the correct result set.
Here is the code:
$confirm= sanitize($_GET['confirm']);
$stmt = $link->prepare("SELECT id, dbkey FROM specials WHERE id = ?");
if (!$stmt)
{
$error = "{$link->errno} : {$link->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
if (!$stmt->bind_param("i", $confirm))
{
$error = "{$stmt->errno} : {$stmt->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
if (!$stmt->execute())
{
$error = "{$stmt->errno} : {$stmt->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
$stmt->store_result();
if ($stmt->num_rows)
{
while ($row = $stmt->fetch())
{
$dbKey = $row->dbkey;
}
$key= sanitize($_GET['key']);
if ($dbKey !== $key)
{
echo 'wrong key';
}
}
else
{
echo 'not in database';
}
I would like to say that all other scripts connecting to the database in this manner do work, but this was the first time I have used prepared statements to select data. I wonder if this problem is caused by an error in my coding, hence the reason why I have posted this question.
If anyone could spot where I have gone wrong here, or possibly possibly provide some advice on how I would debug the code to see what exactly the error is that would be greatly appreciated!
Thanks!!
EDIT: The problem simply is the $key returns a string but $dbkey returns empty
EDIT2:
if ($stmt = $link->prepare("SELECT id, verified, dbkey FROM specials WHERE id=?")) {
$stmt->bind_param("i", $confirm);
$stmt->execute();
$stmt->bind_result($dbId, $dbVerified, $dbKey);
$stmt->fetch();
$stmt->close();
if ($dbKey !== $key)
{
echo 'wrong key';
}
else if ($dbVerified == 1)
{
echo 'already activated';
}
else if ($dbKey == $key && dbVerified == 0)
{
echo 'success';
}
}
else
}
echo 'user not in db';
}
$stmt->fetch() just returns a boolean indicating whether it was successful, not an object whose properties are the current row's fields. You need to call $stmt->bind_result() to specify into which variables you want the fields to be placed.
The approach taken in your second edit looks good, except that the test for whether the user is in the database should be onfetch(), not prepare() (or else use num_rows as you had previously). Thus:
if ($stmt = $link->prepare("SELECT id, verified, dbkey FROM specials WHERE id=?"))
{
$stmt->bind_param("i", $confirm);
$stmt->execute();
$stmt->bind_result($dbId, $dbVerified, $dbKey);
if ($stmt->fetch())
{
if ($dbVerified == 1)
{
echo 'already activated';
}
else if ($dbKey !== $key)
{
echo 'wrong key';
}
else if ($dbKey == $key && dbVerified == 0)
{
echo 'success';
}
}
else
}
echo 'user not in db';
}
$stmt->close();
}

How to test if a MySQL query was successful in modifying database table data?

I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false if the query fails, as I've below.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
$delRecord->close();
echo "true";
} else {
echo "false";
}
}
I would like to know what I have missed and the correct way to check if a query was successful or not.
You're currently only checking whether the SQL statement is correctly prepared, you're not checking whether it actually deleted the record.
Try:
...
echo ($delRecord->affected_rows > 0) ? 'true' : 'false';
$delRecord->close();
That doesn't address whether you're correctly checking the result string in your Javascript code - if that's a problem we'll need more information.
You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).
Taking your example, and modifying nothing but for the above:
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
if ($delRecord->affected_rows > 0) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
}
Use the return value of mysqli_stmt->execute() to see if the query was executed successful.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
$delRecord = $con->prepare($deleteQuery);
if ( $delRecord === false ) {
echo "false";
}
$delRecord->bind_param("s", $pk);
if ( $delRecord->execute() ) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
Checking prepare() could be left out because the query is fixed and should be working (unless there is an error on the server side). execute() returns true, if the query was executed successful. Using affected_rows() can be misleading because perhaps there was no item to delete and therefore affected_rows() whould return 0. Nontheless the query was successfully executed.
function run_query($query,$conn,$dbname){
$conn->select_db($dbname);
if($result = $conn->query($query)){
return $result;
}
else{
echo 'error ';
exit();
}
}
run_query() accepts three parameters, the query, connection, and DB. will through an error if the query was unsuccessful, else result object will be returned.

Categories