PHP, MYSQL checking if a user is owner of a page - php

I am trying to check if a user is the owner of a profile page so that i can display a text box for entering twitter similar posts.
The code
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$ultimatum_form ='';
if(isset($_SESSION['id'])){
if($_SESSION['id']==$id){
$ultimatum_form = 'Write an ultimatum!(220 char max)<br/>
<form action="profile.php" method="post" enctype="multipart/form-data" name="ultimatum_form">
<textarea name="ultimatum_field" rows="3" style="width:97%;"></textarea>
</form>';
}
}
print "$ultimatum_form";
in my DB i have a table called "users", the table users has the columns "firs", "last", "username", "password", "email" and "id".
If i set $ultimatum_form outside of the session check it outputs the text-field and it works. The problem is that if i then go to another persons profile i can see the text-field and write posts for them.

You need to get data from the query:
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$r = mysql_fetch_assoc($id);
$id = $r['id'];
then $id contains the row "id" value.
look into pdo/mysqli, mysql won't wrok in next php version.
here, better:
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$r = mysql_fetch_assoc($id);
$id = $r['id'];
if(isset($_SESSION['id']))
{
if($_SESSION['id']==$id)
{
echo '
Write an ultimatum!(220 char max)<br/>
<form action="profile.php" method="post" enctype="multipart/form-data" name="ultimatum_form">
<textarea name="ultimatum_field" rows="3" style="width:97%;"></textarea>
</form>';
}
else
{
// Not users profile page
}
}

You can't exactly do what you're doing. You need to fetch the records.
$results = mysql_fetch_array(mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'"));
Then you can do:
if($_SESSION['id']==$results['id']){

Related

Check duplicates name ignore entry

I am using following code to insert entry in my database. But i can add same entry multiple time and i wanna that whenever i submit same entry in input type then message will show "Nickname already exists "
<div>
<form>
<div>name <input type="text" name="na"/></div>
<div>marks1 <input type="text" name="m1"/></div>
<div>marks2<input type="text" name="m2"/></div>
<div>marks3 <input type="text" name="m3"/></div>
<div> <input type="submit" name="save" value="save"/></div>
</form>
</div>
And Here is my php code:-
<?php
if(!empty($_GET['save'])){
$na=$_GET['na'];
$m1=$_GET['m1'];
$m2=$_GET['m2'];
$m3=$_GET['m3'];
$query="insert into student(name,marks1,marks2,marks3) values('$na','$m1','$m2','$m3')";
mysqli_query($connect,$query);
}
?>
Make a unique column in database for example unique name for every student. So when you enter new record first check it that either it is present in the database or not. If its there then you can show error to user
For example you can set a unique constraint like this
Do a select before inserting in your base to check if the username already exists.
For your input message showing that the username already exists you can use a hidden paragraph:<p id="informationText" hidden>This paragraph should be hidden.</p>
Then once your select request has returned that the tuple already exists do an ajax query to show up this paragraph: $('#informationText').removeAttr('hidden');
That's a simple way, there is other better way to do that you can do some research about JavaScript Form Validation
FIRST EDIT
Here is a code sample:
<?php
if( isset( $_GET['save'] ) ){
$na=$_GET['na'];
$m1=$_GET['m1'];
$m2=$_GET['m2'];
$m3=$_GET['m3'];
$query = "select * from student where name = ? ";
$result = mysqli_query( $connect,$query, array( &$na ) );
$row = mysqli_fetch_row( $result );
if (count($row) > 0) {
echo "<script>$('#informationText').text = "Username already exists";$('#informationText').removeAttr('hidden');</script>";
} else {
$query="insert into student(name,marks1,marks2,marks3) values('$na','$m1','$m2','$m3')";
mysqli_query($connect,$query);
}
}
?>

Edit User Information for other user

Sorry I'm beginner in PHP MYSQL.
I want to ask how this will work. May I know how to fix this or what code will I add?
Scenario:
We have user type ADMIN and NORMAL USER,
I created edit.php to edit user accounts as an ADMIN incase of lost password etc. but I have problem was when I click Edit button in specific table.
See Picture Below, I logged in here as an Admin, employee.php.
So I choose the user testFN with the id of 22
The code I used here to fetch the id is here :
<td><a href="edit.php?id=<?php echo $row['user_id']; ?>" >Edit</a></td>
When I click the EDIT button it will open the page edit.php, with this url
So I the outcome is not equal to what I want, the information to the input boxes were from the user I'm using/logged in not from the user I chose to edit.
The code I used to EDIT.PHP is here:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{ header("Location: edit.php"); }
$res=mysql_query("SELECT * FROM accounts WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_GET['user'])) {
$id = $_GET['user'];
if(isset($_POST['submit'])) {
$pass = md5(mysql_real_escape_string($_POST['pass']));
$aFName = mysql_real_escape_string($_POST['aFName']);
$aLName = mysql_real_escape_string($_POST['aLName']);
$aMName = mysql_real_escape_string($_POST['aMName']);
$aContact = mysql_real_escape_string($_POST['aContact']);
$aAddress = mysql_real_escape_string($_POST['aAddress']);
$aGender = mysql_real_escape_string($_POST['aGender']);
$utype = mysql_real_escape_string($_POST['utype']);
$query3=mysql_query("UPDATE accounts SET pass='$pass', agentFName ='$aFName', agentLName = '$aLName',
agentMName = '$aMName', agentContact = '$aContact', agentAddress = '$aAddress',
agentGender = '$aGender', user_type = '$utype' ");
if($query3)
{ header("Location: home.php"); }
}//end of post sumbit
}//end of GET
?>
/** HTML IS HERE **/
Agent ID: <input type="text" id="agentCode" name="agentCode" required="required" value="<?php echo $userRow['user_id']; ?>" >
First Name: <input type="text" id="agentCode" name="aFName" required="required" value="<?php echo $userRow['agentFname']; ?>" >
Middle Name: <input type="text" id="agentCode" name="aMName" required="required" value="<?php echo $userRow['agentMname']; ?>" >
Last Name: <input type="text" id="agentCode" name="aLName" required="required" value="<?php echo $userRow['agentLname']; ?>" >
This is where you set the value for that text input:
value="<?php echo $userRow['user_id']; ?>"
Where does $userRow come from? This:
$userRow=mysql_fetch_array($res);
What query was used to fetch the data? This:
$res=mysql_query("SELECT * FROM accounts WHERE user_id=".$_SESSION['user']);
So... you're specifically fetching the data from the logged-in session user, rather than the one specified on the query string. Just use the query string value instead of the session value.
Important:
Using user-supplied values directly in SQL queries is called a SQL injection vulnerability. It's a very bad thing. You're going to want to use query parameters and prepared statements. This is a good place to start reading.
You're really going to want to check if the logged-in user is authorized to edit the specified user before allowing them to do so. Any user can manually add/change query string values or POST values or basically anything that comes from the client.

How can I query a database based on a user text input?

So I am creating a Lorem Ipsum generator and I am stuck.
I have created a table called "wutangsoldiers", which contains the id of the user, their name, and each row has a different lyric. So far I have this:
$id = get_the_ID();
global $wpdb;
$lyrics = $wpdb->get_results("SELECT * FROM `wutangsoliders` WHERE `name` = '$id' ");
Inside of the generated text div, I have
<?php foreach ($lyrics as $lyrics) {
?>
<p><?php echo $lyrics->text;?></p>
<?php } ?>
How would I limit the number of "lyrics" shown based what the user inputs in <input type="submit" id="blaow" name="blaow">
To get the ID of the user based on a (I assume a text Input) I also assume that you are using HTTP POST METHOD ($_POST)
This is the User Value
<form>
<input type="text" value="1" name="user_value">
<input type="submit" id="blaow" name="blaow">
</form>
This is how to get the value
if(isset($_POST['blaow']){ // if the input has been pressed
$idUser = $_POST['user_value']; // the value sent from the HTML above
$lyrics = $wpdb->get_results("SELECT * FROM `wutangsoliders` WHERE `name` = '$idUser' ");
foreach ($lyrics as $lyrics) {
print "<p>".$lyrics->text."</p>";
}
}
Just get the user input limit that
$userinput = $_GET['lyrics_limit'];
Then put it in sql query
$lyrics = $wpdb->get_results("SELECT * FROMwutangsolidersWHEREname= '$id' limit '$userinput' " );
Then you will get only according to the input by user.

allowing just friends to comments in their profile page

i have a profile page that contain a comment system and i just allow the owner of the profile to write their comments now i want to allow friends also to write how to do that ???
in the members table i have a friend_array field that contain the ids of users that are friend with this user
the friend request system include ajax and jquery
code.php
$blab_form="";
if(isset($_SESSION['user_id']))
{
if($_SESSION['user_id']==$id)
{
$blab_form='
'.$blab_output_msg.'<br />
<div style="background-color:#D2F0D3;border:#999 1px solid; padding:8px;">
<form action="profile.php" method="post" enctype="multipart/form-data" name="blab_form">
<textarea name="blab_field" cols="" rows="4" style="width:100%;">
</textarea><br />
(220 Char Max)
<input type="submit" name="submit" value="Blab"/>
</form></div>';
//$sql = mysql_query("DELETE FROM blabing WHERE u_id ='$id'")or die(mysql_error());
}
}
friend_request_system
<?php
//****************friend request system********************//
// for securing the request with and encryption to be more secure.
if(isset($_SESSION['wpit']))
{
$_SESSION['wipt'];
}
$theRundomNum = rand(99999999999999,9999999999999);
$_SESSION['wipt'] = base64_encode($theRundomNum);
//*********for distinguich the users*************//
//if member is a viewer
$friendLink = "";
if(isset($_SESSION['user_id'])&&$_SESSION['user_id']!=$id)
{
//for quering friend array for the viewer if he is not the owner
$sqlArray = mysql_query("SELECT friend_array FROM members WHERE user_id ='".$_SESSION['user_id']."' LIMIT 1")or die(mysql_error());
while($row = mysql_fetch_array($sqlArray))
{
$iFriendArray = $row['friend_array'];
}
$iFriendArray = explode("," , $iFriendArray);
if(in_array($id, $iFriendArray))
{
$friendLink = 'Remove Friend';
}
else
{
$friendLink = 'Add as Friend';
}
$interactionBox='<div class="interactionLinksDiv">
'.$friendLink.'
</div>';
}
//if member is the profile ower
else
{
$interactionBox = '<div class="interactionLinksDiv">
Freind Request List </div>';
}
?>
if($_SESSION['user_id']==$id) is specific to the blog owner, right? So you make this conditional check if the session id is in an array of acceptable id's. Something like this:
// assuming you already populated the $iFriendArray as outlined in your question
$iFriendArray[] = $id; // add blog owner to the friend array
if(in_array($_SESSION['user_id'], $iFriendArray))
{
// can comment
}
This has been updated to use the friend array as updated in your question.
Any questions feel free to ask and I may update.

Selecting ID in while statement PHP

I'm attempting to make a function that will allow users to delete posts they have left. Basically I'm trying to select an ID and then pass it off to another function to delete it. The current code is deleting every comment, not just the comment linked to the ID like I'm attempting to.
Here are the table values
Table eventUpdates
ID - unique ID. Trying to use this value to delete the post
eventID - references an eventID from another table
eventReply - the "message" or response
eventUserID -ID of the user posting the message
username -username of the person
eventTimestamp -timestamp
So, currently every response is being deleted. I can't get it to delete just the ID that I send.
<table border ="1">
<?
$eventUpdates = mysql_query($sql);
while ($list = mysql_fetch_assoc($eventUpdates)) {
echo $updateID;
echo '<tr><td>';
echo $list['username'],"</br>", $list['eventTimestamp'],'<br/>';
if($list['eventUserID'] == $userid){ //used for deleting posts. Checks the session to make sure it's the user who made the post
?>
<form method="post">
<input type="submit" name="deleteUpdate" value="Delete Update">
</form>
<?
if(isset($_POST['deleteUpdate'])){
$updateID = $list['ID'];
$delete = new postprocessing;
$delete->deleteEventUpdate($updateID);
echo '<meta http-equiv="refresh" content="0;url=main.php">';
}
}
echo '</td><td>';
echo $list['eventReply'];
echo '</td></tr>';
}
Here is the function used to delete it
function deleteEventUpdate($ID){
mysql_query("delete from eventUpdates where ID = '$ID'");
}
This is because you haven't specified the ID you want to delete in the post array, so every comment they created "matches" the deletion criteria. The $_POST array looks like:
$_POST = array('deleteUpdate'='Delete Update');
so when you're looping through the list of events, every comment that the user 'owns' ($list['eventUserID'] == $userid) matches the criteria "isset($_POST['deleteUpdate'])":
You need to include a hidden input with the ID the specific comment you want to delete and match against it as well:
<form method="post">
<input type="submit" name="deleteUpdate" value="Delete Update">
<input name='post_id' value="<?php echo $list['ID'];?>" type='hidden' />
</form>
and then in the loop:
if(isset($_POST['deleteUpdate']) && isset($_POST['post_id']) && $_POST['post_id']==$list['ID']){...

Categories