SQL Query and PHP checking if a user is an Admin - php

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

Related

mysql query returning false even when values DO exist in table? Trying to find if not in table?

Ok, so I am building on my first question here https://stackoverflow.com/questions/38102208/php-mysql-how-to-only-echo-links-with-search-bar-post-that-arent-already-echo
trying to only echo only usernames of people whose id is NOT in a mysql table called conversation along with a set id (the person who is signed in).
I echo the people who their id is user_two in a table conversation REGARDLESS if a search bar is posted here:
//$num = mysqli_query($con, "SELECT * FROM `pm_messages` WHERE user_from=".$account['id']."");
$numCon = mysqli_query($con, "SELECT * FROM `conversation` WHERE user_one=".$account['id']."");
$numrows = mysqli_num_rows($numCon);
while ($u = mysqli_fetch_assoc($numCon)) {
//get other users usernames to echo link
$getUserTwo = mysqli_query($con, "SELECT * FROM `accounts` WHERE id=".$u['user_two']."");
$s = mysqli_fetch_assoc($getUserTwo);
//echo $s['username'];
echo "<a href='message.php?id={$s['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/>{$s['username']} </li></a>";
}
This works well, meaning only individuals who a conversation has been started with (a row exists for this user and the one signed in conversation table) are echoed in a link.
Problem comes here with the search bar because it echoes all individuals even if a conversation has been started, resulting in duplicates:
(notice the 2 khusteds)
This does not make sense because here I select the row in conversation where user_one is the signed in user and user_two is the second user and only echo a link if the result is FALSE (meaning there's no conversation):
if (isset($_POST['searchbarpm'])) {
//$sess->getUsers();
$dbh = mysqli_connect("localhost","username","password","sqlserver");
$query = $_POST['searchbarpm'];
$q = mysqli_query($dbh, "SELECT * FROM sqlserver.accounts WHERE username LIKE '%".$query."%'");
//display all the results
while($row = mysqli_fetch_assoc($q)) {
$checkConvo = mysql_query("SELECT 'id' FROM sqlserver.conversation WHERE user_one=".$user_id." AND user_two=".$row['id']."");
//only output users they dont have convo going with because theyre already printed!!!
if ($checkConvo==false && $row['id']!= $user_id) {
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
}
}
But it looks like the query is always false because again, all users are echoed. Why is this happening? How can I only echo users not in conversation table with the signed in user (user_one)?
EDIT:
new code (sorry for screenshot); :
#IanH -
$con = mysqli_connect("localhost","username","password","sqlserver");
//$num = mysqli_query($con, "SELECT * FROM `pm_messages` WHERE user_from=".$account['id']."");
$numCon = mysqli_query($con, "SELECT * FROM `conversation` WHERE user_one=".$account['id']."");
$numrows = mysqli_num_rows($numCon);
while ($u = mysqli_fetch_assoc($numCon))
{
//get other users usernames to echo link
$getUserTwo = mysqli_query($con, "SELECT * FROM `accounts` WHERE id=".$u['user_two']."");
$s = mysqli_fetch_assoc($getUserTwo);
//echo $s['username'];
if(isset($_POST['searchbarpm'])){
//$sess->getUsers();
$dbh = mysqli_connect("localhost","username","password","sqlserver");
$query = $_POST['searchbarpm'];
$q = mysqli_query($dbh, "SELECT * FROM sqlserver.accounts WHERE username LIKE '%".$query."%'");
//display all the results
while($row = mysqli_fetch_assoc($q)){
if($row['id']!= $user_id && $row['id']!=$s['id']) { //only output users they dont have convo going with because theyre already printed!!!
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
}
}
else {
echo "<a href='message.php?id={$s['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/>{$s['username']} </li></a>";
}
}//
First of all, you need change the mysql_query( ... ) on line 9 of your second posted code block to mysqli_query( ... ), for API consistency and compatibility.
Also, you could have duplicate results if you are allowing multiple entries in the conversation table where users A and B can be entered as user1 = A, user2 = B in one conversation, and user1 = B, user2 = A in a different conversation.
Lastly, as Jay Blanchard said, you should use prepared statements to avoid SQL injection.

how to get a particular field from a database via php

I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);

Database not updating row

Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that

Displaying the users information from the database

I am trying to created a way to call information from the database for a user to view. Such as they log in and it has their registered information viewed. I have this
session_start();
if($_SESSION['id'])
$result = mysql_query("SELECT * FROM User WHERE `id` = $_SESSION[id]")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo '<b>First Name:</b>' .$row['fname'];
echo '<br>';
echo '<b>Last Name:</b>' .$row['lname'];
}
but nothing shows up. My database name is megan, table is user, fields i want displayed are first name (fname) and last name (lname).
Can someone point me in the right direction. Thank you in advance!
Bad array indexing.
$result = mysql_query("SELECT * FROM User WHERE `id` = " . $_SESSION['id'])
You should turn on PHP error displaying.
First change this,
if(isset($_SESSION['id']))
because you have to check if the session isset correctly then do the query,
then the sql change to this,
$result = mysql_query("SELECT * FROM User WHERE `id` = ".$_SESSION['id'])

Drupal: PHP field for allowed values

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;
}

Categories