Else does not work in selection of $row - php

I want to check if user has set his gender. If not, it will display the 1st echo. If yes, it'll display the echo of his gender.
Problem is that the page shows only the 1st echo even though there IS set gender in database... I really don't know why it is not working...
My code:
<?php
$username = $_SESSION['username'];
$sql = "
SELECT gender FROM members WHERE username = ?";
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()){
if($row['gender'] == ""){
echo "You have not selected your gender yet."; // This is the 1st echo and this is the only one that is displayed
} else {
echo "You selected that you are {$row['gender']}."; // This is not displayed no matter what...
}
}
?>
What I have wrong?

I'm not a php expert, but I think this code would work better for you as I don't think that $row contains anything (I don't see where it's being set anywhere, and according to the docs, bind_result doesn't work that way anyway):
$username = $_SESSION['username'];
$stmt = $mysqli->prepare("SELECT gender FROM members WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($gender);
while ($stmt->fetch()){
if(empty($gender)){
echo "You have not selected your gender yet.";
} else {
echo "You selected that you are " . $gender;
}
}
EDIT
Used empty() instead of = "" in case nulls are returned for $gender.
EDIT 2
I noticed that you don't ever use $sql. I updated the code for the proper syntax, assuming that your database connection is called $mysqli.
Might want to check the docs here: https://php.net/manual/en/mysqli-stmt.bind-result.php

Related

How do I pull the value of something from an SQL database [PHP]?

I have a column in my database called "Admin" that I want to be able to check the value of (whether it's 1 or NULL). And if it's 1 I want it to do something.
How do I write up the query and validate that the entry is = to 1?
Right now I just have the following set up
<?php
include 'db_connect.php';
if ($_SESSION['username'] == "admin")
{
echo ' Admin Panel ';
echo '';
}
else
{
echo "Please log in as admin (user: admin password: admin) to use the admin control panel";
}
?>
Meaning if the user name is admin it will continue running the loop but I want any user to be able to tick a box on registering and have administrative rights. (I know this is destructive but it's just for a school project and a proof of concept)
Thanks!
EDIT:
I tried the following
<?php
include 'db_connect.php';
$query = "SELECT * from member WHERE Admin = '1'";
$result = mysqli_query($connection, $query);
if ($_SESSION['username'] == "admin")
{
echo ' Admin Panel ';
echo '';
echo $result;
}
else
{
echo "Please log in as admin (user: admin password: admin) to use the
admin control panel"; } ?>
And got the following error after trying to echo it
You just need to know about the return type of mysqli_query(); which return a mixed type variable means it could be an array or binary (True or False) sometimes depends on the query type. The following result may be output as false for error or array for data return so use condition for checking the $result simply by:
if($result) // or if(count($result) > 0 && $result)
If data exists then use a loop for per row data as per your need and for print complete $result you need to use a var_dump() or printr() instead of echo like :
var_dump($result);
For details about mysqli_query() follow this link: http://php.net/manual/en/function.mysql-query.php
Please, for the right way to connect and get data from DataBase read this manual: http://php.net/manual/en/pdo.connections.php
In the most cases using PDO over mysql or mysqli drivers are much more useful.
u are trying something like this maybe..
function admin_check( $email, $password ){
$db = connect();
if( $db ){
$admin=1;
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email and password = :password and admin =:admin ");
$stmt->bindParam(":email", $email);
$stmt->bindParam(":password", $password);
$stmt->bindParam(":admin", $admin);
$stmt->execute();
$row = $stmt->fetchAll();
$resultCount = count($row);
return $resultCount;
}
}

simple profile page for a job site

I've done a login and registration for my site and it works fine.
Now I just want to make a simple profile page where the user can see all their details.
I'm only able to get back the username, so I'm unsure how to get the rest of their details.
Here is the code for registering and logging in:
function selectUser($conn, $username, $password)
{
$query = "SELECT password FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
if (md5($password) == $row->password)
{
$_SESSION['username'] = $username;
//$_SESSION['password'] = $password; DO NOT DO THIS
echo "Welcome, you are now logged in as " . $username;
return true;
}
return false;
} else {
//echo "Your details were not found";
return false;
}
}
function selectNew($conn, $name, $username, $password, $contact, $occupation, $role, $picture)
{
$query = "INSERT INTO login VALUES (NULL, :name, :username, :password, :contactNumber, :occupation, :role, :pic)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $password);
$stmt->bindValue(':contactNumber', $contact);
$stmt->bindValue(':occupation', $occupation);
$stmt->bindValue(':role', $role);
$stmt->bindValue(':pic', $picture);
$affected_rows = $stmt->execute();
if ($affected_rows == 1)
{
return true;
} else {
return false;
}
}
Don't worry, the password has been hashed.
heres what I've tried:
function selectUser($conn, $username, $password)
{
$query = "SELECT * FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch();
echo $row['occupation'];
echo $row['role'];
}
2nd attempt:
if(isset($_SESSION["username"]))
{
echo "Welcome, you are now logged in as <b>".$_SESSION['username']."</b> <img class='clientView' src='images/loginIcon.png' alt='client'>"; }
else {
echo "You are currently not logged in";
}
$user = $_SESSION["username"];
$query = "SELECT * FROM login WHERE username = :username";
$term = $conn->prepare($query);
$term->bindValue(':username', $user);
$term->execute();
if ($username = $term->fetch(PDO::FETCH_OBJ))
{
echo "<li><h3>" . $user->username ." ". $user->user_ID . "</h3></li>";
}
The simple answer is to replace your query in selectUser(...) with SELECT * FROM login WHERE username = :username. Note the * after the SELECT command, which functions as a wild card and thus asks for every single column of each row it finds (instead of just the password column as you are currently asking for.
You could then, as you iterate over the returned rows, access other columns of the user via your $row variable. Just like you access the user's hashed password with $row->password, you could access $row->contactNumber.
A note about good practice:
Depending on the case, I would not recommend doing a wildcard (*) SELECT command at login. In fact, I would recommend simply hashing the password prior to the query and attempting to then qualify your query with WHERE username = :username AND password = :password (obviously, bind the hashed password to :password). Instead of asking for the password column, or wildcard columns, you could SELECT the row's unique ID.
This way, you don't even need to iterate over the returned rows at all...you only have to make sure any row returned (see num_rows) to see if the user can be successfully "logged in". You can then cache the returned row's unique ID into your session, and then do subsequent queries as necessary for other pieces of information...such as the user's role or contact number. This effectively brings the complexity of all of your query processing down from linear time to constant time...a minor, but still non-trivial, improvement for an application.
Also, as a word of warning, this login system is very simple and easily spoofed. PHP sessions provide some security, but they are not full-proof. A sniffer snagging the session cookie will allow them to log in as the user whom they sniffed it from. I would recommend looking into adding in your own session layer as well once you have the rest of your login system implemented. And absolutely use SSL.
A note about optimization:
Using a wildcard (*) in a SELECT command is actually a prime place for a speed bottleneck to occur. If you know exactly what columns you want from the database, it is best to ask for them explicitly. For example, instead of *, you could do password,occupation,role.
$_SESSION['username'] = $username;
You have user name in session right.
Just pass this value in where condition of mysql .and get the entire record from login table .just show where ever you want to show.
You can change your SELECT statement to return the other values you want to store in your $_SESSION variables and then access them each with $row->{variable}
Just make sure you populate the $_SESSION after you do your password check
Not dissimilar to your existing code - use the session variable you set when the user logs in
$username=!empty( $_SESSION['username'] ) ? $_SESSION['username'] : false;
$sql='select * from `login` where `username`=:username;';
$stmt=$conn->prepare( $sql );
if( $stmt && $username ){
$stmt->bindValue(':username',$username);
$result=$stmt->execute();
if( $result ){
$rs=$stmt->fetchAll( PDO::FETCH_OBJ );
/* display results from $rs */
/*
There should most likely only be one record!!
*/
$row=$rs[0];
foreach( $row as $column => $value )echo $column.' '.$value;
}
}

php check username + need variable case insensitive to register in database

I have a file register.php for my site.
$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_object()) {
if(empty($row->username)) {
echo "different username. IS OK !!";
} else {
echo "<font color='red'>*</font>".$username."<font color='red'> : this username already exist in DB!!</font><br />";
}
}
Here I compare the ($username from form) with ($row->username from DB)
$row->username exist only if $username is already register. So, if this exist, will go on ELSE part.
If $row->username doesn't exist (is empty) , because SELECT from sql will find no attribute, my code must go on IF part and display this message "different username. IS OK !!"
Why IF part doesn't work? I know sql will return 0, or NULL or "" or something like this. If I put a username which is not already registered, the code don't show the specific message. Because in this part I want to change the message with the code which permit to register new username.
empty($row->username) is not really empty if SQL can't find something to return?
Another problem is : I have a registered username "Test". MySQL is not case-sensitive, but in php, I can register another username "test". The code in php will run as a new register, but in MySQL nothing will happening because "username is unique" there. So, in "check username" from above, I need to check 2 insensitive variables ($username and $row->username). Because if in DB I have Test, and I want to register new user "test", this code will let me to do it. I want to show a error message if this happening.
All you need is to verify if no rows are returned.
$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$count = $stmt->num_rows;
if ($count == 0) {
// Username not in table
} else {
// Username already exists
]
To be sure that all your usernames are lowercase, simply convert it to lowercase before inserting it.
$username = strtolower($username);
i think you should covert your database and php variable into same case then compare it for checking.
$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT LCASE(username) AS username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', strtolower($username)); // used strtolower();
$stmt->execute();
Try this code, hope this helps...
thanks for fast answers. Honestlly, I don't know where was the issue, because now it's run perfect, without strtolower method. This is my code now:
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_object();
$stmt->close();
if(empty($row->username)) {
// if a cell from below is empty, go on ELSE part
if (!empty($username) && !empty($password) && !empty($email) && !empty($country)) {
$sql="INSERT INTO users (username, password, email, borned, gender, country, phone, register_date) VALUES (?,?,?,?,?,?,?, now())";
$stmt = $con->prepare($sql);
$stmt->bind_param('sssssss', $username, $password, $email, $borned, $gender, $country, $phone);
$stmt->execute();
$stmt->close();
header ("Location: login.php");
} else {
echo "<font color='red'>*Must complete required cells !!</font> ";
}
// end of register dates
} else {
echo "<font color='red'>*</font>".$username."<font color='red'> : this username already exist in DB!!</font><br />";
}
I have user "Test", if try to register "test" will give a message that the user is already registered.
Thanks again, the thread can be deleted is somebody consider that can not help somebody :D

Get variable from mySQLi to PHP

I'm pretty new to the whole PHP and mySQLi thing... But at the moment I am trying to make a simple project where I would like to read a specific value from a mySQL database, and then simply print (echo) it..
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == '' || $password == ''){
echo 'please fill all values';
}else{
require_once('dbConnect.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo 'All values match!';
}else{
echo 'These values do not match!';
}
mysqli_close($con);
}
}else{
echo 'error';
}
?>
I don't know if it is that obvious... but this is actually code for an app. But I mainly want to know how to get a specific value from mySQL as a PHP variable?
I will be using the username to search for the correct variables
Let's say the table looks like this :
username password money
guy 123 10
then I want to use 'guy' to find the amount of money and print it to the screen.
Sorry if this is asked and/or explained badly...
change the code like this where you are making query
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($result)){
$money= $row['money'];
}
//So because your query will return only one user if the ///username is unique so //now you can print money anywhere.

display message to let user know that the value already exist

I want to display an error message if the insert already exists.
I've made name unique in the database and if I enter the same value, it does not insert. Just as I wanted. Here is my code:
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
Now I want to echo a message to let the user know that the value he has entered is already present in the database and will not be inserted. Anyone?
I take it you are collecting $foo from a form?
what I would do is an sql query of the table register collecting the name field then when you collect the name entered in the form and its posted you can run an if condition against the name field you have already gathered using the sql statement and if there is a name = to the name they enter on the field they can receive a message and exit before the sql injection into the register table.
The simpliest way:
$res = mysql_query($query):
if ($res)
echo 'Insertion ok';
else
echo 'error: name already exists';
A better way: do first a SELECT query to see if name exists or not.
Note: you should think about moving from mysql_* to mysqli_* or PDO
Try this :
$query = "INSERT INTO register(name) VALUES('$name')";
$user = mysql_query($query):
if ($user)
echo 'User Register';
else
echo 'User Already Exist';
As per Melon's comment, you should use mysqli.
// Create your connection
$mysqli = new mysqli($host, $user, $pass, $dbname);
// Do your query
$mysqli->query("INSERT INTO register(name) VALUES('$foo')");
if($mysqli->affected_rows == 0) {
// Your chosen method of alerting the user goes here
}
\\this first part collects name information from your table.
$name="SELECT name FROM register";
$name_query = mysqli_query($db_conx, $name);
$numrows = mysqli_num_rows($name_query);
if($numrows < 1){
echo "cannot find user";
header ("location: index.php");
}
while ($row = mysqli_fetch_array($name_query, MYSQLI_ASSOC)){
$name = $row["name"];
}
\\ this part gets the name from your form
if (isset($_POST['class']) && ($_POST['class'] !='')){
$foo = $_POST['foo'];
\\this part checks to see if the 2 values are equal
if ($name == $foo){
echo "This name has already been used try again";
\\this part then adds the name if its not already in the database
}else{
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
}
}
//then all you need to do is create your form to post the foo or name so it can be collected and passed through the querys.

Categories