know the userid of logged in user - php

Good morning guys, I have a problem. I created one login page and connected it with another page. That page is like a sending friend request system. I want the sender to be able to view their own profile but not be able to send friend requests to their own id. How can I hide the details of the logged in user? How can I get the logged in user's id? I hope someone will help me. Thanks a lot.
Login page:
<?php
session_start();
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if(isset($_POST['login'])) {
$username =$mysqli->real_escape_string($_POST['username']);
$pass = md5($_POST['pass']);
$sql="SELECT * id FROM users WHERE username='$username' AND pass='$pass' LIMIT 1;";
$result = mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
$row = mysqli_fetch_array($result);{
$_SESSION['loggedIn'] = true;
$_SESSION['uid'] = $result['id'];
$result['id']= trim($row["id"]);
header ("Location:Home.php");
exit;
}
}
?>
Home page:
<?php
session_start();
$_SESSION['uid'];
$db = new PDO('mysql:host=127.0.0.1;dbname=accounts','root','');
require 'class/friends.php';
$query = $db->prepare("SELECT * FROM users");
$query->execute();
if($query->rowCount()>0)
{
while($fetch = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $fetch['id'];
$username = $fetch['username'];
$profile = $fetch['profile'];
$email = $fetch['email'];
?>
<form method="post"><table>
<tr class="border_bottom">
<td height="230">
<img src='<?php echo $profile;?>'width="200" height="200"/>
</td>
<td><td></td></td>
<td><?php echo $username;?><br />
<?php echo $email;?>
</td>
<?php
if($id != $_SESSION['uid']) {
if(Friends::renderfriendship($_SESSION['uid'],$id,'isThereRequestPending')== 1){
?>
<td><button class="request_pending" disabled>Request Pending</button></td>
<?php
} else {
if(Friends::renderfriendship($_SESSION['uid'],$id,'isThereFriendShip')== 0) {
?>
<td><button class='friendBtn_add' data-uid='<?php echo $id;?>' data-type='addfriend'>Ad as friend</button></td>
<td> <button class="request_pending hidden" disabled>Request Pending</button></td>
<?php
}else{
?>
<td> <button class='friendBtn unfriend' data-uid='<?php echo $id;?>' data-type="unfriend">Unfriend</button></td>
<td> <button class='friendBtn_add hidden' data-uid=<?php echo $id;?> data-type='addfriend'>Ad as friend</button></td>
<td> <button class="request_pending hidden" disabled>Request Pending</button></td>
</td >
</tr>
</table>
</form>
<?php
}
}
}else{
}
?>
</div>
</div>
<?php
}
}
?>
</div>
</table>

Your login file seems a little big jumbled, but I will try to decipher your errors. From Progrock, the MySQLi query is wrong. You want it to look like: SELECT * FROM users WHERE username='$username' AND pass='$pass' LIMIT 1
RiggsFolly helped me notice a little error with a if statement as well. It should look like this:
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_array($result);
$_SESSION['loggedIn'] = true;
$_SESSION['uid'] = $row['id'];
$result['id']= trim($row["id"]);
header ("Location:Home.php");
exit;
}
You had the curly bracket in the wrong column and you used the $result variable instead of the $row variable.
Apart from that, I would strongly recommend RiggsFolly's advice, as your code is very susceptible to lots of attacks and is not written very securely.

Related

how to get each input value on form submit

I'm building a friend request system,But my problem is how to get each user value which is the id in my code,But with the code i have so far it only get and return only the first user id even when you try to add other friend it only get the first user id in my database please someone should fix my code.
users.php
<div class="users_b">
<?php
include 'db.php';
$sq = "select * from alert_users_account";
$query = mysqli_query($con,$sq);
while($row = mysqli_fetch_assoc($query)){
?>
<div class="user_dis_p">
<div id="user_img"><a href="alert_profile.php?id=<?php echo $row['id']?>"><img src="alert<?php echo $row['photo']; ?>">
</a></div> <div id="user_fs">
<a href="alert_profile.php?id=<?php echo $row['id']?>">
<?php echo $row['firstname']." "." "." "." ".$row['surname'];?></a>
<form id="f_form">
<input type="text" name="friend_id" id="friend_id" value="<?php echo $row['id']?>">
<input type="submit" id="add_user" value="ADD" onclick="return request()">
</form>
</div><?php }?>
</div>
</div>
<div id="msg"></div>
<script>
function request(){
var frnd = document.getElementById("friend_id").value;
alert(frnd);
$.ajax({
type:'get',
url:'user_request.php',
data:{
frnd:frnd
},
cache:false,
success: function(message){
$("#msg").html(message);
}
});
return false;
}
</script>
user_request.php
<?php
session_start();
include 'db.php';
if(isset($_SESSION['email'])){
$eml = $_SESSION['email'];
$sq = $con->prepare("select id from alert_users_account where email_phone=?");
$sq->bind_param('s',$eml);
$sq->execute();
$res = $sq->get_result();
$ro = $res->fetch_assoc();
$user = $ro['id'];
if($_GET['frnd']){
echo $id = $_GET['frnd'];
$sql = $con->prepare("select * from alert_users_account where id=?");
$sql->bind_param('i',$id);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
$frnd = $row['id'];
$sql = $con->prepare("insert into friend (user_id,friend_id)values (?,?)");
$sql->bind_param('ss',$user,$frnd);
$sql->execute();
$sql->close();
echo "successfully inserted!";
}else{
echo 'error';
}
}else{
echo 'you cant add a friend!';
}
?>
I also try to use post method but both still give the same feedback
It appears you will need to rewrite certain aspects of your code. Here is my explanation:
You're using a while loop to show many different form elements with the id of "friend_id".
By using document.getElementById("friend_id"), you're only able to get one of those input elements that has the id of "friend_id".
You might use class="friend_id" on your input elements and go from there.

Php not working in form

Update
My Page is not pulling information from the form for some reason it wants to keep all the fields empty even though if it is checked it should change the value of the QuestionOptionId. What i want it to do is when you check the radio button it saves the value to the session so it can be submitted later like a quiz. For some reason my code wont change the value or even obtain the value of QuestionOptionId
Code below
<?php
session_start();
//check if the user is already logged in.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
}
$QuestionOptionId = "";
//get value from post data and store into session
if (isset($_POST['QuestionOptionId'])){
$_SESSION['QuestionOptionId'] = $_POST['QuestionOptionId'];
}
//get back from session
if (isset($_SESSION['QuestionOptionId'])){
$QuestionOptionId = $_SESSION['QuestionOptionId'];
}
print $_SESSION['username'];
?>
<?php
$con=mysqli_connect("localhost","root","root","root") or die();
//execute query
$query ="SELECT UserId from user where username = '".$_SESSION['username']."'";
$result=mysqli_query($con, $query);
$UserId=$result->num_rows;
while ($row = $result->fetch_assoc()) {
echo $row['UserId'];
$UserId=$row['UserId'];//etc...
}
?>
<body>
<header>
<p class="text-center">
Welcome :<?php echo $_SESSION['username'];
echo $UserId;
?>
</p>
<?php
$query="SELECT * from testview";
$res=mysqli_query($con, $query);
$rows=$res->num_rows;
$i=1;
while($result=mysqli_fetch_array($res))
{?>
<?php if($i==1){?>
<div id='question<?php echo $i;?>' class='cont'>
<form name="QuestionTime"Method="post" action="push.php">
<p class='questions' id="qtext<?php echo $i;?>"> <?php echo $i?>.<?php echo $result['QuestionText'];?></p>
<input <?php if ($QuestionOptionId=='3'){ echo 'checked="checked"';} ?>type="radio" value="1" id='radio1_<?php echo $result['QuestionOptionId'];?>'name="1"/>
<?php
$query="SELECT OptionChoiceName FROM testview WHERE OptionChoiceId=3";
$res=mysqli_query($con, $query);
$rows=$res;
$i=1;
while($result=mysqli_fetch_array($res))
echo $result['OptionChoiceName'];?>
<input <?php if ($QuestionOptionId=='4'){ echo 'checked="checked"';} ?> type="radio" value="2"id='radio1_<?php echo $result['QuestionId'];?>'name="1"/>
<?php
$query="SELECT OptionChoiceName FROM testview WHERE OptionChoiceId=4";
$res=mysqli_query($con, $query);
$rows=$res;
$i=1;
while($result=mysqli_fetch_array($res))
echo $result['OptionChoiceName'];
?>
<br><br>Selected Value: <?php echo $QuestionOptionId; ?>
<br/>
<?php
$_SESSION['UserId']=$UserId;
?>
<button id='next<?php echo $i;?>' class='next btn btn-success' type='submit'>Finish</button>
</div>
<?php } $i++;} ?>
</form>
</div>
</div>
</header></header>
any help would be grand thanks
You were not fethcing QuestionOptionId & QuestionId. Try with this query -
SELECT OptionChoiceName, QuestionOptionId, QuestionId FROM testview WHERE OptionChoiceId=3
This should be -
if(isset($_SESSION['QuesitonOptionId']))
{
$QuestionOptionId= $_SESSION['QuesitonOptionId'];
}

Session variable content changes when form refreshes in PHP

suppose I have two users in the SQL database. In the table column authority one is the Administrator and the other is user.
My issue is if I log in as the Administrator, before the form refreshes, the $_SESSION['Authentication'] echoes 'Administrator', but after the form refreshes $_SESSION['Authentication']` echoes as 'user'.
Where have I gone wrong in my code which result the $_SESSION['Authentication'] = 'user' whereas it should be $_SESSION['Authentication'] = 'Administrator' after the form refreshes?
Code :
Session started at the beginning....
then this follows.
<?php
include ("connect_db/index.php");
if(isset($_SESSION['loggedUser']))
{
echo "<form action='signoff/index.php'><div id='four'>Welcome&nbsp". $_SESSION['loggedUser']." !
<input type='submit' name='soff' id='soff' class='sout' value='Sign off'></div></form>";
echo "You are the : ".$_SESSION['Authentication']." of the site.";
}
else
{
?><div id='one'><?php
echo "
<div id='u2'>
<form name='form1' method='post' action='''>
<table border='1' style='width:520px; bordercolor:#FFFFFF;'>
<tr>
<td style='width:30px;'>User Name: </td>
<td style='width:80px;'><label for='textfield'></label>
<input type='text' maxlength='12' name='UnameZoom' id='UnameZoom' class='txss'></td>
<td style='width:30px;'> Password: </td>
<td style='width:80px;'><label for='txss'></label>
<input type='password' maxlength='12' name='PwordZoom' id='PwordZoom' class='txss'></td>
<td> <input type='submit' name='loggedUser' id='loggedUser' class='mylog' value='Login'></td>
</tr>
</table>
</form>
<p> </p>
<p> </p>
</div>";
?></div><?php
if(isset($_POST['loggedUser']))
{
?><div id='two'><?php
$un = $_POST['UnameZoom'];
$pw = $_POST['PwordZoom'];
if($un=='' || $pw == '')
{echo "<div id='three'>Empty Fields</div>";}
else {
$SQL = "SELECT pword FROM users WHERE username='$un'";
$resultA = mysqli_query($db,$SQL) or die ("SQL Error!!!");
$row = mysqli_fetch_array($resultA);
if($pw == $row['pword'])
{
$resultB = mysqli_query($db,"SELECT fname AS Lna FROM users WHERE username='$un'");
$rowB = mysqli_fetch_assoc($resultB);
//$sum = $rowB['Lna'];
$_SESSION['loggedUser'] = $rowB['Lna'];
$resultC = mysqli_query($db,"SELECT authority AS Auth FROM users WHERE username='$un'");
$rowC = mysqli_fetch_assoc($resultC);
unset($_SESSION['Authentication']);
$_SESSION['Authentication'] = $rowC['Auth'];
header("refresh:3;");
//echo "<div id='four'>Welcome&nbsp". $_SESSION['loggedUser']."&nbsp!</div>";
}
else
{
echo "<div id='three'>No user found</div>";
}
}
?></div><?php
}
}
?>
// this is where I'm trying to echo
<div id="contentLog">
<?php
if(isset($_SESSION['Authentication']))
{echo $_SESSION['Authentication'];}
?>
Your header("refresh:3;"); makes me suspicious. This might be relevant. Add session_write_close() before you call header()? Echo session_id() to see if the refresh creates a new blank session or if you have a logic error.
please use this condition
if($_POST['loggedUser'] != "")
{
}

Printing session variable content in PHP

Hi I have the following as my login script. (The script is not yet sanitized.) But I have an issue here. Once a successful log in attempt is made I need to echo the loggedUser but the information doen't get printed once echoed. Can someone pls help me understand where I have gone wrong?
Code as follows;
<?php
SESSION_start();
?>
<!doctype html>
<html>
<head></head>
<body>
<div>
<?php
include ("connect_db/index.php");
if(isset($_SESSION['loggedUser']))
{
echo '<div>User :'.$_SESSION['loggedUser'].'</div>';
}
else
{
echo "
<div id='u2'>
<form name='form1' method='post' action='''>
<table border='1'>
<tr>
<td>User Name: </td>
<td><label for='textfield'></label>
<input type='text' name='UnameZoom' id='UnameZoom' class='txss'></td>
<td> Password: </td>
<td><label for='txss'></label>
<input type='password' name='PwordZoom' id='PwordZoom' class='txss'></td>
<td> <input type='submit' name='loggedUser' id='loggedUser' class='mylog' value='Login'></td>
</tr>
</table>
</form>
<p> </p>
<p> </p>
</div>";
if(isset($_POST['loggedUser']))
{
$un = $_POST['UnameZoom'];
$pw = $_POST['PwordZoom'];
if($un=='' || $pw == '')
{echo "Empty fields"; return;}
$SQLSz = "SELECT pword FROM users WHERE username='$un'";
$rVz = mysqli_query($db,$SQLSz) or die ("SQL Error!!!");
$roVz = mysqli_fetch_array($rVz);
if($pw == $roVz['pword'])
{
$result = mysqli_query($db,"SELECT Lname AS Lna FROM users WHERE username='$un'");
$row11 = mysqli_fetch_assoc($result);
$sum = $row11['Lna'];
$_SESSION['loggedUser'] = $sum;
echo $_SESSION['loggedUser'];
}
else
{
echo "No user found";
}
}
}
?>
<div></body></html>
I think problem is in your variable. It can be array but u cant echo array. try dump your variable with var_dump.
As already mentioned - SESSION_start() shall be session_start()
Try another statement for displaying your SESSION array - for example:
echo '<pre>';
print_r($_SESSION);
echo '</pre'>;
This will show you all session keys in a nice and readable way

show single entry on a new page with sending id of row

i am very novice to php and mysqli and found a great tutorial but am needing some help.
i am wanting a row to be linkable and send it to another page named single.php?id=ROWID so it will show the single entry
this is what i got so far.
<html>
<head>
<title>MySQLi Tutorial</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}
}
$query = "select * from users";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results ){
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$firstname}</td>";
echo "<td>{$lastname}</td>";
echo "<td>{$username}</td>";
echo "<td>";
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<script type='text/javascript'>
function delete_user( id ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + id;
}
}
</script>
</body>
</html>
i am right in thinking i would be sending the rows id in the url ?
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
but i am having issues with single.php what code would i have to put to show the single entry?
i have been on this a while and got no were near so i deleted the code and swallowed my pride to seek some help :/
thanks in advance
Thank you for the interesting question.
First, let me inform you that, although you are using a moder-looking database access library, the way you are using it is as ancient as a mammoth fossil.
Several things to consider
Never use mysqli as is, but only in the form of some higher level abstraction library.
Never use real_escape_string in the application code but use prepared statements only.
Never mix your database code with HTML output. Get your data first, then start for output.
Never use GET method to modify the data.
Here goes the example based on the above principles. It does ALL basic CRUD operations:
<?
include 'safemysql.class.php'; // a library
$db = new SafeMysql();
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') {
if (isset($_POST['delete'])) {
$db->query("DELETE FROM ?n WHERE id=?i",$table,$_POST['delete']);
} elseif ($_POST['id']) {
$db->query("UPDATE ?n SET name=?s WHERE id=?i",$table,$_POST['name'],$_POST['id']);
} else {
$db->query("INSERT INTO ?n SET name=?s",$table,$_POST['name']);
}
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) {
$LIST = $db->getAll("SELECT * FROM ?n",$table);
include 'list.php';
} else {
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
It is using templates to display the data:
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
and form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? if ($row['id']):?>
<div align=right>
<form method="POST">
<input type="hidden" name="delete" value="<?=$row['id']?>">
<input type="submit" value="Удалить"><br>
</form>
</div>
<?endif?>
here goes the part for display.
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
if you don't want to show the form - create another template called single.php with whatever markup you wish
Single.php
I Use PDO if u want you can make it with MySQLi too.
<?php
include("db_connect.php"); // database configuration file
if(isset($_GET['id'])
{
$id = (int) $_GET['id'];
$sql = "SELECT * FROM `users` WHERE id=?";
$query = $conn->prepare($sql); // $conn is PDO object yours can be different
$query->bindValue(1,$id);
$query->execute();
if($query){
$row = $query->fetch(); //
}else{
echo "Error with Database";
}
}
else // Error for the Id selection
{
echo("ID is not selected");
}
?>
No while loop because you want just 1 record. $row variable is just for test because i don't know your fields in your DB
<table border="1">
<tr>
<td>ID</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
<tr>
<td><?php echo $row['id]; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
</table>
in your single.php
$id=$_GET['id'];
$query="select * from users where id='".$id."'";

Categories