I'm working in Drupal 6 with CCK. Under each text field there is a PHP section where you can run some PHP code to get allowed values. I'm running into trouble using an "if" statement to change the allowed values based on user type
So to start, I do a query to determine current users user type. -1 is default user, which is employees and user type id "1", is for site users. What I want is to restrict the site user to only the allowed values they need to see, while allowing employees to edit that value when on the node edit screen with all choices.
The first part of the if statement works. However, the "else" part doesn't work. Is this field set up to deal with control structures?
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
if($res1 == '1'){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res2 = db_query($sql2);
while($row2 = db_fetch_array($res2)){
$rows2[] = $row2['title'];
}
$rows2 = drupal_map_assoc($rows2);
return $rows2;
}
The choices are type=accounts in nodes, however, when a user is created one of the choices is selected and stored in the user table, under a column I created named "account"
If by 'the "else part does not work' you mean that it is never executed, even if user_type_id does not equal 1, it might be the missing db_fetch_array() on $res1. You're comparing your result object directly to the string '1', not the field value.
Here is the working code for this. There may have been a quicker/shorter way to do this.
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
while($type = db_fetch_array($res1)){
$types[] = $type['user_type_id'];
}
$resType = $types[0];
if($resType == "1"){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res = db_query($sql2);
while($row2 = db_fetch_array($res)){
$rows2[] = $row2['title'];
}
return $rows2;
}
Related
I am trying to create a Secret Santa system using a PHP page and a MySQL database to store the details so if someone forgets their match they can re-request it.
Step 1: I created a random number generator based on the number of people in the list in the database.
Count Function:
$maxSQL = "SELECT COUNT(id) as total FROM secretsanta";
$maxRS = mysqli_query($conn, $maxSQL);
$maxQuery = mysqli_fetch_array($maxRS);
$maxpersons = $maxQuery['total'];
Then the Random Number Generator:
$assigned = rand(1,$maxpersons);
Step 2: Test if the random number matches the persons own id and regenerate a new number if true.
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id);
Step 3: Write the paired id to the persons database record.
$assignSQL = "UPDATE secretsanta SET assigned = '".$assigned."' WHERE secretsanta.id = ".$id;
if (mysqli_query($conn, $assignSQL)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
The Problem: Now I need to check that other people aren't assigned to that person or otherwise some could miss out and others would get more than others.
I tried to implement a function that contained a query to test each record to see if that number already existed and was hoping to add it as a condition to perhaps a while or do while statement?
if (!function_exists('checkRandom')){
function checkRandom($funcid){
$Check_SQL = "SELECT assigned FROM secretsanta ORDER BY id ASC";
$Check_RES = mysqli_query($conn, $Check_SQL);
if (Check_RES) {
while ($CheckArray = mysqli_fetch_array($Check_RES, MYSQLI_ASSOC)) {
$CheckAsgn = $CheckArray['assigned'];
if ($funcid==$CheckAsgn) {return true;}else{return false;}
}
}
}
}
Then implement it into the do while statement like this:
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id||checkRandom($assigned));
No luck so far...HELP!.. please :)
P.S. I know there are websites that already do this, I just don't trust them to give out mine and family email address' if I can make my own private version myself.
Using your method, the first few assignments will be done with no problem, but imagine the last unassigned entry and how many times it will try a random number only to find the person with that id is already assigned..
I'm gonna give you another approach to your problem: for each user that you want to assign a santa to, make a new SELECT statement with a WHERE clause that lets you select only those users that are not assigned yet.
check out my code and see if that helps you. I just typed this and didnt test it so there could be some mistakes.
// load all unassigned users into an array
$unassignedUsers = [];
$query = "SELECT id, assigned FROM secretsanta WHERE assigned is NULL";
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedUsers[] = $row;
}
if(count($unassignedUsers) == 1){
echo 'There is only 1 unassigned user. Therefore he cannot be matched';
} else {
// for loop for each user in DB that is not assigned yet
//for ($i = 1;$i <= count($unassignedUsers); $i++){
$i = 0;
foreach($unassignedUsers as $user)
// if its the second-to-last iterations of the for-loop, check for legality of the last one
if(count($unassignedUsers) - $i == 1){
$lastUserID = $unassignedUsers[count($unassignedUsers)-1]['id'];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id = ".$lastUserID;
$res = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($res);
if ($rowcount){
// last user is still unassigned
$query = "UPDATE secretsanta SET assigned = '".$lastUserID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
} else {
// select all unassigned users
$unassignedIDs = [];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id <> ".$user['id'];
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedIDs[] = $row['id'];
}
// get a random id from $unassignedIDs
$randomIndex = rand(0, count($unassignedIDs)-1);
$randomID = $unassignedIDs[$randomIndex];
// assign $randomID to user
$query = "UPDATE secretsanta SET assigned = '".$randomID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
$i++;
}
}
last edit: refactored whole code so it is able to be run multiple times and only assigns new users who are not assigned yet.
Step 1 is dependent on have a contiguous set of ids for the people. Think what happens if '3' leaves the company and it hires 6 to replace them....1,2,4,5,6 ($maxpersons=5)
"Now I need to check" - no you are still trying to solve the problem by guessing then seeing if your guess worked. Use an algorithm which is always going to return a correct result. The method below requires the addition of a temporary field 'sequence' of type float.
mysqli_query($conn,"UPDATE secretsanta SET sequence=RAND()");
$first=false;
$prev=false;
$all=mysqli_query($conn, "SELECT * FROM secretsanta ORDER BY sequence, id");
while ($r=mysqli_fetch_assoc($all)) {
if (false===$first) {
$first=$r['id'];
} else {
save_pair($prev, $r['id']);
}
$prev=$r['id'];
}
save_pair($prev, $first);
(but with better error checking)
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
I have a large table and would like to search all of the fields in one go but some of the fields are dates so the search I have created falls over when it hits those fields.
Is there a way to exclude certain types of fields when using this type of search?
$table = 'accounts';
$condition = 'tracey';
$sql = "SHOW COLUMNS FROM accounts";
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0)
{
$i=0;
while ($row = mysqli_fetch_array($result))
{
if($i==0)
{
$q="select * from ".$table." where ".$row[0]." LIKE %".$condition."%";
}
else
{
$q.=" or ".$row[0]."="." LIKE %".$condition."%";
}
$i++;
}
}
$sql = $q;
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
$row = mysqli_fetch_array($result);
$answer = $row['phone_office'];
echo '<br><br>answer = '.$answer;
Or perhaps someone can suggest a better way of searching all of the fields in a table in one go?
To exclude certain types of fields You need to change the query SHOW COLUMNS FROM accounts with this one:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE (table_name=".$table.")AND(NOT(DATA_TYPE IN ('field_type_1','field_type_2',...)));
Where field_type_i is the name of an excluded type (for example 'timestamp')
I'm trying to set up a simple comment system and I want to create the correlation between the comment and the page landed.... so when a user arrives at blog.php?id=3 they would be presented the correct comments.
What I'm doing is creating the comments table with a pageid column. The pageid column will be filled when a user posts to the page. Maybe a hidden form field? How do I make this correlation within my MYSQLI
This is what I was thinking...
<?php
include_once("includes/check_login_status.php");
?>
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "includes/db_conx.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "UPDATE content SET views=views+1 WHERE ID=$id";
$update = mysqli_query($db_conx,$sql);
$sql = "SELECT * FROM content WHERE id=$id LIMIT 1";
$result = mysqli_query($db_conx,$sql);
$productCount = mysqli_num_rows($result);
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($result)){
$article_title = $row["article_title"];
$category = $row["category"];
$readmore = $row["readmore"];
$author = $row["author"];
$date_added = $row["date_added"];
$article_content = $row["content"];
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<?php
include_once "includes/db_conx.php";
$sql = "SELECT * FROM comment WHERE pageid ="$id"ORDER BY id DESC";
$sql_comments = mysqli_query($db_conx,$sql);
while($row = mysqli_fetch_array($sql_comments)){
$name = $row["name"];
$comment = $row["comment"];
$commentlist .= 'name : '.$name.'<br />comment : '.$comment.'<hr>';
}
//////////////
?>
Is the lower half in scope of the get variable? So that I can determine what page we're on? Can this type of variable be passed thorugh a variable in the comment form?
The 3rd sql statement contains an error:
$sql = "SELECT * FROM comment WHERE pageid ="$id"ORDER BY id DESC";
to
$sql = "SELECT * FROM comment WHERE pageid =".$id."ORDER BY id DESC";
You might also want to change the pre_replace statement to intval:
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
to
$id = intval($_GET['id']);
The reason being if $_GET['id'] = 'ABC123' then preg_replace will return 123 whereas the intval will return 0.
Alright let me explain myself here:
I am making an online text based game. I have a page where 3 things can happen:
They can create a position
Can edit a position
Can delete a position
So far I have creating a position working. I moved on deleting a position next. All was good and I got no errors, no warnings, etc.. And when I ran it, it came back to the screen it was supposed to after the script to delete the position ran. It is only supposed to come here after the query runs.
Well nothing happened and after 3 hours of trying crap I'm coming to you guys b/c I'm on my last leg. I still have no critical errors, nothing is making it fail: Here is my code.
<?php
//In the include file is the connection to the db
include("library/new_library.php");
//Below is the session id, gets their position id from the DB, than grabs whether or not they can edit the company
$user_id = $_SESSION['user_id'];
$sql = "SELECT ID, PositionID FROM users WHERE ID = '$user_id'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
$position = $row['PositionID'];
}
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
$editCompany = $row['Edit_Company'];
}
//Next I check for position edit and if they try to put in the position id of a position the company does not control it gives them a "nice" message.
$company = $_SESSION['company'];
if($_GET['pidedit']){
$position = $_GET['pidedit'];
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
if($row['CompanyID'] != $company)
{
$warning = "<div class='warning'>You are trying to edit a position that does not belong to your company. DO NOT TRY TO CHEAT THE SYSTEM!</div>";
}
else
{
$positionArray[] = array(ID => $row['PositionID'], name => $row['Name'], hire => $row['Hire'], fire => $row['Fire'], bid => $row['Contract'], edit => $row['Edit_Company'], finances => $row['Finances']);
}
}
}
//Here I check for $_GET delete
elseif($_GET['piddelete'])
{
$position = $_GET['piddelete'];
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
if($row['CompanyID'] != $company)
{
$warning = "<div class='warning'>You are trying to delete a position that does not belong to your company. DO NOT TRY TO CHEAT THE SYSTEM!</div>";
}
}
}
else
{
$sql = "SELECT * FROM tblCPositions WHERE CompanyID = '$company'";
$query = mysql_query($sql);
$number = mysql_num_rows($query);
$numberLeft = 12 - $number;
while($row = mysql_fetch_assoc($query))
{
$positionArray[] = array(ID => $row['PositionID'], name => $row['Name'], hire => $row['Hire'], fire => $row['Fire'], bid => $row['Contract'], edit => $row['Edit_Company'], finances => $row['Finances']);
}
}
//
if($_POST['submitNewPosition'])
{
$name = $_POST['positionName'];
$hire = $_POST['hire'];
$fire = $_POST['fire'];
$bid = $_POST['bid'];
$edit = $_POST['edit'];
$finances = $_POST['finances'];
$cid = $_SESSION['company'];
$sql = "INSERT INTO tblCPositions(CompanyID, Name, Hire, Fire, Contract, Edit_Company, Finances) VALUES ('$cid','$name','$hire','$fire','$bid','$edit','$finances')";
$query = mysql_query($sql);
if($query)
{
header("location: view_company.php?newp=success");
}
}
//Haven't finished this section yet
if($_POST['submitEditPosition'])
{
$name = $_POST['positionName'];
$fire = $_POST['hire'];
$fire = $_POST['fire'];
$bid = $_POST['bid'];
$edit = $_POST['edit'];
$finances = $_POST['finances'];
}
//This this is my problem area, this is where it says its running the query but its not.
if(isset($_POST['deletePosition']))
{
$deleteID = $_GET['piddelete'];
$deleteSql = "DELETE FROM tblCPositions WHERE PositionID = '$deleteID'";
$deleteQuery = mysql_query($deleteSql);
if($deleteQuery)
{
header("location: view_company.php?delete=success");
}
if(!$deleteQuery)
{
header("location: view_company.php?delete=failure");
}
}
UPDATE -
Ok so I got it working the problem was something I forgot, this form was just meant to be a "yes or no form" so I was doing post only to post the submit button, nothing else was on the form. What I had forgot was on the action="file.php" (what I had) I had forgotten to pass on the get variable so once I changed it to action="file.php?piddelete=12" it worked.
Thanks for everyones help I really appreciate it.
10 to 1 your variable $_GET['piddelete']; is empty. What do you get when you do this:
var_dump($_GET['piddelete']);
Disable the header redirect so that you can see the output.
edit
Or, as Nick pointed out, you can add die() statements to your queries:
$deleteQuery = mysql_query($deleteSql) or die(mysql_error());
If your query still runs, and the script doesn't die, and the position is still not deleted, you should check the query, it may be deleting 0 rows successfully. try killing at die($deleteSql); and run the query through MySQL's console.
/edit
Also, I'm compelled to introduce you to my good friend SQL injection attack. You should filter all data contained in the $_POST and $_GET superglobals before handing them over to the MySQL server. use mysql_real_escape_string().
Try to grok this:
whatever.com/your_url.php?pidedit=x'%3B%20DROP%20TABLE%20tblCPositions%3B%20--
If I were to execute that query string on your application, your tblCPositions table would be dropped.