Displaying name (data from mySQL) on the main page using php [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Good day everyone,
Firstly let me explain a little bit about my page flow, btw Im using PHP:-
User will Login to the page using their ID (NRIC No) with pw
Then, In the Main page I would like to display their full name (Eg: Welcome, fullname) whereby the name will automatically fetched from the same table with the nric no in the database.
I was successfully do that when I used the same attribute (fullname) with the ID. However, my sv wants the login ID using NRIC No. SO, When I edit the code, there is nothing appear in the main page :(
Here are my codes in the main page;
<!-- logged in user information -->
<?php if (isset($_SESSION['namapengguna'])) : ?>
<p style="margin-left:360px;margin-right:60px">Welcome<strong><?php echo $_SESSION['namapengguna']; ?></strong></p>
<?php endif ?>
***The information(NRIC No, full name) in the database was successfully inserted.
Example of my Table in database:-
namapengguna | idpengguna | password |
Maisarah | 1234567891 | dfsdfdsf |
This is code for login:-
// LOGIN USER
if (isset($_POST['login_user'])) {
$idpengguna = mysqli_real_escape_string($db, $_POST['idpengguna']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($idpengguna)) {
array_push($errors, "Masukkan ID Pengguna");
}
if (empty($password)) {
array_push($errors, "Masukkan Kata Laluan");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE idpengguna='$idpengguna' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['idpengguna'] = $idpengguna;
$_SESSION['success'] = "";
header('location: lamanutama.php');
}else {
array_push($errors, "ID Pengguna/Kata Laluan salah");
}
}
}

<?php
session_start();
// to store session values
$_SESSION['namapengguna']= $idpengguna; // Initializing Session with value of PHP Variable
?>
Main page Code:
echo $_SESSION["namapengguna"];
please visit this link best example for it. here

As long as you have session you can easily write like this
first add session_start(); and change namepenguna to idpenguna because it has to be the same session you set the time you were receiving result form mysql result
echo 'welcome' .$_SESSION['idpengguna'];
I hope this will work

In your database , password column is not encode by md5(dfsdfdsf), but $password = md5($password);.You should check it

try like this, i hope it will help you:
<?php if (isset($_SESSION['namapengguna'])){
echo 'welcome' .$_SESSION['idpengguna'];
}
?>

Related

Retrieving specific value from a database php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a college project where users are able to register and login to a website. I have it set up so when registering a user enters their username, email, password, confirm password, address, and phonenumber. Once registered they are assigned a random string value, lets call it $randomString.
So my database is login_db and it contains the table user. The table headings are username, email, password, address, phonenumber, randomstring.
Its running fine a user can register, their details are added to the database and a user can login. When they log in they are redirected to admin.php. This page is blank at the moment.
Remember the $randomString people are assigned? I need to go into the database retrieve $randomString and display on admin.php.
This is what I've tried so far, I've only been able to display all users random strings but i need only the logged in users randomString. So im presuming the steps i need to go through are
1. Check IF user is logged in. maybe ----> if(isset($_SESSION['email']) ????
2. Check WHAT user is logged in. ????
3. Retrieve logged in users randomString. ????
4. Display the random string. maybe ----> echo $result ???
I have absolutely zero idea how to do it so all help is appreciated.
$connection = mysqli_connect('localhost', 'root', '', 'login_db');
if($connection) {
echo "we are connected";
} else {
die("Database connection failed");
}
?>
<div class="jumbotron">
<h1 class="text-center"><?php
$query = "SELECT randomString FROM users";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_row($result)) {
print_r($row);
}
?></h1>
</div>
Let me explain with your question :
Check IF user is logged in
You need to set some value in session when user logs in your system,so that you can check that session value in each new request like you have said in your may be . i.e. if(isset($_SESSION['email'])
Check WHAT user is logged in. ????
If you want to find out which user had logged in then also you have to set all the user info
(id,username/first or last name etc) in you session same as you had saved
user email in session.
Retrieve logged in users randomString
To retrieve logged in users randomString, you can query the database with the users info that you had kept in session when user logged in first time. i .e .
Select randromString from users_table where id='$_SESSION['id']'; //i had suppose you had kept id of logged in user in session here .
Display the random string
To display the random string, yes now you simply echo the value of $randomString that you have retrieve from database using the query above.
First create the connection
<?php
$hostname_localhost = "localhost";
$database_localhost = "databasename";
$username_localhost = "root";
$password_localhost = "";
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
Secondly select what you want from the database for the logged in user
<?php
$colname_record = "-1";
if (isset($_SESSION['email'])) {
$colname_record = $_SESSION['email'];
}
mysql_select_db($database_localhost, $localhost);
$query_record = "SELECT userID, randomString, email FROM users WHERE email='$colname_record'";
$record = mysql_query($query_record, $localhost) or die(mysql_error());
$row_record = mysql_fetch_assoc($record);
$totalRows_record = mysql_num_rows($record);
?>
Thirdly get the variable of the logged in user and echo it
<?php
$randomstring = $row_record['randomString'];
?>
And display it
<?php
echo $randomstring;
?>

Only admin enters a page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This is my signin.php file
and I want to make a page which only admin (mousoufi) can enter.
I made a new page where I want to post only admin things can see. Else I wanted to echo to other users that they dont have permission here.
I just make a session on top of my admin page?
Any ideas?
<?php
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=new mysqli("localhost","root","","3333");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT username FROM `3333` WHERE password='$pass' AND username='$user'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
}
}
else {
echo "Wrong Password Try Again"; }
// Set session variables
$_SESSION["username"] = "$user";
$_SESSION["password"] = "$pass";
print_r($_SESSION);
if ("$user"=="mousoufi" AND "$pass"=="1234"){
echo "HELLO Mousoufi ";
}
$con->close();
?>
If you want to use sessions you need to start them on every single page that you need them on, and that is done with this:
session_start();
Put that at the top of your php script.
You'll need a way to distinguish admins (if you're going to have more than one?), but since your question only states one, this should work for you:
<?php
// start session
session_start();
// check if username is admin
if($_SESSION['username'] !== 'mousoufi'){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
Notes
You should have more readable table names. 3333 isn't really the best, especially when you call the table the same thing...
You should at least sanitize your user input variables - mysqli_real_escape_string() at very least. It'd be best if you go with PDO or MySQLi Prepared Statements.
Your script is wrong, badly wrong. If your user didn't log in correctly, don't set the session.
if (mysqli_num_rows($result) < 0) {
die("Wrong Password Try Again";);
} else {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
$_SESSION['username'] = $row["username"];
// and so on...
}
}
This is what your block should look like.

how to create a user registration page and cheak if the user is already registered? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have designed a registration form where users are being registered by there name and phone no. now i want a script so that there should be a cheak before registering any user, that wheather the phone number is already been registered or not, only if the user is new he can register into and his data will be filled in the database...
I hope you could do this using this method
if(isset($_POST['signup'])){
$user_name= $_POST['name'];
$phone = $_POST['phone'];
$check = mysql_query("SELECT * FROM users WHERE name='$user_name' AND phone='$phone'");
if( mysql_num_rows($check) ==0 ){
//User is not exist run INSERT Query here
}
else
{
//User is Exist
$exist = true;
exit;
}
}
I don't want to do all of your work for you, but I'll gladly point you in the right direction.
You can do a SELECT query on your users table with the desired username in the WHERE clause and you can use the mysql_num_rows($queryCallback) function in an if statement to see if there are one or more rows returned. If there are, then the process will be terminated and you can just send the user back with an error message.
Example:
SELECT * FROM Users WHERE username = "monkeyballs";
Returns 1 Row
if (mysql_num_rows($result) >= 1) {
return false;
//terminate the registration
} else {
//INSERT query and whatnot
}
Good luck!
I recommend you research MySQL functions in PHP or pick up a framework. CakePHP makes registration / logging in a breeze. Just my two cents for you.
You will have to query the database table holding info about the already registered users and see if that is already there:
eg:
$mysqli = new mysqli("localhost", "user", "password", "dbname");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
if ($query = $mysqli->query("SELECT id FROM users WHERE phone = '123456'")) {
if($result->num_rows == 0)
//register user
else
// send error message
}

password and username validation in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
i have this information on my database...
Username - kam, mav, shin
Password - kam, mav, shin
this is my code...
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2=mysql_query("SELECT * FROM tablename WHERE `username` =
'".mysql_real_escape_string($_POST['username'])."' and `password` =
'".mysql_real_escape_string($_POST['password'])."'");
while($row=mysql_fetch_array($tbl2))
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
if (($row['username']!=$_POST['username'])&&($row['password']!=$_POST['password']))
{
header("location: /login.php?codeError=1");
die;
}
?>
the problem is, if i enter the username "mav" and the password is "kam", it still go through the next page. What should i do?
You should just check if the query returns any rows with mysql_num_rows():
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2 = mysql_query("SELECT `username`, `password` FROM `tablename` WHERE
`username` = '".mysql_real_escape_string($_POST['username'])."' AND
`password` = '".mysql_real_escape_string($_POST['password'])."'
");
$rows = mysql_num_rows($tbl2);
if($rows){
// user and password exists in db
} else {
// does not exist
header("location: /login.php?codeError=1");
die;
}
Like I told you in previous question, try to move from mysql_* functions.
Just a suggestion but why not try it this way:
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}else{
header("location: /login.php?codeError=1");
die;
}
I don't understand why you need two if statements here, it's only boolean and the result will either be true or false.
Hope this helps :)!
You are checking for validation already in your query. If the user entered username and password correctly and only then, the query returns a row, containing that data.
So you only have to count the rows returned bye your Query. If it is below 1, then the user is not authenticated
Try
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
else
{
header("location: /login.php?codeError=1");
die();
}
Anyway, a nice way to address this kind of issues is temporary printing on screen the variables (as a debug).
echo $row['username']." ".$_POST['username']." ".$row['password']." ".$_POST['password']
see if the variables are actually there of if there are issues with your DB query or with the form that posts the data.

Adding a login system [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hey!
I bought and settled up my site long ago..
My site is a facebook like site where people can add their own or like others.
I thought about adding a login system so people can post with their username and make it easier to make posting-liking contests.
I already have the system itself - using this http://www.evolt.org/node/60384
I tried to add an option in the process file that when the session is 'loggedin' the code retrieves the username and in all other cases, 'Anonymous'.
Problem is it doesn't work :(
The code is:
$today = date("Ymdhis");
$rand = $today.mt_rand().mt_rand().mt_rand();
$count = '0';
$type = 'picture';
$username = '<? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?>';
$sql = "INSERT INTO `like` (`rand`, `like`, `count`, `created`, `youtube`, `type`,`username`) VALUES ('$rand', '$like', 0, '$today', '$string', '$type', '$username')";
I first defined $username and then 'told' the script to INSERT the $username entry into it's field.
The problem is that when I try this in real-time,
the field shows the actual code; <? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?> instead of the desired output.
Also, I've included the session.php for the login in the start of the process document.
The session.php I used along with all of the other files is available at http://www.evolt.org/node/60384 WITHOUT download.
P.S the code i used for $username is used on the main page to output the username after logged in.. I added the 'Anonymous' part myself.. which could cause it to not work..
The code you post is PHP, but gets put into your side AFTER it is parsed. So it will never 'run'.
Unless you are using some sort of templating system that parses your code twice, don't you mean this?
if($session->logged_in){
$username = $session->username;
} else {
$username = "Anonymous" ;
}
$username is a variable containing a string :
$username = '<? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?>';
Everything that is in the quotes is a string, not PHP code. It won't be executed.
You need to do something like this :
if($session->logged_in){
$username = $session->username;
} else {
$username = "Anonymous";
}
Change
$username = '<? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?>';
to
if($session->logged_in) $username = $session->username; else $username = "Anonymous"

Categories