Jump to content

Chips

Members
  • Posts

    68
  • Joined

  • Last visited

    Never

Posts posted by Chips

  1. It works when the code is this:
    [code]$query = mssql_query("SELECT * from " . _CONTENTDB_ . "  where section = (SELECT section from " . _SECTIONSDB_ . " where sectionName = 'news') AND date BETWEEN '2006-06-01' AND '2006-06-31' ORDER BY date DESC;");[/code]

    But if I try to make a $date1 and $date2 to replace the two dates inputted, it no longer works. Any suggestions anyone at all?

    Tried:[code]
    where sectionName = 'news') AND convert(varchar, date) between '$date1' AND '$date2'[/code]

    [code]
    where sectionName = 'news') AND date between convert(datetime, $date1) AND convert(datetime, $date2)[/code]

    The $date1 is made up of a concatenated variables -
    [code]$date1 = $year . $month . $day;[/code]
    But also:
    [code] $date1 = $year . "/" . $month . "/" . $day;
    $date1 = $year ."-".$month."-".$day;
    [/code]
    All have been tried, fiddled and experimented.
    Can't seem to work out how this should be done, any help grateful.
  2. Trying to create a news archive where a user can view news items from a month. In other words, select the month/year and all the news items from the 1st of that month until the 31st of that month will be returned.

    [code]$query = mssql_query("SELECT * from " . _CONTENTBD_ . " where section = '2' and date BETWEEN  $date1 AND $date2[/code]

    The DATE field is in smalldatetime format - so yielding yyyy-mm-dd hh:mm:ss. Obviously the ss is always 00 being a smalldatetime format.

    Currently the user has two drop down html boxes with the months (1-12) and years (current year onwards only, so 2006 available at the moment).
    Code for calculating my dates is:
    [code]$date1 = $year ."/". $month ."/01";
        $date2 = $year ."/". $month ."/31";[/code]
    Obviously yields yyyy/mm/dd as the format. I have tried this, or with dashes as well. I have also done that with adding 00:00:00 to the above dates to give a format of yyyy/mm/dd hh:mm:ss as well (matching the datetime field).
    My query, obviously, returns nothing. There are 3 news items with dates between my values, and none are brought back. I have tried doing a convert, but found no real documentation that helped too much (Trying to convert the date field to a varchar and then see if it's between the two dates, which I assume are string formats at the present time) but this didn't appear to work (problem being I don't know if i executed this correctly).
    I've spent quite some time searching the web and forums too - found similar problems, but using mysql instead of mssql - and their solutions haven't worked for me either!

    Any suggestions, hints, tips or pointers would be highly appreciated. Having spent the best part or 2 hours fiddling, it's obviously hit the time where any more time will be wasted without help :(
  3. EDIT: Fixed it myself, stupid mistake of not thinking :/ Obviously value=" <?php blah blah ?>" solves it. What a numpty.


    My issue lies with inserting a value from the database into a value for an input field - as so:
    [code]
    <tr><td>Last Name:</td><td><input type='text' value='<?php echo $rows['lname']; ?>' name='lnameEDIT'/></td></tr>
    [/code]

    The issue is that when I am obtaining a value from the database that includes a ' character, it cuts off the value right there. If I echo the value to the page, it comes out correctly (as in o'neil), but if I try to put the value of the input field as (o'neil), it just get (o)... effectively disregarding everything after the ' character.

    I cannot find out how to output the field value with this character, tried using addslashes, but it adds a slash, but still cuts off everything from ' onwards.

    Has anyone got any suggestions/work arounds. I think its with the input field not taking a ' in a value, not php itself - just looking for a solution!

    Thanks
  4. Hello, having some trouble with this one. Checked the php.net topics for anything, nothing can be found. tried using "addslashes()" but that doesn't seem to work either!

    So can anyone give me any quick pointers on what characters need to be escaped, and if they know of any functions that do this (integrated in php) or whether i'll have to use a different function and tailor it or not.

    Especially relevent to:

    Preventing sql injection attacks on mssql database (dunno how, but guessing ensuring they can't insert sql statements into queries that are just supposed to insert data instead!).
    Allowing users names like O'Donnel etc
    Allowing users to put ! ? " - ' ; : etc inside comments sections that will be logged into a database table.

    Unfort having massive trouble finding any information with regards to mssql, and plenty on mysql that just doesn't work (tried addslashes and nothing was entered when putting ' into a string of text!).

    Many thanks if anyone can help out.
  5. [code]$msg = "There is an error";
    }
    if (!isset ($error
    [/code]

    I don't see where $error is set...

    Also, why not just do this instead of setting the message variable?
    [code]
    if(form data was empty){
    echo "There is an error";
    exit();
    } else {
    process here;
    }
    [/code]

    If you wish to show the form again, you could stick the form as being part of a function, and call the function when the page is loaded. If post data is no of value, and it was submitted, instead of exit instantly - it could just call the function to display the form once more...
  6. I have a page, where users can log in etc

    The main page is called index.php, and within this page it has the login.php/loggedin.php - which is just a user login form, or the menu if they are already logged in. The below is a basic version of what I have (obviously more layout code on my proper version).

    [code]
    <?php //index.php
    session_start();
    ?>

    <table>
    <tr>
    <td> <?php
    if($_SESSION['access']) {
    include 'loggedin.php';
    } else {
    include 'login.php'
    }
    ?></td>

    <td><?php include '$page'; ?></td>

    </tr></table>
    [/code]


    When a user logs in successfully, the "verify.php" will redirect them back to the index.php page again as follows:

    header('location: index.php');

    Obviously they will have had a session created for them, holding their access level inside it. When they get redirected, the $_Session['access'] will include the loggedin.php instead of login.php, so they see their user menu instead.

    The problem is when someone tries to login and fails. How would I go about showing them an error message for why it failed? Right now I've just done it so that the redirect for failure is:
    [code]header('location: index.php?error=1');[/code]
    Obviously the value is 1 or 2 depending upon whether no such email exists in database, or if the password doesn't match the stored version.

    When a user gets to the page I had added this:
    [code]
    <?php //index.php
    session_start();

    switch($_REQUEST['error']) {
    case '1' : $content = "Login failed as no email exists";
    break;

    case '2' : $content = "Login failed as password doesn't match";
    }
    <table>
    <tr>
    <td> <?php
    if($_SESSION['access']) {
    include 'loggedin.php';
    } else {
    include 'login.php'
    }
    ?></td>

    <td><?php
    if(isset($content)) {
    echo $content;
    } else {
    include '$page';
    }
    ?></td>

    </tr></table>
    [/code]

    Now this will display the error message, but I am concerned that I am not handling this in the best way possible. The difficulty I am having is that my pages are based around a page with includes in it - for different content.
    The include '$page'; is actually drawn from a database, where $page is the name of the file returned by a query dependant upon the id of said item - so that things like register forms can be brought up in the area. Does anyone have any suggestions or thoughts about my method? I'm trying to make it dynamic, so that one page can load lots of different cotent in it (for example, the links in logged in are actually index.php?id=2 in format, and id=2 is what content will result in being etc, or the register link si actually index.php?id=5 - where id 5 is actually the file named register.php, which is assigned to the $page value, and therefore included).

    If this makes no sense, I'll try to clear it up further on request :)
  7. Essentially i am trying to check my forms content to ensure that nothing is in the wrong places - eg, telephone numbers are actual numbers, emails are email address etc.

    I am having trouble with other fields where i just want to have a-zA-Z0-9... and spaces.
    Does anyone know how I allow spaces? I have a text area where strings of non solid text will be entered (ie, strings containing spaces between words!) - but checking them as a-zA-Z means that spaces = error.

    Seeing as I am also using mssql as my database, I am concerned about sql injection, and so am wondering how i can "escape" characters that may be troublesome like ', " etc etc. I know addslashes works for mysql - but i am not sure that this escapes characters such as this in mssql - does anyone know?

    Many thanks for any suggestions/pointers/help.
  8. For a login system, I used a method of checking the username/password against the database. If it matches up, then i set them a session with an id number.

    For any page, i start with with something along the lines of:
    [code]if(!isset($_SESSION['userid'])) {
    die("No access to this page");
    }

    [/code]

    Now this may not be the best idea in existance at all, indeed it may be a massive issue - I just don't know (so if anyone comments on this with knowledge, a heads up as well would be much appreciated), however, if they don't have a session set - then they see "No access to this page". Replace this with:
    [code]
    header('location: login.php');
    [/code]
    Sends them to the login page.
  9. Not really used dates much myself, so not exaclty sure how they are evaluated.

    However:
    [code]
    $today = time();

    $query = "SELECT account_expire FROM user WHERE account_expire < $today";
    $result = mysql_query($query);

    while (list($account_expire) = mysql_fetch_row($result))
        {

        $query = "UPDATE user SET confirmed = '2' WHERE ($account_expire < $today)";
            $result = mysql_query($query);
        }
    [/code]


    I don't understand why you don't just role it all into one query?
    [code]
    $sql = mysql_query("Update tablename SET confirmed = '2' where account_expire < '$today';");
    [/code]

    Course, i may be totally wrong with that just there, but looks okay to me!
  10. [code]
    $query = "Select * from ".$DBprefix."client_info where id='$actnum'";
    $result = mysql_query($query);
    if ($row = mysql_fetch_array($result)){
    if ($row["id"] == $actnum)
    }
    }
    [/code]
    Personally, and I haven't tried this, you should be able to do this:
    [code]
    $query = "Select * from ".$DBprefix."client_info where id='$actnum'";
    $result = mysql_query($query);
    $row = mysql_num_rows($result); //number of rows returned as matching.

    if($row) {
       //carry out a repeat id generation perhaps, and then call function again?
    } else {
       //do whatever you like if the number isn't taken, as in insert into database etc.
    }
    [/code]
    $row = number of rows returned matching your query.
    if(0) - or no matches, then expression if($row) will evaulate to false, as it's if(0) which is false!
    if(1) - or if the number of matching rows is greater than 0, it will evaluate this expression to true.

    HOwever, as mentioned above, if it's a unique id number, i would just go with making that field your primary key, and autoincrementing it. IE - you won't actually insert anything into that field, just insert the details instead and it will automatically fill in the field with a unique identifier upon insertion of the other fields information.
  11. [!--quoteo(post=383743:date=Jun 14 2006, 07:51 AM:name=Sorthy359)--][div class=\'quotetop\']QUOTE(Sorthy359 @ Jun 14 2006, 07:51 AM) [snapback]383743[/snapback][/div][div class=\'quotemain\'][!--quotec--]
    how would i select that from the db and echo it?

    im using this on the menu as an example but i plan to use this for userinfo.php for admins ;)

    this below outputs
    [code]
    Admin
      Admin Center  
    (test) Your IP: Resource id #15[/code]

    here is the code.
    [code]
       if($session->isAdmin()){
          $q2 = "SELECT ip FROM users WHERE username = '$session->username'";
          $result2 = mysql_query($q2);
          echo "<br><b>&nbsp;&nbsp;<u>Admin</u></b><br>&nbsp;&nbsp;<a href=\"admin/admin.php\">Admin Center</a> &nbsp;&nbsp;";
          echo "<br>(test) Your IP: $result2";
       }
    [/code]

    ..what did i do wrong with that SELECT line? :(
    [/quote]

    All you've done is carry out a query, not actually returned the value itself. For that you'd need an extra line or two - like this:
    [code]
    $q2 = mysql_query("SELECT ip FROM users WHERE username = '$session->username';");
          $result2 = mysql_result($s2, 0, "ip");
    echo $result2;
    [/code]
    The mysql_result(your query, num, field name)
    num is representative of the number of returned results. There should be only 1, but if you returned (for strange example) 200, you could do a loop with this set to a variable as:
    [code]

    for($i=0; $i < msql_num_rows($q2);$i++) {
    echo mysql_results($s2, $i, "ip") . "<br />";
    }
    [/code]

    That [i]should[/i] print out a list of IP address that match (for example if you selected everything from the database instead, without any parameters). You have parameters to your query to return just one result, hence the 0 being used.

    Hope that works, if I am wrong I am sure someone with more competance will reply shortly :)
  12. [code]$sql = 'UPDATE "users" SET "ip" = "$userip" WHERE "username" = "$session->username"';
       mysql_query( $sql ); [/code]

    Not overly familiar with mysql, but in mssql the below would be correct. I assume that mysql is near identical.

    [code]$sql = "UPDATE users SET ip = '$userip' WHERE username = '$session->username';";
    [/code]

  13. As you may have guessed by the title, I am not profficient in php at all - I am learning as I go along. Indeed, I learnt the login system via a tutorial on this very site (which was excellent) - however, I am expanding parts of the tutorial.

    Essentially I have my login pages, verify, validate (for registering) register, etc - but once a user is logged in I am trying to create a profile area where they can access their personal profile.

    I have done this, but am worried that the coding and way of implementation leaves a lot to be desired, hence my asking. The code is below, essentially if a user clicks on a link to their profile once logged in, they get taken to the profile.php page (I use sessions during the log in process). Different parts of the script will be loaded dependant upon what the user is wanting to do.

    Here is the file overall:

    [code]<?
    session_start();
    include 'db.php';

    /*
    * This will be the profile page for users to change passwords to more acceptable passwords.
    * User not logged in will be sent straight back to the login form.
    */

    //check if session exists...
    if($_SESSION['access_level']) {     //if not
      //send them to the login page!
      header('location: http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/login.php');
      exit();
    }

    /*
    * If a user wants to change their password, this is the code from here down. First it will provide a
    * form for the user to log in via the same page. After this, it will then take the value of the password
    * entered in the form and change their password accordingly. Finally user is returned back to their profile area
    * as per the code below this section.
    */

    //check whether the request of change password was past or not.
      if($_REQUEST['change_password']) {
         echo "<form name=\"change_pass\" action=\"profile.php\" method=\"post\"><span>Enter new password:</span><input type=\"password\" name=\"password\" value=\"\"/><br /><span>Verify new password:</span><input type=\"password\" name=\"password2\" value=\"\"/><br /><input type=\"submit\" value=\"change\" /></form>";
         exit();
      }
      
      //check whether a post value for password has been received.
      if($_POST['password']) {
        $password = md5($_POST['password']);
        $password_check = md5($_POST['password2']);
        if($password != $password_check) {
          echo "passwords did not match, please try again.<br />
          <a href=\"profile.php?change_password=true\">Try again</a>";
          exit();
        }
        $userId = $_SESSION['user_id'];
        $email = $_SESSION['email_address'];
        $sql_update = mysql_query("UPDATE users SET password = '$password' where userId = '$userId' and email = '$email';");
        $sql = mysql_query("SELECT userId FROM users WHERE userId = '$userId' and password = '$password' and email = '$email';");
        $sql_check = mysql_num_rows($sql);
             if($sql_check > 0) {
                     echo "<p>Password update succcessful</p>
                     <a href=\"profile.php\">My Profile</a>";
                     exit();
             } else {
                     echo "Password update has failed";
                     header('location: http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/profile.php');
                     exit();
             }
        }
        
        
        /*
        * Default display for when a user first logs into their area.
        */
        $name = $_SESSION['first_name'];  //get the users name
        
        //provide the html links for the user to choose what to do.
        echo "<p>Welcome $name, this is your personal profile area.</p>
        <a href=\"profile.php?change_password=true\">Change password</a><br />
        Link 2<br />
        Link 3<br />
        Link 4<br />
        <a href=\"logout.php\">Logout</a>";

    ?>[/code]

    Mainly these bits - if a user clicks on this link:[code]
    <a href=\"profile.php?change_password=true\">Change password</a><br />[/code]
    You can see it links back to this page but with a request of change_password=true.
    This in turn will load up this part of the script:
    [code]if($_REQUEST['change_password']) {
         echo "<form name=\"change_pass\" action=\"profile.php\" method=\"post\"><span>Enter new password:</span><input type=\"password\" name=\"password\" value=\"\"/><br /><span>Verify new password:</span><input type=\"password\" name=\"password2\" value=\"\"/><br /><input type=\"submit\" value=\"change\" /></form>";
         exit();
      }[/code]

    Essentially it loads the page with two password text boxes. The user inserts their password twice and hits submit. When submitted it submits to the same old profile.php once more - where it should be picked up by this part:[code]if($_POST['password']) {
        $password = md5($_POST['password']);
        $password_check = md5($_POST['password2']);
        if($password != $password_check) {
          echo "passwords did not match, please try again.<br />
          <a href=\"profile.php?change_password=true\">Try again</a>";
          exit();
        }
        $userId = $_SESSION['user_id'];
        $email = $_SESSION['email_address'];
        $sql_update = mysql_query("UPDATE users SET password = '$password' where userId = '$userId' and email = '$email';");
        $sql = mysql_query("SELECT userId FROM users WHERE userId = '$userId' and password = '$password' and email = '$email';");
        $sql_check = mysql_num_rows($sql);
             if($sql_check > 0) {
                     echo "<p>Password update succcessful</p>
                     <a href=\"profile.php\">My Profile</a>";
                     exit();
             } else {
                     echo "Password update has failed";
                     header('location: http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/profile.php');
                     exit();
             }
        }[/code]

    Obvioulsy passwords are hashed before being entered into database, and checked to ensure they match.
    The question is - is this good or bad practice to keep linking back to the same file but just to different portions of it? If it's okay, is there a better way to execute this behaviour than the way I have done (for example by directing them to the profile.php?change_password=true)? Same for the form too - is that okay?
    I've done a similiar thing with my login.php script where if a session exists, then you don't get the login form - but instead a greeting and a link to the profile.php and a logout link instead.

    Furthermore, the use of echo to print out things in combiation with a header(location: ) doesn't seem to go down well. One or the other works fine, but not both... so is using an include right for the behaviour of (say) displaying the profile page again but with an added message of changing passwords failed or something?

    Any hints/tips/comments/critique/suggestions etc are very welcome, and I will post up any of the code requested. I am programming this for a small company at the moment, and I want to not only make the best job I possibly can... but to also learn [i]good[/i] practices too! Although the finished deal is a long way off and this is just the ugly implementation of it, I need all the help I can get to make sure I don't miss/mess up/botch things up.

    Also - the login is via email/password. The email is checked to be a valid email address (via a check of the characters making it up), and the password hashed and checked against the stored hashed password. Is this safe against an sql_injection type of attack without needing to do the slashes issue?

    And lastly, there is no way for anyone to read your php files are there from a browser? It's a server side executed language, so the script isn't transmitted, only the data generated right?

    Here's hoping for some tips/thoughts etc, and thanks for taking the time to read the post.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.