I'm trying to make an admin page and allow only users with role 2 for some reason its not giving me the information I expected.
<?php
session_start();
require_once('includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: login.php');
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;
if($user['role'] == '2'){
echo "Hello $user['name']";
}
else {
header('location: index.php');
}
?>
When I do vardump($user) its giving me the output 1.
When I echo the $_SESSION['id'] it is giving me the right id (the session id is the same as user id).
Right now what you have done is, you just executed the query and had the resultset stored in $user. You need to fetch the results from the Result Set.
$user = mysqli_fetch_array($user);
Now it should work as expected.
Update: You should also handle the following:
Sanitization: Make sure you use ' for the values and ` for the column names. Also use mysqli_real_escape_string() for escaping some obvious stuff.
Validation: That's the next most important. Try checking if the resultset has any rows returned. You can do by using mysqli_num_rows($user) > 0 or precisely in your case, mysqli_num_rows($user) == 1.
Variables: Here in the example, I have used the same $user for the Result Set as well as the row. It is always better to have two separate variables, say, $userRes (for result set) and $userData (for the fetched data).
Hope this should answer your question.
After a successful select query mysqli_query() will return an mysqli_result object. You have to itterate over that to get your results. For example:
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;
if(user ){
// Cycle through results
while ($row = user ->fetch_object()){
$users[] = $row;
}
$user->close();
}
You're not fetching the results... If you check the manual, and look for the return value of mysqli_query(), you'll find:
Returns FALSE on failure. 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
So go ahead and fetch it:
//$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false; // I'm unfamiliar with this || false stuff.
$result = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']);
$user = mysqli_fetch_array($result);
It's also a good idea to sanitize your input (in order to prevent SQL-injection) and to check whether there are any results with mysqli_num_rows().
Related
My connection & sql queries have already been tested and they work. I am just trying to print one column of data into my browser for output so I can test the rest of the database. I am just trying to print one row and when I run the code, nothing shows up in the browser as output. The database column name is "type" and there is a "1" in there for the user I am logging in with. The login works but I am trying to read the integer in the database in order to direct it to a specific profile. I can't get anything to printout from my table into the browser.
$role = "SELECT type FROM fp.user WHERE usname ='$username' AND pswd = '$password'";
$access = mysqli_query($link, $role);
$row = mysqli_fetch_row($access);
echo $row['type'];
There may be a problem with your query. You should check to see if $access is first false (Which would indicate a query failure), and echo out the error associated with the query.
$role = "SELECT type FROM fp.user WHERE usname ='$username' AND pswd = '$password'";
$access = mysqli_query($link, $role);
if ( !$access )
{
echo 'There was a problem running this query: ', mysqli_error($link);
exit;
}
$row = mysqli_fetch_row($access);
Also, according to the docs:
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.
Check to make sure the user/password combo in the database is correct. Another issue could be that no user exists for that $username/$password combo.
I'm fairly new to php and have a question. I have an HTML form that has a SELECT auto-populated from an SQL table via PHP. The dropdown is populated with all users with the level of "Admin" or "Moderator". This is the code to connect:
$con = mysqli_connect("localhost", "root", "", "database") or die("Error " . mysqli_error($con));
And the dropdown itself:
<form name="htmlform" role="form" method="POST" action="result.php">
<select id="user" name="user" required>
<option selected disabled>User</option>
<?php
$result = $con->query("SELECT username FROM users WHERE level='admin' OR level='moderator' ORDER BY level");
while ($row = $result->fetch_assoc())
{
$username = $row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
?>
</select>
This works perfectly. The problem I'm having is that I am trying to reuse the data from this form (specifically $_POST['user']) on another page to auto-populate another field in a form. I need to see if the 'user' is an Admin or not and return $other as either "y" (Admin) or "n" (not Admin), which will then be added to another table.
Here's my code on the 2nd page (result.php):
$user=$_POST['user'];
$query = $con->query("SELECT level FROM users WHERE username=$user");
$variable=mysqli_query($con, $query);
if ($variable=="admin") {
$other = 'y';
} else {
$other='n';
}
At the moment all output for $other is "n" regardless of anything. So, obviously I have an error in the code, but don't know enough php to be able to spot or correct it.
Please could someone help point out the error?
text values have to be wrapped in quotes in a query
$query = $con->query("SELECT level FROM users WHERE username='$user'");
You also look like you were trying to execute that same query twice here:
$query = $con->query("SELECT level FROM users WHERE username=$user");
$variable=mysqli_query($con, $query);
this is not legal usage.
Also when you run this line
$variable=mysqli_query($con, $query);
$variable is not a value, but a mysqli_result object that will contain a resultset or FALSE if the query failed, but definitely not the content if the id column in your query.
However if you are using data got from the user, it is not safe to assume thay are not attempting a SQL Injection Attack
So you should use Prepared and Parameterised queries like this
$stmt = $con->prepare("SELECT level FROM users WHERE username=?");
$stmt->bind_param('s', $_POST['user']);
$stmt->execute();
I think you shoud start by reading the PHP manual for the mysqli extension
(Without getting into issues about best practices ...)
Your second code snippet's usage of the return value from mysql_query() is problematic.
The PHP Manual states:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Hence, $variable is a PHP resource and cannot ever be equal to a string.
Use tripple === equals when possible. You still need to "fetch" the record from the result resource (you managed to to do this in the first code snippet).
Generally speaking ...
$result = mysqli_query($con, $query);
$record = result->fetch_assoc();
//if(result->fetch_assoc()['level'] === 'admin') in PHP 5.4 and up.
//or
//if(mysqli_query($con, $query)->fetch_assoc()['level'] === 'admin') in PHP 5.4 and up.
if($record['level'] === 'admin')
{
}
else
{
}
Cheers!
According with mysqli_query doc:
Returns FALSE on failure. 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.
So don't expect to get database value directly from call, you are comparing a mysql_result object (you made a SELECT) versus a constant string. You need to get your data from mysql_result object and then you can make comparison.
This code should work for you:
$user = $_POST['user'];
$sql = "SELECT level FROM users WHERE username={$user}";
$variable = mysqli_query($con, $sql)->fetch_row();
if ($variable[0]=="admin") {
$other = 'y';
} else {
$other='n';
}
Ok so the problem is... i m a newbie and i m trying to understand what is happening.Im sending through an html form this data(name,email) using POST in a database.I understand the logic behind it all but what basically happens is that everytime I enter a name,any name,it echoes the else statement:"there is already a user with that name". and it sends back the first name in the database.when there s nothing,it sends nothing. So here's the chunk:
$query= "SELECT* from users where username='".$_POST['name']."'";
$result = mysql_query($query);
if (!$result){
$query = "INSERT into users (username, email, password) values
('".$_POST["name"]."', '".$_POST["email"]."',
'".$passwords[0]."')";
$result = mysql_query($query);
if ($result){
echo "It's entered!";
} else {
echo "There's been a problem: ".mysql_error();
}
} else {
echo "There is already a user with that name: <br />";
$sqlAll = "select * from users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
You may want to check mysql_num_rows() rather than checking for !$result, I think that if the query is sucsesfull you'll get a resource back, even though it contains zero rows.
You may also want to read up on: http://php.net/manual/en/security.database.sql-injection.php
ESCAPEEEEE
Firstly, you need to learn about escaping.
Have you never heard of little Johnny DROP TABLES?
http://xkcd.com/327/
Serious business
The reason why it always returns, is because the response in $result is actually a resource data type. And that will always when cast as a boolean be true. (And since your query shouldn't fail).
You should fetch the result. For example. (This isn't the best way, but it is a way to do it).
mysql_fetch_row(result)
Per the manual, mysql_query will return false when there is an error - "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
see no violation in your code. first mysql_query executes with no error and always returns true. try to test returned rows count like this:
if (mysql_num_rows($result) == 0) {
//insert record
} else {
// show alreay exists
}
First of all, you are testing for:
if (!$result)
which will evaluate to true only if the query fails.
You should also sanitize all input before using it in SQL queries.
I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.
The query is like this:
$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);
The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.
I know I could probably just do this query:
"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
//...
}
But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.
You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?
$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];
Is that what you are looking for?
Use pg_fetch_result:
$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);
But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.
I tried what seemed like the most intuitive approach
$query = "SELECT * FROM members
WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
if ($result)
{ ...
but that didn't work because mysql_query returns a true value even if 0 rows are returned.
I basically want to perform the logic in that condition only if a row is returned.
Use mysql_num_rows:
if (mysql_num_rows($result)) {
//do stuff
}
If you're checking for exactly one row:
if ($Row = mysql_fetch_object($result)) {
// do stuff
}
You can use mysql_fetch_array() instead, or whatever, but the principle is the same. If you're doing expecting 1 or more rows:
while ($Row = mysql_fetch_object($result)) {
// do stuff
}
This will loop until it runs out of rows, at which point it'll continue on.
mysql_num_rows
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
If none match, then zero will be the return value and effectively FALSE.
$result = mysql_query($query);
if(mysql_num_rows($result))
{ //-- non-empty rows found fitting your SQL query
while($row = mysql_fetch_array($result))
{//-- loop through the rows,
//-- each time resetting an array, $row, with the values
}
}
Which is all good and fine if you only pull out of the database. If you change or delete rows from the database and want to know how many were affected by it...
To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$result = mysql_query($query);
if(mysql_affected_rows())
{ //-- database has been changed
}
//-- if you want to know how many rows were affected:
echo 'Rows affected by last SQL query: ' .mysql_affected_rows();
mysql_query() will only return FALSE if the query failed. It will return TRUE even if you have no rows, but successfully queried the database.
$sql = "SELECT columns FROM table";
$results = mysql_query($sql, $conn);
$nResults = mysql_num_rows($results);
if ($nResults > 0) {
//Hurray
} else {
//Nah
}
This should work.
I used the following:
if ($result != 0 && mysql_num_rows($result)) {
If a query returns nothing it will be a boolean result and it's value will be 0.
So you check if it's a zero or not, and if not, we know there's something in there..
HOWEVER, sometimes it'll return a 1, even when there is nothing in there, so you THEN check if there are any rows and if there is a full row in there, you know for sure that a result has been returned.
What about this way:
$query = "SELECT * FROM members WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
$result = mysql_fetch_array($result);
//you could then define your variables like:
$username = $result['username'];
$password = $result['password'];
if ($result)
{ ...
I like it because I get to be very specific with the results returned from the mysql_query.
-Ivan Novak
well...
by definiton mysql_query:
mysql_query() returns a resource on
success, or FALSE on error.
but what you need to understand is if this function returns a value different than FALSE the query has been ran without problems (correct syntax, connect still alive,etc.) but this doesnt mean you query is returning some row.
for example
<?php
$result = mysql_query("SELECT * FROM a WHERE 1 = 0");
print_r($result); // => true
?>
so if you get FALSE you can use
mysql_errorno() and mysql_error() to know what happened..
following with this:
you can use mysql_fetch_array() to get row by row from a query
$result = mysql_query(...);
if(false !== $result)
{
//...
}