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';
}
Related
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().
I'm fairly new to PDO in PHP and I'm trying to make a simple log-in form. I need to be able to fetch the data and can't seem to make that work with fetchColumn(), which I need to check if the user and password match.
$query = "SELECT * FROM administrator
WHERE user = :user
AND pass = :pass";
$res = $db->prepare($query);
$params = array("user" => $username, "pass" => $password);
$res->execute($params);
$num_rows = $res->fetchColumn(1);
if ($num_rows) {
$_SESSION['user'] = $num_rows['user'];
header('Location: .');
exit();
} else {
echo "Failure";
}
if (isset($_SESSION['user'])): ?>
<p>Hello, <?= $_SESSION['user']; ?>! This is admin content.</p>
Logout
<?php endif; ?>
When using this code, using the username adminuser, the output is:
"Hello, a! This is admin content."
when it should be:
"Hello, adminuser! This is admin content."
So, how does one fetch the data when the fetchColumn() function has already been executed?
I think you are misunderstanding what fetchColumn does. It will simply return a single value.
You have two options:
Change $num_rows['user'] to just $num_rows (strange naming convention there by the way). Here I'm assuming that you are actually targeting the correct column. See note below about using *
or
Use $res->fetch(PDO::FETCH_ASSOC) instead of fetchColumn, which will return an associative array containing all values in the row (which you can then continue to access with $num_rows['user']
If you go for option 1, I strongly recommend that you define which columns should be returned in your SELECT statement. Using fetchColumn with SELECT * FROM is very fragile, because the order of columns may change if new fields are added. To be honest, it's rare that you should use * anyway, so I'd probably specify the columns in any case.
I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.
I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.
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.