i am creating a friend request system that allow user to send request to each other to add as friends like facebook
and i have 2 conditions that if :
the user is the profile owner he can not add him self i will echo an
error msg
the user is not the owner of the profile it will echo a message that
say wait then the request is send
if the user has already send the request i will echo a message to infor the user that a request had been send.
but the error is that i am in the first condition because the system display that the user is the owner profile but this is wrong
can anyone help me ??
this is a chunk of code
function addAsFriend(a,b){
//alert("Member with id:" + a + "request friendship with the memeber with id:" + b);
var url = "script_for_profile/request_as_friend.php";
$("#add_friend").text("please wait...").show();
$.post(url,{request:"requestFreindship",mem1:a,mem2:b},function(data){
$("#add_friend").html(data).show().fadeOut(12000);
});
}
<div class="interactContainers" id="add_friend">
<div align="right">Cancel</div>
Add <?php echo $username ?> as Friend?
Yes
request_as_friend.php
<?php
//var we need for both members
$mem1=preg_replace('#[^0-9]#i','',$_POST['mem1']);
$mem2=preg_replace('#[^0-9]#i','',$_POST['mem2']);
if(!$mem1||!$mem2)
{
echo "Error .missing data";
exit();
}
if($mem1==$mem2)
{
echo "Error you can not add yourself as friend";
exit();
}
require_once('../include/connect.php');
if($_POST['request']=="requestFriendship")
{
//check that there is not a request pending where this viewer is requesting this profile owner
$sql = mysql_query("SELECT id FROM friend_requests WHERE mem1='$mem1' AND mem2='$mem2'limit1")or die(mysql_error());
$numRows = mysql_num_rows($sql);
if($numRows > 0)
{
echo "You have a friend request pending already for this member. they must approve it when they view their request list";
exit();
}
//check that there is not a request pending where this profile owner is not already requesting this viewer
$sql = mysql_query("SELECT id FROM friend_requests WHERE mem1='$mem2' AND mem2='$mem1'limit1")or die(mysql_error());
$numRows = mysql_num_rows($sql);
if($numRows > 0)
{
echo "This user has requested you as friend already! Check your friend Request on your profile";
exit();
}
$sql = mysql_query("INSERT INTO friend_requests(mem1,mem2,timedate) VALUES('$mem1','$mem2',now())") or die (mysql_error("friend request insertionn error"));
//$sql = mysql_query("INSERT INTO pms(to,from,time,sub,msg) VALUES('$mem2','XXXXX',now(),'New Friend Request','YOU Have a New friend request waiting for approval.<br /><br />Navigate to your profile and check your friend request.<br /><br />Thank you.')") or die (mysql_error("friend request PM insertionn error"));
echo "Friend Request sent succesfully. this member must approve the request";
exit();
}
?>
I was totally wrong, you don't need to create any extra flag, just store the user_id -which you retrieve from the database when the user logs in - store it in the session then when he/she clicks on the add friend button check the $_SESSION['user_id'] with the id of the other user before completing the friendship function, if they're both the same, means it's the same person, otherwise add friends.
What the post array returns for mem1 and mem2?
However, you shouldn't compare the post data. Or not both.
For example you have logged in, your id is stored in session. You are opening a user profile i.e.: http://yoursite.com/viewprofile.php?id=1001 . Then after passing from the jquery you should check in PHP smth like:
if ($_GET['id'] = $_SESSIOM['id']) {
//you cannot add yourself
}
I have made an app in which the scenario is as below:
user can register and that registration information goes to a PHP server and is stored in a MySQL database.
This is my PHP file:
<?php
// Check if he wants to login:
if (!empty($_POST[username]))
{
require_once("connect.php");
// Check if he has the right info.
$query = mysql_query("SELECT * FROM gen_users
WHERE username = '$_POST[username]'
AND password = '$_POST[password]'")
or die ("Error - Couldn't login user.");
$row = mysql_fetch_array($query)
or die ("Error - Couldn't login user.");
if (!empty($row[username])) // he got it.
{
echo "success";
exit();
}
else // bad info.
{
echo "comes in else part";
exit();
}
}
?>
If I enter a username and password that match from MySQL database, then it throws the word "success" to Android class and will go further in the app. I have a display list-view of registered people in my app.
How can I know how many people use my app right now? The people who are logged-in in app are to appear as a green image in a list view and other people are to appear as a red image.
How can I achieve this?
in addition to #GlaciesofPacis answer you can do one of the following:
send a request for the server in intervals and check who's online or not.
you can use a client-server mechanism - which -is much more complicated but much more efficient and elegant - and make the server push to all online clients when some client is now off or on.
i don't really know what your app is supposed to do, but option number 2 - for my opinion - worth the hard work..
links:
intro to socket servers in php
intro to socket servers in java
Try adding a column to your users table regarding logged-in status (tinyint(1) since it's a MySQL table). It will be populated as either 0 (indicating logged out) or 1 (logged in). Upon logging in, the value needs to be set in the database as 1, and within your logout function, set back to 0. This way, you can use something similar to the below (which assumes the use of User objects):
<?php
$users = getUsers();
foreach($users as $user)
{
$display = "";
if($user->isLoggedIn())
{
$display .= '<img src="green.png" alt="Logged In" />';
}
else
{
$display .= '<img src="red.png" alt="Logged Out" />';
}
$display .= $user->getUsername().'<br />';
echo $display;
}
?>
The SQL command to alter your table:
ALTER TABLE gen_users ADD COLUMN loggedin TINYINT(1) DEFAULT 0;
New to php. I have a form that is only for members to submit. What php code do I need for the form to check that the email address on the form is found my members database and then its okay to submit the form?
If email address is not in the members database then I want to echo "Only members can submit this form." What php code do I need to connect to database in the form and do the check so I don't get forms submitted from non members?
Thanks
At the top of your php file you could do something like this:
if(isset($_POST['email'])) {
mysql_connect("hostname","username","password");
$result = mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'");
if($row = mysql_fetch_array($result)) {
// found email
} else {
// email wasn't found
}
}
Of course you would need to replace the hostname, username and password to correct values, also you should change the users and email in the select query to the name of your table and field.
Here is a dummy form:
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="text" name="email" />
<input type="submit" value="Send" />
</form>
You want to study Mysql query and other mysql functions. The code would basically look like:
$c = mysql_connect( ...);
mysql_select_db( 'database', $c);
$q = mysql_query( "SELECT COUNT(*) FROM users WHERE email = '" .
mysql_real_escape_string( $_POST['email'],$c) . "'");
$row = mysql_fetch_row( $q);
if( $row[0]){
echo "Thanks for submitting...";
} else {
echo "Only members...";
}
This is only brief example which is far from perfection but I think it's good place for you to start.
If someone is a registered member that implies you're very likely using a $_SESSION['id_member'] variable.
This will set the cookie's name that can be seen by the client to 'member'...
if (!headers_sent() && !isset($_SESSION))
{
session_name('member');
}
...then when a user authenticates assign a session variable and their permission...
$_SESSION['member_id'] = $mysql_row['id'];
$_SESSION['member_status'] = $mysql_row['id'];
Here is a status hierarchy that you might use or change but it should be a good point of reference...
10 - Super Admin (only you)
9 - Admin// mid-level admin
8 - Assistant//restrictive admin
7 - Moderator//Don't give this status to any jerks
6 - Premium Member//they gave you money!
5 - Registered Member//normal account status
4 - Frozen Account//not banned but did something wrong, will "thaw"
3 - Unverified Email Address//registered but did not verify email
2 - Unregistered Visitor//human
1 - Good Bots
0 - Banned
Generally first determine how to catch the form...
if ($_SERVER['REQUEST_METHOD']=='GET')
{
}
else if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['submit_button_name_value'])) {blog_post_ajax_comment();}
}
I add the name="value" attribute/value to submit buttons, why? Have two submit options (preview and publish in example) you may want to have the server trigger one function or the other, VERY simple and valid (X)HTML.
You should check if the variable isset (keep permissions in mind).
Then check if their user permissions are adequate, you can use a simple integer to represent this.
Then wrap the isset and permission if statements around two things, one the form and secondly make sure you use these conditions when PROCESSING the form.
I always test against things to reject and throwing in database query error handling to give you a little extra boost...
//function module_method_ajax_purpose()
function blog_post_ajax_comment()
{
if (!isset($_SESSION['member'])) {http_report('403',__FUNCTION__,'Error: you must be signed in to do that.');}
else if ($_SESSION['member_status']<=4) {http_report('403',__FUNCTION__,'Error: permission denied; your account has been flagged for abuse.');}
else if (flood_control($datetime,'60')!=1) {http_report('403',__FUNCTION__,'Error: you can only post a comment once every X seconds.');}
else if (!isset($_POST['post_form_name_1']) || !isset($_POST['post_form_name_2'])) {http_report('403',__FUNCTION__,'Error: permission denied.');}
else
{
// NOW process
$query1 = "SELECT * FROM table";
$result1 = mysql_query($query1);
if ($result1)
{
//successful, increment query number for further queries
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
}
Error reporting is VERY powerful, use it for HTTP, JavaScript, PHP and MySQL. You could also benefit from my answer about real-time log reading here: jQueryUI tabs and Firefox: getBBox broken?
I run a fantasy basketball league. My php website/sql database is designed to let the person running the team do everything through the website - they can waive a player, and the player automatically goes into the FA pool, etc.
Everything has worked perfectly until about a week ago. Anytime now that a team goes to sign a player, after clicking "Sign", they get a blank PHP page. I have no idea why - I have made no adjustments to any files. It just started happening. Below is the code for the blank PHP page - can someone help?
<?php
$username = "me";
$password = "mypassword";
$database = "mydatabase";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$Team_Offering = $_POST['Team_Name'];
$Fields_Counter = $_POST['counterfields'];
$Roster_Slots = $_POST['rosterslots'];
$Healthy_Roster_Slots = $_POST['healthyrosterslots'];
$Type_Of_Action = $_POST['Action'];
$queryt="SELECT * FROM nuke_ibl_team_info WHERE team_name = '$Team_Offering' ";
$resultt=mysql_query($queryt);
$teamid=mysql_result($resultt,0,"teamid");
$Timestamp = intval(time());
// ADD TEAM TOTAL SALARY FOR THIS YEAR
$querysalary="SELECT * FROM nuke_iblplyr WHERE teamname = '$Team_Offering' AND retired = 0 ";
$results=mysql_query($querysalary);
$num=mysql_numrows($results);
$z=0;
while($z < $num)
{
$cy=mysql_result($results,$z,"cy");
$cyy = "cy$cy";
$cy2=mysql_result($results,$z,"$cyy");
$TotalSalary = $TotalSalary + $cy2;
$z++;
}
//ENT TEAM TOTAL SALARY FOR THIS YEAR
$k=0;
$Salary=0;
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
if ($Check == "on")
{
if ($Type_Of_Action == "drop")
{
if ($Roster_Slots < 4 and $TotalSalary > 7000)
{
echo "You have 12 players and are over $70 mill hard cap. Therefore you can't drop a player! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
}else{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '1000', `droptime` = '$Timestamp' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$topicid=32;
$storytitle=$Team_Offering." make waiver cuts";
$hometext="The ".$Team_Offering." cut ".$playername." to waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
} else {
if ($players_team == $teamid)
{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
} else {
if ($Healthy_Roster_Slots < 4 and $TotalSalary + $Salary > 7000)
{
echo "You have 12 or more healthy players and this signing will put you over $70. Therefore you can not make this signing. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots > 3 and $TotalSalary + $Salary > 7000 and $Salary > 103) {
echo "You are over the hard cap and therefore can only sign players who are making veteran minimum contract! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots < 1) {
echo "You have full roster of 15 players. You can't sign another player at this time! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} else {
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `bird` = '0', `cy` = '1', `cy1` = '$Salary', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
}
}
}
$k++;
}
?>
Put the following right after the open PHP tag:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
If this doesn't work, there is a probably a parse error and then you'll need to check the error log.
You will also need to escape your values that you are putting in the queries. This maybe causing a MySQL query to fail. If someone puts a " in $_POST['Team_Name'] your first query may fail.
Another final possible problem: are you sure it can still connect to MySQL?
An option to find the problem is commenting out large portions of code and then piece by piece uncommenting sectons.
Edit: So your first problem is the mysql_connect line. It needs to be changed to, notice the quotes: mysql_connect('localhost',$username,$password); Also, the variable $result and $queryt are spelt wrong in this line and used in their correct spelling: $resultt=mysql_query($queryt); I haven't checked the rest, but there maybe other errors that will cause your script to break. Some of the errors list are important to fix, but won't break your script.
Escaping: Check out the following page: http://php.net/manual/en/function.mysql-escape-string.php This basically prevents people from deleting your entire database.
Check the sample code on this page to find out how to connect to MySQL and check to see if you are connected.
Another suggestion: Are you sure none of your queries are failing? You probably want to check if the result from query is false before continuing, like:
if ($resultcat2 === false) {
trigger_error('query failed ' . $sql, E_USER_ERROR);
echo 'Sorry, there was a problem processing your request. Please try again later.';
exit;
}
Turn error reporting on for PHP in your php.ini file and see if any errors or warnings are reported. Also try removing the trailing whitespace at the end of the file before the last ?>, this has caused problems for me in the past.
Added comments to some of the above responses. Please try to dumb down for me as much as possible - I'm extremely new to this. I can't figure out why it would suddenly stop working, though, when I've made no changes at all to the code.
If you made no changes to any files and it just "broke" then that would indicate that either your webhost went thru a configuration change, your database got hosed somehow, or that someone else may've changed something.
To help spot the culprit, after every one of these
if{
else{
while{
or/and after every few statements (statements end with a semicolon ;) add this to the next line
print "<br> made it to this label: some_unique_label_name_here";
Where you should replace the label each time to help you trace the code.
This will be your first step into debugging the script to figure out how far the code execution is reaching.
Without going through your code in too much detail,I would suggest you look for any sections that may loop for a long time,without returning
After enabling error reporting, make sure to put in else statements that correspond with all of your if-statements so you can determine if those statements are being triggered or not. Throw in some echos.
Also, to clarify - I have probably three dozen PHP files on the site - this is the ONLY one that has stopped working.
As an aside, you should change every variable from a get or post such as:
$Team_Offering = $_POST['Team_Name'];
to
$Team_Offering = mysql_real_escape_string($_POST['Team_Name']);
before using it in a mysql query, otherwise you are vunerable to SQL injection attacks.
This is where I got...everything below the print line wouldn't show up if I put the print line below it.
$k=0;
$Salary=0;
print "<br> made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
So an update...nothing. lol
If you review this code:
$k=0;
$Salary=0;
print " made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
If I put the print statement below while, the page goes blank and it doesn't show up. If the print statement is before while, the statement shows up but there's no action made on the page. The end result is that when running this page, the player selected on the previous page should be removed from Free Agents, added to the user's team, and a story should be posted on the front page announcing it. Obviously none of those are happening here.