Jump to content

need help to make links hidden if not admin


alexandre
 Share

Recommended Posts

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
	header('Location: index.html');
	exit;
}
include 'functions.php';
// Connect to MySQL
$pdo = pdo_connect_mysql();
// MySQL query that retrieves all the polls and poll answers
$stmt = $pdo->query('SELECT p.*, GROUP_CONCAT(pa.title ORDER BY pa.id) AS answers FROM polls p LEFT JOIN poll_answers pa ON pa.poll_id = p.id GROUP BY p.id');
$polls = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once '../donation-clash/includes/connect_db2.php';
if ($stmt = $con->prepare('SELECT admin_id,	admin_name, admin_balance, admin_status FROM admins WHERE admin_id = ?')) {
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($id, $admin_name, $admin_balance, $admin_status);
$stmt->fetch();
// Store the result so we can check if the account exists in the database.
$admin = mysqli_query($con, $stmt);

 if (isset($admin)) {
	$create =	'<a href="create.php" class="create-poll">Create Poll</a>';
	$delete =	"<a href='delete.php?id=<?=$poll['id']?>' class='trash' title='Delete Poll'><i class='fas fa-trash fa-xs'></i></a>";
		}
	else if (!isset($admin)) {
		unset($create);
		unset($delete);
		}
}
?>

<?=template_header('Polls')?>

<div class="content home">
	<h2>Polls</h2>
	<p>Welcome to the home page! You can view the list of polls below.</p>
	<?=$create?>
	<table>
        <thead>
            <tr>
                <td>#</td>
                <td>Title</td>
				<td>Answers</td>
                <td></td>
            </tr>
        </thead>
        <tbody>
            <?php foreach($polls as $poll): ?>
            <tr>
                <td><?=$poll['id']?></td>
                <td><?=$poll['title']?></td>
				<td><?=$poll['answers']?></td>
                <td class="actions">
					<a href="vote.php?id=<?=$poll['id']?>" class="view" title="View Poll"><i class="fas fa-eye fa-xs"></i></a>
            <?=$delete?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?=template_footer()?>

i have this php poll code that i found and i am trying to implement it into my website. my issue here,  is that i cant seem to be able to store the links into variables without changing its php code inside it. also the person was using pdo and his logic is way above my knowledge right now so the mysqli extension you can see is my test i am trying to implement the "create" button and "delete" button to disapear if the user is not admin. there are other files to this poll but  i think the required code is all on this page. i am getting unexpected string content error on this try.

Edited by alexandre
Link to comment
Share on other sites

no the instruction was in another code sorry , just the code is important not the instructions since there might be different parts of different tutorials that i used. i should have removed them a while ago i usualy dont use instructions and just read the code.

14 minutes ago, requinix said:
// Store the result so we can check if the account exists in the database.
$admin = mysqli_query($con, $stmt);

Are you sure you want to do that?

 

 

Link to comment
Share on other sites

15 minutes ago, alexandre said:

what i do at this line is simply to verify if there is data with this session id

That code doesn't do that.

 

16 minutes ago, alexandre said:

the data fetched will be used later for other stuff.

That will be a problem as you don't store the data, you just fetch it and throw it away.

Link to comment
Share on other sites

2 minutes ago, Barand said:

That code doesn't do that.

 

That will be a problem as you don't store the data, you just fetch it and throw it away.

if i use those fetched variables in this same script , it will be fine right? when i say later , i mean that later i will add more features. i always fetch the data i need right before using it, so this will mostly be for the sidebar displaying links and the balance and user levels etc..

Link to comment
Share on other sites

fixed it but i still have to display something in the place of the buttons or this will display a undefined variable error. i just compared the session id with the id fetched and this does it for now.

if ($stmt = $con->prepare('SELECT admin_id,	admin_name, admin_balance, admin_status FROM admins WHERE admin_id = ?')) {
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($id, $admin_name, $admin_balance, $admin_status);
$stmt->fetch();

 if ($_SESSION['id'] == $id) {
	$create =	'<a href="create.php" class="create-poll">Create Poll</a>';
	$delete =	"<a href='delete.php?id={$poll['id']} class='trash' title='Delete Poll'><i class='fas fa-trash fa-xs'></i></a>";
		}
	else if ($_SESSION['id'] != $id) {
	$create = "<div class='annonce'>only admins can create polls</div>";
		$delete = "<div class='announce'>only admins can delete polls</div>";
		}
}

 

Link to comment
Share on other sites

even simpler and better solution was to make two files one for the user and one for the admin output and then verify at the very start if they are an admin or not then redirect the user to the user output page if he is not admin. this way i just had to remove the two undesired links for the simple users page and it fixes my issue. everything is working perfectly now.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
	header('Location: index.html');
	exit;
}
require_once '../donation-clash/includes/connect_db2.php';
$stmt = $con->prepare('SELECT admin_id, admin_name, admin_balance, admin_status FROM admins WHERE admin_id = ?');
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($admin_id, $admin_name, $admin_balance, $admin_status);
$stmt->fetch();
$stmt->close();
if ($_SESSION['id'] != $admin_id) {
	header('location: user_poll.php');
	exit;
}
else {
include 'functions.php';
// Connect to MySQL
$pdo = pdo_connect_mysql();
// MySQL query that retrieves all the polls and poll answers
$stmt = $pdo->query('SELECT p.*, GROUP_CONCAT(pa.title ORDER BY pa.id) AS answers FROM polls p LEFT JOIN poll_answers pa ON pa.poll_id = p.id GROUP BY p.id');
$polls = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<?=template_header('Polls')?>

<div class="content home">
	<h2>Polls</h2>
	<p>Welcome to the home page! You can view the list of polls below.</p>
	<a href="create.php" class="create-poll">Create Poll</a>
	<table>
        <thead>
            <tr>
                <td>#</td>
                <td>Title</td>
				<td>Answers</td>
                <td></td>
            </tr>
        </thead>
        <tbody>
            <?php foreach($polls as $poll): ?>
            <tr>
                <td><?=$poll['id']?></td>
                <td><?=$poll['title']?></td>
				<td><?=$poll['answers']?></td>
                <td class="actions">
					<a href="vote.php?id=<?=$poll['id']?>" class="view" title="View Poll"><i class="fas fa-eye fa-xs"></i></a>
                    <a href="delete.php?id=<?=$poll['id']?>" class="trash" title="Delete Poll"><i class="fas fa-trash fa-xs"></i></a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?=template_footer()?>

.

Link to comment
Share on other sites

so, now you have to maintain two almost identical pages, where every change you make to the poll output, must be repeated in both pages. that's the wrong direction to move toward when doing programming. you want to reduced the amount of work you have to do to create and maintain a web site, not increase it.

what's wrong with adding a simple conditional test where the two links appear at in the html document, so that they are only output if the current user is an admin? Keep It Simple (KISS.)

edit: i also recommend that you convert your mysqli based code to use PDO. it is very simple to do so and actually eliminates a bunch of lines of code. you will also be able to directly fetch the result from the query into an appropriately named array variable, such as $user_data, so that you don't need to worry about naming a bunch of variables to keep from overwriting other variables that may already exist.

Edited by mac_gyver
Link to comment
Share on other sites

27 minutes ago, alexandre said:
FROM admins

you should have one login system with a single set of ids. if your user login system and admin login system reuses ids, those users having ids the same as an admin will appear to be the admin with that same id. Keep It Simple.

Link to comment
Share on other sites

On 11/18/2022 at 12:18 AM, mac_gyver said:

you should have one login system with a single set of ids. if your user login system and admin login system reuses ids, those users having ids the same as an admin will appear to be the admin with that same id. Keep It Simple.

yes it was the purpose too, since i am planning to make this a community based platform, there are strong chances that loyal users will end up being lifted to simple admin or stuff like that also for now the only admin is my account that i added and i have total control over who is going to have access to that admin status. and about making two different pages it just seemed extremely simple compared to what i had to do to get to almost the same result, its just that i am still too much uncomfortable with pdo to merge all my code to it, but my main issue is that i have to use code samples  that i didnt write and it makes it a lot more complicated for myself to find a way around issues created by changing things as simple as a coma in the other person code. all in all i appreciate your advices and will try to make it better for my further developping experiences.

Link to comment
Share on other sites

If pdo is THAT complicated for you to switch to then simply write your mysqli way of doing something and we can easily show how it needs to look.  That's what we are here for.  Of course if you just went to the php manual you would see examples of how to use pdo.  And once you do that you will see how much simple pdo is as opposed to all of the other functions that mysqli uses.

When mysql was deprecated and removed I made the highly-suggested move to PDO and am so glad I didn't make the easier switch to mysqli.

Link to comment
Share on other sites

yeah i understand what you mean, and thank you for the advice , also i read the manual and i try to learn new stuff from time to time but mysqli just gotten into me, the functions and parameter setups are way simpler in my opinion. and until now i didnt really fell onto something that i could not achieve with mysqli. if i ever get something that i would need pdo absolutely  i will learn how to do what i need to do but if my brain doesnt judge it vital, there is no way i retain any informations even if wanted. i know myself. i have three features left to code into my website and i hope that i wont need pdo 🤣 shopping cart, voucher code system and a wallet of my creation for managing their currency on my website.  

if anyone needs inspiration about something to create, there is this other project i have been thinking since i was launching crypto currencies with a friend. i obviously doesnt have the knowledge to realize it so if anyone see this, feel free to dive in. 

so here is the idea long story short, i despise social networks but i cant help but imagining a better platform for users. when you look at the actual biggest social networks, you think of a profile page for anyone that you want to have access, so it is suitable for normal users who just use example messenger and never go on the actual social network. My idea here is to make a platform for the influencers , the one trying to build something out of their name or companies. from there i thought about a way to give a value to each users account. for doing so you imagine a normal account creation but on a main blockchain(representing the social network itself and its currency) where each account would be built on a fork of the main blockchain. if you succeed to achieve this then all you have to do is to work on a strong algorithm to calculate the value of the main currency of the platform from which the forked currencie's values will be defined by the demand and how many of the coins are in circulation for each account. so when you think of the influencers doing their things to try to make their own values out of nothing. so a platform like that would provide a safe and secure way to establish a personal value, as in every single human beings should have the equal chances of success and decide if they have the will to do something of their lifes, if you provide them the right tool a huge economy could run after that. that governments likes it or not crypto-currencies are the future of the actual economy and i think its better to start doing it yourself right now then letting facebook doing it in 20 years. it is a pretty simple concept but out of reach for me.

Link to comment
Share on other sites

this means nothing to me, a lot of things can lead to a company going banckrupt. if things are handled well this wont affect at all ,the value of a currency is defined by the belief of the people into it and nothing else. when people will realize that, if they was all trying to get all their money out of the banks , all at the same time , there would never be enough physical money for everyone. banks are functioning on the concept that they owe you money if you deposit. if they give you credits or you have a mortgage to pay then you owe them money that doesnt even exist in the first place this money is reinjected in the system when you pay your interests on it. most of people are stuck in a endless loophole where they can always pay only the minimum so in the end they end up paying forever that same amount of money over and over again ... yes people need to wake up and pull out something transparent safe and secure to use, to give people access to their actual money without them paying everytime they need to spend. a lots of things are to be done but i am telling you , there is no other futur for an economy than a digital currency. you can also think about the price it cost just to print physical money , if i am right they spent five times what they printed in value last time to create and print this new plastic paper.. i am really trying to find any logical reason for everyone to still be so blind about the society and governments , there is so much to say but so little tolerance about negativity that it becomes useless to even try to reason others.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.