by Alast
12 replies
I'm having terrible trouble with two of my scripts. They are frustrating me to the point of quitting (joking, but seriously). You need to bear (bare?) in mind that I'm a complete beginner to this crap, so there may be some simple solution. That being said, I've had several people try and figure out what was going on, particularly with the search script, but no solution was found.

We'll start with the friend system:

PHP Code:
<?php
    error_reporting
(E_ALL);

    require_once(
"sSQL.php");
    
login1("localhost""root""""users");

    
$id "1";
    
$u_id $_GET['id'];
    
$s $_GET['s'];
    
$back $_SERVER['HTTP_REFERER'];
    
$ip $_SERVER['REMOTE_ADDR'];

    
$a mysql_query("SELECT * FROM `friends` WHERE `user_id`='$id' AND `friend_id`='$u_id' OR `user_id`='$u_id' AND `friend_id`='$id'") or die(mysql_error());
    
$b fetch($a);
    
$c num($a);
    
$user_id $b['user_id'];
    
$friend_id $b['friend_id'];
    
$stage $b['stage'];

    if(
$c == 0)
    {
        
// they're not friends, but id wants to be friends.
        
if($s == 1)
        {
            
// Add friend
            
mysql_query("INSERT INTO `friends` (`user_id`, `friend_id`, `stage`, `ip`) VALUES ('$id', '$u_id', '$s', '$ip')")or die(mysql_error());
            
header("Location: $back");
        }
    }
    else
    {
        
// remove request sent
        
if($id == $user_id && $stage == 1)
        {
            
mysql_query("DELETE FROM `friends` WHERE `user_id`='$id' AND `friend_id`='$u_id' AND `stage`='1'") or die(mysql_error());
            
header("Location: $back");
        }
        else
        if(
$id == $friend_id && $stage == 1)
        {
            
// Ew, I don't wanna be your friend.
            
mysql_query("DELETE FROM `friends` WHERE `user_id`='$u_id' AND `friend_id`='$id' AND `stage`='1'") or die(mysql_error());
            
header("Location: $back");
        }
        else
        if(
$u_id == $friend_id && $s == 2)
        {
            
// okay, let's be friends. I'll accept.
            
mysql_query("UPDATE `friends` SET `stage`='$s' WHERE `user_id`='$u_id' AND `friend_id`='$id' AND `stage`='1'") or die(mysql_error());
            
mysql_query("INSERT INTO `friends` (`user_id`, `friend_id`, `stage`, `ip`) VALUES ('$id', '$u_id', '$s', '$ip')")or die(mysql_error());
            
header("Location: $back");
        }
        else
        if(
$id == $user_id && $stage == || $id == $friend_id && $stage == 2)
        {
            
// Screw you, I'm deleting you!
            
mysql_query("DELETE FROM `friends` WHERE `user_id`='$u_id' AND `friend_id`='$id' AND `stage`='2'") or die(mysql_error());
            
mysql_query("DELETE FROM `friends` WHERE `user_id`='$id' AND `friend_id`='$u_id' AND `stage`='2'") or die(mysql_error());
            
header("Location: $back");
        }
    }
    if(
$s == 3)
    {
        
// Block the scum!!!
        
mysql_query("DELETE FROM `friends` WHERE `user_id`='$u_id' AND `friend_id`='$id'") or die(mysql_error());
        
mysql_query("DELETE FROM `friends` WHERE `user_id`='$id' AND `friend_id`='$id'") or die(mysql_error());
        
mysql_query("INSERT INTO `friends` (`user_id`, `friend_id`, `stage`, `ip`) VALUES ('$id', '$u_id', '$s', '$ip')")or die(mysql_error());
        
mysql_query("INSERT INTO `friends` (`user_id`, `friend_id`, `stage`, `ip`) VALUES ('$u_id', '$u_id', '$s', '$ip')")or die(mysql_error());
        
header("Location: $back");
        
        
    }
?>
PHP Code:
<?php
    error_reporting
(E_ALL);

    require_once(
"sSQL.php");
    
login1("localhost""root""""users");

    
$a mysql_query("SELECT * FROM `friends` WHERE `user_id`='$id' AND `friend_id`='$user_id' OR `user_id`='$user_id' AND `friend_id`='$id'") or die(mysql_error());
    
$b fetch($a);
    
$c num($a);
    
$user_id2 $b['user_id'];
    
$friend_id $b['friend_id'];
    
$stage $b['stage'];
    if(
$id != $user_id) {
    if(
$c == 0)
    {
        
// Add friend!
        
echo "<a href='request.php?id=$user_id&s=1'>Add Friend</a>";
    }
    else
    {
        if(
$id == $user_id && $stage == 1)
        {
            
// Cancel friend request
            
echo "<a href='request.php?id=$friend_id&s=1'>Remove Request</a>";
        }
        else
        if(
$id == $friend_id && $stage == 1)
        {
            
// Don't accept friend & Accept
            
echo "<a href='request.php?id=$user_id2&s=2'>Accept</a>";
            echo 
"<a href='request.php?id=$user_id2'>Decline</a>";
        }
        else
        if(
$id == $user_id && $stage == || $id == $friend_id && $stage == 2)
        {
            
// Remove friend
            
echo "<a href='request.php?id=$user_id2'>Remove as friend</a>";
        }
    }
    
// Block..........
    
echo "<a href='request.php?id=$user_id&s=3'>Block</a>";
    }
?>
Firstly, you need to understand that I didn't create this myself, I had someone with more experience help me out, but he got himself stuck so left it for someone else to fix up. I'll be honest, I don't really understand what's going on, but basically, I want it to be a standard friend system. That being where you can send a request, delete a request, block the user, etc.

Now, for the search script:

PHP Code:

<?php  
        
if (isset($_POST['search'])) {
                
$searchq $_POST['search'];
               
                
$query mysql_query("SELECT * FROM users WHERE first_name = '$searchq' OR last_name= '$searchq'") or die("An error occurred.");
                
$count mysql_num_rows($query);
                if (
$count == 0) {
                        
$output 'There were no search results!';
                } else {
                        while(
$row mysql_fetch_array($query)) {
                                
$fname          $row['first_name'];
                                
$lname          $row['last_name'];
                                
$user_id        $row['user_id'];
                               
                                echo 
'<div> '.$fname.' '.$lname.'</div>';
                        }
                }
    print(
"$output");
}
    
?>
It works to an extent. That being it allows you to search their first or last name to get a result, but if you search the full name, then it returns as an error. I need it where you have the ability to search a full name and it returns with that specific name.

If you know any of these solutions, please explain to me what is going on so maybe I can grasp what's happening. Right now PHP is a blur. To put this into perspective:

Try speaking a language you've never seen before.

That is what I feel like at the present time.

I'd also like to ask a question, how long before someone beginning can begin to actually make scripts without the need of tutorials and/or assistance? I've been learning for 3~ weeks, but in total in terms of hours, probably around 24-48 hours has been spend creating/learning scripts. I can understand things like...

PHP Code:
if($ == 1) {
echo 
"friends";
} else if($ == 
2) {
echo 
"not friends";

Any more than that I get lost.

Thanks!
#php #troubles
  • Profile picture of the author Andrew H
    Well.

    1. This script is wide open to sql injection; your friend that made it should be thrown out a window Never put user input directly into an sql query. You should use PDO or you can use a PHP extension like mysql_real_escape_string

    PDO:PHP: PDO - Manual
    mysql_real_escape_string - PHP: mysql_real_escape_string - Manual

    No time to deal with the rest now...
    Signature
    "You shouldn't come here and set yourself up as the resident wizard of oz."
    {{ DiscussionBoard.errors[8418268].message }}
  • Profile picture of the author yestyle
    Banned
    I see you got problem with database, why you don't use database class for that. Also I suggest you use template engine for your website like smarty or x-template. It's easy to develop a big website in short time.
    {{ DiscussionBoard.errors[8418326].message }}
    • Profile picture of the author 723Media
      There are quite a few problems with the first script. Without knowing exactly what it is you want this to do, it's going to be hard to tell you how to fix it.

      Your second script has a more specific requirement of being able to search on first name, last name or full name. Assuming you want to match a broad set of results (first name, last name OR full name):

      Note: This is not taking into account that you need to sanitize the user input

      SELECT * FROM users WHERE (first_name LIKE '%$searchq%') OR (last_name= '%$searchq%') OR (CONCAT(first_name, ' ', last_name) LIKE '%$searchq%')

      If you want to return exact matches, you'll switch from using "LIKE" to =.

      If you do that, you should use an advanced search format to let the user select whether they want to search broad or exact results.
      {{ DiscussionBoard.errors[8420221].message }}
      • Profile picture of the author Alast
        Originally Posted by 723Media View Post

        There are quite a few problems with the first script. Without knowing exactly what it is you want this to do, it's going to be hard to tell you how to fix it.

        Your second script has a more specific requirement of being able to search on first name, last name or full name. Assuming you want to match a broad set of results (first name, last name OR full name):

        Note: This is not taking into account that you need to sanitize the user input

        SELECT * FROM users WHERE (first_name LIKE '%%') OR (last_name= '%%') OR (CONCAT(first_name, ' ', last_name) LIKE '%%')

        If you want to return exact matches, you'll switch from using "LIKE" to =.

        If you do that, you should use an advanced search format to let the user select whether they want to search broad or exact results.
        It works, but for some reason I'm getting an error;

        Notice: Undefined variable: output in C:\wamp\www\includes\search_body.php on line 21
        {{ DiscussionBoard.errors[8420996].message }}
        • Profile picture of the author Brandon Tanner
          Originally Posted by Alast View Post

          It works, but for some reason I'm getting an error;

          Notice: Undefined variable: output in C:wampwwwincludessearch_body.php on line 21
          That error message means that the script is trying to use a variable that has not been "set" (ie the variable does not contain a value). So look on line 21 in search_body.php to find out what variable that is.
          Signature

          {{ DiscussionBoard.errors[8422870].message }}
          • Profile picture of the author 723Media
            Brandon Tanner is right, $output is undefined. The reason is this block:

            if ($count == 0) {
            $output = 'There were no search results!';
            }

            $output gets set within a conditional that first checks that there are no results returned from your query. Since you have results, this variable will never be set.

            You have 2 options.

            1. Declare $output at the opening of your first if statement and set it equal to ''.
            2. Move the print output into the if statement where you have $output declared now, print it and return so you can exit out of the code and stop processing.

            if ($count == 0) {
            print('There were no search results!');
            return;
            }
            {{ DiscussionBoard.errors[8424290].message }}
  • Profile picture of the author Alast
    I got it. I just have one problem now, if I search nothing, it output's all the member's from the database. How do I stop this?

    Thanks for the help though!
    {{ DiscussionBoard.errors[8425109].message }}
    • Profile picture of the author David Beroff
      Originally Posted by Alast View Post

      I just have one problem now, if I search nothing, it output's all the member's from the database. How do I stop this?
      Assuming you're using 723Media's approximate search ("LIKE") approach, this makes sense: you are saying to the database, show me everyone whose name contains this string, and when the search string is nothing, (0-length), then everyone's name "has" nothing. The easiest way to fix this is to simply require that the search string has a minimum length.

      To echo what others have said above:

      1. It's great that you are learning PHP and MySQL, but you might want to consider smaller projects until you are more comfortable before attacking something like this. In the meantime, I find that oDesk is a great, cheap way to work on projects where I don't yet know something, and then I get to learn by watching what the outsourcer does.

      2. You definitely need to learn more about SQL injection, or you risk losing your entire website. e.g.,


      (Source)
      Signature
      Put MY voice on YOUR video: AwesomeAmericanAudio.com
      {{ DiscussionBoard.errors[8425328].message }}
  • Profile picture of the author Alast
    My main focus on building this website is to learn, however, at the same time, I want to actually have created something which I am proud of. I would lose all motivation if I was creating pointless things -- I learn at my best if I tackle larger projects, and then the smaller things will come naturally, especially if I have to learn something smaller in order to achieve something larger. In terms of the SQL injection, where would that be the issue in terms of these two scripts? I would genuinely like to know. Also, there are many free tutorials which I learn off, so for now I'll give oDesk a miss. :]
    {{ DiscussionBoard.errors[8425603].message }}
  • Profile picture of the author Andrew H
    You seem to not understand the issue of sanitizing your inputs. What everyone is saying, politely, is that you need to STOP what you are doing now and go read about sql injection. When programming one of your primary concerns must always be security. The way your code is above any user can exploit your whole database (get all username and password hashes - assuming you even hashing passwords?, drop all the tables in your databases, etc.).

    This is why nobody is answering your original question, because as soon as we see the unsanatized user input going directly into the sql query we cringe.

    So here is your homework: https://www.owasp.org/index.php/SQL_Injection

    Don't come back here asking questions about why your query isn't returning the proper results until you understand sql injection.
    Signature
    "You shouldn't come here and set yourself up as the resident wizard of oz."
    {{ DiscussionBoard.errors[8425942].message }}
    • Profile picture of the author phpg
      Let me just show.

      Let's assume that your page is http://example.com/index.php

      What will happen if i open it in browser like this:

      http://example.com/index.php?id=1%27+or+1%3D1%3B+--+

      You have this line:

      $u_id = $_GET['id'];

      Urldecoded 1%27+or+1%3D1%3B+--+ is 1' or 1=1; --

      So, now $u_id = "1' or 1=1; -- ";

      Then, you have this line:

      mysql_query("DELETE FROM `friends` WHERE `user_id`='$u_id' AND `friend_id`='$id' AND `stage`='1'");

      Replace $_uid with 1' or 1=1; -- and you get:

      mysql_query("DELETE FROM `friends` WHERE `user_id`='1' or 1=1; -- ' AND `friend_id`='$id' AND `stage`='1'");

      Everything after ; is not just ignored, but also commented out with -- .

      So you query is:

      DELETE FROM `friends` WHERE `user_id`='1' or 1=1

      What it will do - it will just delete everything in your friends table ...

      Go figure ...
      {{ DiscussionBoard.errors[8430274].message }}
  • Profile picture of the author jminkler
    I consulted on a website before with similar code problems. I advised that the input be sanitized, the owner told the developer, who never did it. His entire goal, project, life was taken down 3 months later by script kiddies who dumped the entire database, and trashed his hosted files.

    This code is pretty horrible, all of us can see that. Don't plan to have a site for long if this "goes live"

    Learn about Frameworks - Zend, Symfony, Yii, CodeIgnitor
    {{ DiscussionBoard.errors[8452236].message }}

Trending Topics