Level/Group label system? - php

I am working on a login system and have a basic admin/level system implemented in to it. Right now the levels are just numbers (1-9). I do however have them labeled as different names or groups. For example, 1=member, 2=Supporter and so on. I also have a member list that displays the user id, level, and time of last activity. However it only shows the number for the id (as to be expected). My question is how would I set it up so the numbers end up displaying the name/group on the member list?
Thanks in Advanced, Josh
Here is the code for the table:
<?php
include("include/session.php");
function displayUsers(){
global $database;
$q = "SELECT username,userlevel,email,timestamp "
."FROM ".TBL_USERS." ORDER BY userlevel DESC,username";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "Database table empty";
return;
}
/* Display table contents */
echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n";
echo "<tr><td><b>Username</b></td><td><b>Level</b></td><td><b>Last Active</b></td></tr>\n";
for($i=0; $i<$num_rows; $i++){
$uname = mysql_result($result,$i,"username");
$ulevel = mysql_result($result,$i,"userlevel");
$time = mysql_result($result,$i,"timestamp");
echo "<tr><td>$uname</td><td>$ulevel</td><td>$time</td></tr>\n";
}
echo "</table><br>\n";
}
?>
my "array":
<?php echo $form->error("upduser"); ?>
<table>
<form action="adminprocess.php" method="POST">
<tr><td>
Username:<br>
<input type="text" name="upduser" maxlength="30" value="<?php echo $form->value("upduser"); ?>">
</td>
<td>
Level:<br>
<select name="updlevel">
<option value="1">Member
<option value="2">Supporter
<option value="3">Donor
<option value="4">VIP
<option value="5">Veteran
<option value="7">Co-Founder
<option value="8">Founder
<option value="9">Admin
</select>
</td>
I just need help setting up an array with the code

You should add a table in your database with the info for the levels (id and name) then use a join in your query to get the name with the user details.
The other solution, which in my opinion is less advisable, would be to hard-code your array and display the corresponding level name:
function displayUsers(){
$levels = array('1'=>'Member','2'=>'Supporter','3'=>...);
//do_query
//loop results
$ulevel = $levels[mysql_result($result,$i,"userlevel")];
//continue loop
}

Related

Displays the current value taken from ENUM in form

I have a field in the mysql database of type "ENUM",
the field is called "career_status" and these values are stored,
Active,
Retired,
Dead
I created a form for update, the one I would like and display the current value in the form.
Example:
if now it is stored Active displaying Active in the form, if nothing is empty etc ..
How to get these values from the field?
this is the code
<?php
require_once("connetti.php");
$actor_id = $_GET["id"];
$query = mysql_query("SELECT * FROM actor WHERE actor_id=" . (int)$actor_id) or die ("Error in query: " . mysql_error());
$row = mysql_fetch_array ($query);
$nome=$row['nome'];
$performer_aka=$row['performer_aka'];
$website=$row['website'];
$career_status=$row['career_status'];
$birthday=$row['birthday'];
$died=$row['died'];
$status=$row['status'];
?>
<div id="BioData" style="overflow: hidden;">
<center><h1><?php echo $nome;?> <span class="infoblock-pagetype">modifica dati</span></h1></center>
<form action="<?php echo $_SERVER['PHP_SELF'] . '?id=' . $actor_id; ?>" method="post">
<tr>
<td class="paramname">
<b>Career Status: </b> (<b><font color="red">selezionare il valore</font></b>)
</td>
<td class="paramvalue">
<select name="career_status" id="career_status"><?php echo $career_status;?>
<option value="1">Active</option>
<option value="2">Retired</option>
<option value="3">Dead</option>
<option value="0"> </option>
</select>
</td>
</tr>
<?php
if (isset($_POST['modifica']))
{
//include "connetti.php";
//$query = mysql_select_db("xxx", $db);
if ($query)
{
$nome=$_POST['nome'];
$performer_aka=$_POST['performer_aka'];
$website=$_POST['website'];
$career_status=$_POST['career_status'];
$birthday=$_POST['birthday'];
$died=$_POST['died'];
$status=$_POST['status'];
$query=mysql_query("UPDATE actor SET
nome='".$_POST['nome']."',
performer_aka='".$_POST['performer_aka']."',
website='".$_POST['website']."',
career_status='".$_POST['career_status']."',
birthday='".$_POST['birthday']."',
died='".$_POST['died']."',
status='".$_POST['status']."'
WHERE actor_id=". $actor_id);
if($query) echo "<h2>Congratulazioni! Dati inseriti.</h2>";
else echo "<h2>Attenzione! Dati non inseriti!</h2>";
} else echo "<h2>Errore! Database non selezionato.</h2>";
}
?>
If I understood correctly that you wish to indicate which career_status option is currently selected for the record then perhaps the following might help
<select name='career_status'>
<?php
/* possible options for career status */
$status=array(
0=>'',
1=>'Active',
2=>'Retired',
3=>'Dead'
);
for( $i=0; $i < count( $status ); $i++ ){
/* is this item selected? */
$selected = $i==$career_status ? ' selected' : '';
printf('
<option value="%d"%s>%s',
$i,
$selected,
$status[ $i ]
);
}
?>
</select>

Pass PHP array through Select Option Fields

I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)

Cant get my user database to sort.

I have a user database which I want the admin to be able view users. I want the admin to be able to sort the users by different fields. (E.g first name or surname).
My problem:
Is that it wont sort. Im trying to do it using a drop down box and a submit button. I have have tried the Sql in phpMyAdmin to make sure the statement is correct which it is. I have also added a or die to make sure its not a mysql error. Im getting no errors its just not sorting. I have also tried echoing out the drop down to make sure the right value is being added to the variable.
code:
HTML drop down
<form action="View_users.php" enctype="multipart/form-data" name="sort" id="sort" method="post" align="right">
<label>
<select name="sortdropdown" id="sortdropdown">
<option value="<?php echo $sortby; ?>"><?php echo $sortby; ?></option>
<option value="name">First Name</option>
<option value="surname">Surname</option>
<option value="email">Email</option>
<option value="signupdate">Date</option>
</select>
</label>
<label>
<input type="submit" name="button" id="button" value="Sort" />
</label>
</form>
logic:
$sortby = "";
if (!isset($_POST['sortdropdown'])) {
$sortby = "surnname";
}else{
$sortby = mysql_real_escape_string($_POST['sortdropdown']);
}
// This block grabs the whole list for viewing
$product_list = "";
$counter = 0;
$sql = mysql_query("SELECT * FROM users ORDER BY '$sortby' ASC") or die(mysql_error());
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$counter++;
$id = $row["id"];
$email = $row["email"];
$name = $row["name"];
$surname = $row["surname"];
$lastlogin = $row["lastlogin"];
$signupdate = $row["signupdate"];
if (is_float($counter/2)) {$class = "#CCCCCC"; }
else {$class = "white";}
$product_list .= '<tr bgcolor="'.$class.'">
<td>'.$surname.'</td>
<td>'.$name.'</td>
<td>'.$email .'</td>
<td>View More</td></tr>';
}
} else {
$product_list = "There are no users in the system yet";
}
Thanks
The comments are correct, you should be using back ticks `$sortby` instead of '$sortby'
The reason is - single quotes are used to wrap values in MySQL, which is not what you want. You're passing the name of a table column, so you use back ticks because they are used to wrap table column names.

how do you use multiple dropdowns and know which status each has?

the below code shows a table with users to be accepted or declined. the code as it is has a dropdown on the end allowing to either accept it, deny it or leave as is. there is a button on the bottom to submit the form and after that there should be a php script that decides which user is accepted, denied or still pending.
what would be the best approach to make this work since i find it hard to link the dropdown box and the id.
<table align='center' width='90%'>
<tr>
<center><td><strong>ID:</strong></td></center>
<center><td><strong>Name:</strong></td></center>
<center><td><strong>Level:</strong></td></center>
<center><td><strong>Job:</strong></td></center>
<center><td><strong>Guild:</strong></td></center>
<center><td><strong>Date:</strong></td></center>
<center><td><strong>Action:</strong></td></center>
</tr>
<?php
$id = 0;
$result=mysql_query("SELECT * FROM accounts WHERE active ='0' ORDER BY date LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$id = $id + 1;
?>
<form method='POST' action=''>
<tr>
<center><td><?php echo $row['id']; ?></td></center>
<center><td><?php echo $row['user']; ?></td></center>
<center><td><?php echo $row['level']; ?></td></center>
<center><td><?php echo $row['job']; ?></td></center>
<center><td><?php echo $row['guild']; ?></td></center>
<center><td><?php echo $row['date']; ?></td></center>
<td>
<select name='action_<?php echo $row['id']; ?>'>
<option value='none'>None</option>
<option value='accept'>Accept</option>
<option value='decline'>Decline</option>
</select>
</td>
</tr>
<?php } ?>
<tr>
<br /><td align='right'><input type='submit' value='Submit' name='submit' /></td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit'])) {
if(isset($_POST['action_'.$row['id'].'']) && $_POST['action_'.$row['id'].''] == "accept" ) {
$acc = mysql_query("UPDATE `accounts` SET `active`='1' WHERE `id` = '".$row['id']."'");
echo "<meta http-equiv=refresh content=\"5; url=?wesofly=main&page=recruitment\">";
}elseif(isset($_POST['action_'.$row['id'].'']) && $_POST['action_'.$row['id'].''] == "decline" ) {
$dec = mysql_query("DELETE * from `accounts` WHERE '".$row['id']."'");
echo "<meta http-equiv=refresh content=\"0; url=?wesofly=main&page=recruitment\">";
}
}
?>
Your code is confusing. Your WHILE loop starts before the form tag, but the WHILE loop closes before the form tag closes. This means that you are going to have multiple form elements.
So, first of all, change that in your code. Next the way you want this to work is using arrays.
Your drop down box should look like this
<select name='action[<?php echo $row['id']; ?>]'>
<option value='none'>None</option>
<option value='accept'>Accept</option>
<option value='decline'>Decline</option>
</select>
Then on the PHP side, you should be able to do something like
foreach ($_REQUEST['action'] as $key => $value) {
$id = $key;
$status = $value;
// put your code here to update the specific database item
}
I think you'll be better off with HTML form arrays, for instance:
<select name="action[<?php echo $row['id']; ?>]">
<option value="none">None</option>
<option value="accept">Accept</option>
<option value="decline">Decline</option>
</select>
And inside your php code, you would simply loop through the submitted action field in your $_POST array to find which id had which action. Each entry would be presented as an array, the key would be the user's id.

How do I populate the selected value of drop down lists with Mysql data? [duplicate]

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
I need the values of form inputs to be populated by the sql database. My code works great for all text and textarea inputs but I can't figure out how to assign the database value to the drop down lists eg. 'Type of property' below. It revolves around getting the 'option selected' to represent the value held in the database.
Here is my code:
$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");
$row = $db->sql_fetchrow($result);
echo "<center><font class=\"title\">"._CHANGE_MY_INFORMATION."</font></center><br>\n";
echo "<center>".All." ".fields." ".must." ".be." ".filled."
<form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\">
<table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\">
<tr>
<td align=\"right\">".Telephone." :</td>
<td>
<input type=\"text\" name=\"telephone\" size=\"27\" value=\"$row[telephone]\"> Inc. dialing codes
</td>
</tr>
<tr>
<td align=\"right\">".Type." ".of." ".property." ".required." :</td>
<td>Select from list:
<select name=\"req_type\" value=\"$row[req_type]\">
<option>House</option>
<option>Bungalow</option>
<option>Flat/Apartment</option>
<option>Studio</option>
<option>Villa</option>
<option>Any</option>
</select>
</td>
</tr>
....
using your current code:
<?php
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
foreach($options as $option) {
if ($option == $row['req_type']) {
print '<option selected="selected">'.$option.'</option>'."\n";
} else {
print '<option>'.$option.'</option>'."\n";
}
}
?>
assuming $row['req_type'] is one of the values in $options. i strongly suggest quoting your array elements (ie $row['req_type'] instead of $row[req_type]. the latter method generates errors under error_reporting(E_ALL)
you also might want to look at resources such as phpbuilder.com. some articles are pretty outdated, but will provide you with some basics on how to better structure your code. (for example, separating your HTML from your PHP code woulud help readiability in this sitaution a lot).
edit: as per the comments, any information displayed should be escaped properly (see htmlentities() for example).
Nigel,
See the answer with the check mark next to it. It go me start in solving my problem. First I select my data from the table, then I select the data i want display in my dropdown menu. If the data from the primary table matches the data from the dropdown table selected is echoed.
$query9 = "SELECT *
FROM vehicles
WHERE VID = '".$VID."'
";
$result9=mysql_query($query9);
while($row9 = mysql_fetch_array($result9)){
$vdate=$row9['DateBid'];
$vmodelid=$row9['ModelID'];
$vMileage=$row9['Mileage'];
$vHighBid=$row9['HighBid'];
$vPurchased=$row9['Purchased'];
$vDamage=$row9['Damage'];
$vNotes=$row9['Notes'];
$vKBBH=$row9['KBBH'];
$vKBBM=$row9['KBBM'];
$vKBBL=$row9['KBBL'];
$vKBBR=$row9['KBBR'];
$vYID=$row9['YID'];
$vMID=$row9['MID'];
$vModelID=$row9['ModelID'];
$vELID=$row9['ELID'];
$vECID=$row9['ECID'];
$vEFID=$row9['EFID'];
$vColorID=$row9['ColorID'];
$vRID=$row9['RID'];
$vFID=$row9['FID'];
$vDID=$row9['DID'];
$vTID=$row9['TID'];
}
$query1 = "SELECT * FROM year ORDER BY Year ASC";
$result1=mysql_query($query1);
echo "<select name='Year'>";
while($row1 = mysql_fetch_array($result1)){
echo "<option value = '{$row1['YID']}'";
if ($vYID == $row1['YID'])
echo "selected = 'selected'";
echo ">{$row1['Year']}</option>";
}
echo "</select>";
May not be efficient, but it's simple & gets the job done.
$dropdown = str_replace("<option value=\"".$row[column]."\">","<option value=\"".$row[column]."\" selected>",$dropdown);
Thanks Owen. Your code seems perfect but gave lots of php errors. I simplified it to this but just get whitespace as options:
<td>Select from list: <select name=\"req_type\">
$option = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
foreach($option as $option) {
if ($option == $row[req_type]) {
<option selected>$option</option>}
else {
<option>$option</option>}};
</select></td>
<?php
$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");
$row = $db->sql_fetchrow($result);
// options defined here
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
?>
<center><font class="title"><?php echo _CHANGE_MY_INFORMATION; ?></font></center><br />
<center> All fields must be filled </center>
<form name="EditMyInfoForm" method="POST" action="users.php" enctype="multipart/form-data">
<table align="center" border="0" width="720" id="table1" cellpadding="2" bordercolor="#C0C0C0">
<tr>
<td align="right">Telephone :</td>
<td>
<input type="text" name="telephone" size="27" value="<?php echo htmlentities($row['telephone']); ?>" /> Inc. dialing codes
</td>
</tr>
<tr>
<td align="right">Type of property required :</td>
<td>Select from list:
<select name="req_type">
<?php foreach($options as $option): ?>
<option value="<?php echo $option; ?>" <?php if($row['req_type'] == $option) echo 'selected="selected"'; ?>><?php echo $option; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
...
oops.. a little too carried away.
Thanks everyone for all your help. Although I couldn't get any one answer to work it gave me ideas and I have accomplished the job! I ended up going about it a long-winded way but hey-ho if it's not broke don't fix it.
if ($row[$req_type]=='House'){
$sel_req_type1='selected';
}
else if ($row[$req_type]=='Bugalow'){
$sel_req_type2='selected';
}
etc. etc. etc.
And in the table:
<option $sel_req_type1>House</option>
<option $sel_req_type2>Bulgalow</option>
etc. etc. etc.
I still have other issues to overcome i.e. htmlentities for the text fields and quoting the array elements (ie $row['req_type'] instead of $row[req_type]. But I'll ask that on another question. Thanks again
Here is another way of going about it.
<?php
$query = "SELECT * FROM ".$prefix."_users WHERE userid='$userid'";
$result = mysql_query($query); ?>
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
<select name="venue">
<?php
while($row = mysql_fetch_array($result)) {
print '<option value="'.$option.'"';
if($row['req_type'] == $option) {
print 'selected';
}
print '>'.$option.'</option>';
}
?>
</select>

Categories