Page 1 of 2 12 LastLast
Results 1 to 20 of 23

Thread: Question for PHP/MySQL Wizards

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1

    Default Question for PHP/MySQL Wizards

    If there are any of you on this forum, I need a bit of help.

    I've been messing around with PHP for the last couple of days, so today I decided to try creating a login function on my website. I made a login.php file, and that went smoothly, except I need to create a MySQL db, and access it. The problem is, I haven't the foggiest what my password is. Is there a way to find out? I installed it a while ago to install an SMF forum to my server, and I can't remember for the life of me. I've tried everything, but, I keep getting errors. So does anyone know a way to find out?

    Also, I might as well post my code:

    Code:
    <?php
    $connect = mysql_connect("localhost","root","monkey901");
    if (!$connect)
      {
      die("Failed to connect: " . mysql_error());
      }
    ?>
    I can use localhost if MySQL is installed on the same machine, right? And if it matters, I'm using XAMPPLite, because finding a version of PHP and MySQL that worked together was impossible.
    Last edited by Bolkonsky; March 06, 2011 at 03:22 PM. Reason: localhose, lol
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  2. #2
    Simetrical's Avatar Former Chief Technician
    Patrician

    Join Date
    Nov 2004
    Location
    θ = π/0.6293, φ = π/1.293, ρ = 6,360 km
    Posts
    20,154

    Default Re: Question for PHP/MySQL Wizards

    If SMF works, then your MySQL password is probably somewhere in its configuration files. Go look there. Failing that, you can reset the root password.
    MediaWiki developer, TWC Chief Technician
    NetHack player (nao info)


    Risen from Prey

  3. #3

    Default Re: Question for PHP/MySQL Wizards

    Excellent! No more errors. I should have thought of that when I was looking over the active databases.

    My hearty thanks!

    EDIT: A quick follow-up question. If I create a database, every time the script runs, will it re-create and overwrite the database, or will it just return an error?

    2nd EDIT: Figured out by trial and error. In case anyone's wondering, it returned with:

    Error creating database: Can't create database 'users'; database exists
    Last edited by Bolkonsky; February 03, 2011 at 06:41 PM.
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  4. #4

    Default Re: Question for PHP/MySQL Wizards

    I've got another question, not directly related, but does anyone know how to direct apache to automatically add the file extensions? It does it with index.html, but for everything else, (like register) I have to manually add the .php
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  5. #5
    Simetrical's Avatar Former Chief Technician
    Patrician

    Join Date
    Nov 2004
    Location
    θ = π/0.6293, φ = π/1.293, ρ = 6,360 km
    Posts
    20,154

    Default Re: Question for PHP/MySQL Wizards

    Quote Originally Posted by Bolkonsky View Post
    I've got another question, not directly related, but does anyone know how to direct apache to automatically add the file extensions? It does it with index.html, but for everything else, (like register) I have to manually add the .php
    What do you mean? Give more details of what the problem is.
    MediaWiki developer, TWC Chief Technician
    NetHack player (nao info)


    Risen from Prey

  6. #6

    Default Re: Question for PHP/MySQL Wizards

    Hmmm...I was wondering if there was a way to not have to type the file extensions into the browser, but it seems as though there isn't, upon further investigation.
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  7. #7
    Dragooon's Avatar Centenarius
    Join Date
    Mar 2010
    Location
    NCR, India
    Posts
    807

    Default Re: Question for PHP/MySQL Wizards

    There is, simplest method would be apache's mod_rewrite although there are a lot more ways to do such things.

    Also, I wouldn't recommend creating the DB every time the script runs, it is a big waste of resources.

  8. #8

    Default Re: Question for PHP/MySQL Wizards

    Quote Originally Posted by Dragooon View Post
    There is, simplest method would be apache's mod_rewrite although there are a lot more ways to do such things.

    Also, I wouldn't recommend creating the DB every time the script runs, it is a big waste of resources.
    Ok, thanks, I'll look into that.

    Also, I rather guessed that, I'm just fooling around with it at the moment. When I actually finish everything, I'll remove that whole script, and just add data to the tables. Problem is, I don't have a monitor for my server, so this was just easier than remote desktop.
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  9. #9

    Default Re: Question for PHP/MySQL Wizards

    Does anyone know what variable types default to in PHP? For instance:

    PHP Code:
    while($row mysql_fetch_array($result)) 
    in that code, if $result has no value, will it default to an int?

    Also, do redirect (PHP) codes like this one have to go in <head></head> to work?


    PHP Code:
    <?php

       header
    'www.igmod.net/index.html' ) ;

    ?>


    Nevermind, that doesn't even work.
    Last edited by Bolkonsky; March 04, 2011 at 02:45 PM.
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  10. #10
    Simetrical's Avatar Former Chief Technician
    Patrician

    Join Date
    Nov 2004
    Location
    θ = π/0.6293, φ = π/1.293, ρ = 6,360 km
    Posts
    20,154

    Default Re: Question for PHP/MySQL Wizards

    Quote Originally Posted by Bolkonsky View Post
    Does anyone know what variable types default to in PHP? For instance:

    PHP Code:
    while($row mysql_fetch_array($result)) 
    in that code, if $result has no value, will it default to an int?
    Variables that haven't been declared evaluate to null, which will be treated as 0 by anything that expects an int. This will raise a PHP notice, and isn't recommended practice: initialize variables before using them.
    Quote Originally Posted by Bolkonsky View Post
    Also, do redirect (PHP) codes like this one have to go in <head></head> to work?


    PHP Code:
    <?php

       header
    'www.igmod.net/index.html' ) ;

    ?>


    Nevermind, that doesn't even work.
    You need to do something like
    PHP Code:
    header'Location: http://www.igmod.net/index.html' ); 
    You can only use header() before you've output anything at all. If you've output the opening doctype or <html>, or even just a stray newline, header() will do nothing (except raise a warning of some kind). This is assuming you aren't using some kind of buffering; if you buffer (e.g, ob_start) then header() will work until you flush something from the buffer.

    The underlying reason for this is that generally, all HTTP headers must be sent before the response body (i.e., actual page) starts. As soon as you tell PHP to output the first byte, it will first output all headers, and after that point you can no longer modify the headers, naturally. The Wikipedia article on HTTP has more details on how HTTP works.
    MediaWiki developer, TWC Chief Technician
    NetHack player (nao info)


    Risen from Prey

  11. #11

    Default Re: Question for PHP/MySQL Wizards

    Thanks for the response!

    Quote Originally Posted by Simetrical View Post
    Variables that haven't been declared evaluate to null, which will be treated as 0 by anything that expects an int. This will raise a PHP notice, and isn't recommended practice: initialize variables before using them.
    I'll keep that in mind. From now on: Declare all variables at top of page. (When possible.)

    Quote Originally Posted by Simetrical View Post
    You need to do something like
    PHP Code:
    header'Location: http://www.igmod.net/index.html' ); 
    You can only use header() before you've output anything at all. If you've output the opening doctype or <html>, or even just a stray newline, header() will do nothing (except raise a warning of some kind). This is assuming you aren't using some kind of buffering; if you buffer (e.g, ob_start) then header() will work until you flush something from the buffer.
    Does this include comments? Also, will PHP script on the page (below the redirect) still execute? (EDIT: I'm an idiot. Just thought of a real easy way to test this. 2nd EDIT: Yes, it does appear to execute.)

    Quote Originally Posted by Simetrical View Post
    The underlying reason for this is that generally, all HTTP headers must be sent before the response body (i.e., actual page) starts. As soon as you tell PHP to output the first byte, it will first output all headers, and after that point you can no longer modify the headers, naturally. The Wikipedia article on HTTP has more details on how HTTP works.
    This is good stuff, thanks!

    One final question.

    Does MySQL index rows? For instance, I have:



    Now in the first row, there's my email, my username, and my password. Could I theoretically find the row that has "COGlory" as it's username, (we'll say row1) and then get the value from the email and password in row1? I can't find anything on this in any tutorials. I think I'm just gonna buy a book. (Which if I do, does anyone have recommendations?)

    EDIT: Nevermind that, I solved it with the most inefficient ridiculous script I could ever think up, but hey, it works.

    Well, here's another question to make up for me figuring those out. After the header, is there a way to redirect someone to a different webpage, after the header? For instance, if a login is successful, I'd like to forward the user to a different page, but if it's unsuccessful, I'd like to send them back to the index. Google can't seem to find this one.
    Last edited by Bolkonsky; March 04, 2011 at 07:52 PM. Reason: solved it myself
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  12. #12
    Dragooon's Avatar Centenarius
    Join Date
    Mar 2010
    Location
    NCR, India
    Posts
    807
    My PC: Intel Core 2 Quad Q9550 @ 3.65Ghz, 4GB DDR2 RAM, ATi Radeon HD5850, Samsung 1920 x 1080p monitor, Windows 7 Home Premium 64 bit

    My Steam username : draggygarg (Feel free to add me if interested in TW:S2 Multiplayer)

  13. #13

    Default Re: Question for PHP/MySQL Wizards

    Thanks, but I have a couple problems with the meta.

    1. It needs to be in the header.
    2. I don't think (or I can't find if) it's dynamic. That's kind of a must have when you're creating a login script.

    Is it possible to create a blank/dummy form, that forwards someone to a web-page?
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  14. #14
    Dragooon's Avatar Centenarius
    Join Date
    Mar 2010
    Location
    NCR, India
    Posts
    807

    Default

    It needs to be in the head of the HTML, what do you mean dynamic? You can redirect via javescript as well by setting document.location.
    My PC: Intel Core 2 Quad Q9550 @ 3.65Ghz, 4GB DDR2 RAM, ATi Radeon HD5850, Samsung 1920 x 1080p monitor, Windows 7 Home Premium 64 bit

    My Steam username : draggygarg (Feel free to add me if interested in TW:S2 Multiplayer)

  15. #15

    Default Re: Question for PHP/MySQL Wizards

    By dynamic, I mean if the login's successful, I need it to redirect to one page, but if it's unsuccessful, it needs to redirect to an index. I hadn't thought about javascript, I'll look into that!
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  16. #16
    Simetrical's Avatar Former Chief Technician
    Patrician

    Join Date
    Nov 2004
    Location
    θ = π/0.6293, φ = π/1.293, ρ = 6,360 km
    Posts
    20,154

    Default Re: Question for PHP/MySQL Wizards

    Quote Originally Posted by Bolkonsky View Post
    Thanks for the response!


    I'll keep that in mind. From now on: Declare all variables at top of page. (When possible.)
    It doesn't have to be at the top of the page. Just make sure you declare it sometime before you use it. E.g., don't do stuff like
    PHP Code:
    function my_function() {
        if (
    something()) {
            
    $foo " there";
        }
        return 
    "Hello$foo!";

    I mean, you can do it. It will reliably return "Hello!" if something() returned false, and "Hello there!" if something() returned true. Some PHP programmers do stuff like that. But it's a better idea IMO to set error_reporting(E_ALL | E_STRICT); at the top of every page, and make sure you fix all the errors. It helps avoid bugs.
    Quote Originally Posted by Bolkonsky View Post
    Does this include comments? Also, will PHP script on the page (below the redirect) still execute?[/DEL] (EDIT: I'm an idiot. Just thought of a real easy way to test this. 2nd EDIT: Yes, it does appear to execute.)
    The PHP script will always execute in full no matter what you output. An HTTP redirect created with header() is just a special type of response, which tells the browser to go to the given location instead of displaying something. It behaves like a normal HTTP response in all other ways.
    Quote Originally Posted by Bolkonsky View Post
    One final question.

    Does MySQL index rows? For instance, I have:
    [/DEL]


    Now in the first row, there's my email, my username, and my password. Could I theoretically find the row that has "COGlory" as it's username, (we'll say row1) and then get the value from the email and password in row1? I can't find anything on this in any tutorials.
    Yes:
    Code:
    SELECT email, password FROM table_name WHERE username='COGlory';
    If you don't tell MySQL otherwise, this works by MySQL just scanning through all the rows until it finds all the ones matching the WHERE clause, which it then returns. This is fine for small tables, but for larger tables (thousands of rows or more) it can be slow. Then you want to add an index like so:
    Code:
    ALTER TABLE table_name ADD INDEX (username);
    Any decent introduction to MySQL should explain this.

    I should also add that you really need to escape any strings you pass to MySQL. Otherwise your program will break if people use special characters like ' or \. For instance, consider the following:
    PHP Code:
    $result mysql_query("SELECT email, password FROM table_name WHERE username='" $_GET['username'] . "'"); 
    If $_GET['username'] is "COGlory", this will work fine. But if the user submits a name like "Apos'trophe", then it will become
    PHP Code:
    $result mysql_query("SELECT email, password FROM table_name WHERE username='Apos'trophe'"); 
    which is a syntax error. Worse, an attacker could submit a malicious name to make the query do something entirely different (an "SQL injection attack"). The correct way to do this is
    PHP Code:
    $result mysql_query("SELECT email, password FROM table_name WHERE username='" mysql_real_escape($_GET['username']) . "'"); 
    mysql_real_escape() serves a similar purpose to htmlspecialchars() for HTML.
    Quote Originally Posted by Bolkonsky View Post
    I think I'm just gonna buy a book. (Which if I do, does anyone have recommendations?)
    Unfortunately, I don't know a good intro MySQL book.
    Quote Originally Posted by Bolkonsky View Post
    Well, here's another question to make up for me figuring those out. After the header, is there a way to redirect someone to a different webpage, after the header? For instance, if a login is successful, I'd like to forward the user to a different page, but if it's unsuccessful, I'd like to send them back to the index. Google can't seem to find this one.
    Why don't you just send a different Location header depending on whether it was successful? E.g.,
    PHP Code:
    $successful try_to_login();

    if ( 
    $successful ) {
        
    header'Location: http://mysite.com/different_page.php' );
    } else {
        
    header'Location: http://mysite.com/index.php' );

    Quote Originally Posted by Bolkonsky View Post
    By dynamic, I mean if the login's successful, I need it to redirect to one page, but if it's unsuccessful, it needs to redirect to an index.
    The PHP script itself is dynamic. You don't need to output the same thing every time, just output different redirects in the different cases.
    MediaWiki developer, TWC Chief Technician
    NetHack player (nao info)


    Risen from Prey

  17. #17

    Default Re: Question for PHP/MySQL Wizards

    Quote Originally Posted by Simetrical View Post
    It doesn't have to be at the top of the page. Just make sure you declare it sometime before you use it. E.g., don't do stuff like
    PHP Code:
    function my_function() {
        if (
    something()) {
            
    $foo " there";
        }
        return 
    "Hello$foo!";

    I mean, you can do it. It will reliably return "Hello!" if something() returned false, and "Hello there!" if something() returned true. Some PHP programmers do stuff like that. But it's a better idea IMO to set error_reporting(E_ALL | E_STRICT); at the top of every page, and make sure you fix all the errors. It helps avoid bugs.
    "(E_ALL | E_STRICT);" will save me some time, thanks.

    Quote Originally Posted by Simetrical View Post
    The PHP script will always execute in full no matter what you output. An HTTP redirect created with header() is just a special type of response, which tells the browser to go to the given location instead of displaying something. It behaves like a normal HTTP response in all other ways.
    Yeah, I did some tests and it's working.

    Quote Originally Posted by Simetrical View Post
    Yes:
    Code:
    SELECT email, password FROM table_name WHERE username='COGlory';
    If you don't tell MySQL otherwise, this works by MySQL just scanning through all the rows until it finds all the ones matching the WHERE clause, which it then returns. This is fine for small tables, but for larger tables (thousands of rows or more) it can be slow. Then you want to add an index like so:
    Code:
    ALTER TABLE table_name ADD INDEX (username);
    Any decent introduction to MySQL should explain this.
    I figured this out after several hours of racking my brains. I'll look into the indexes, though I don't plan to have many users, why sacrifice efficiency for laziness?

    Quote Originally Posted by Simetrical View Post
    I should also add that you really need to escape any strings you pass to MySQL. Otherwise your program will break if people use special characters like ' or \. For instance, consider the following:
    PHP Code:
    $result mysql_query("SELECT email, password FROM table_name WHERE username='" $_GET['username'] . "'"); 
    If $_GET['username'] is "COGlory", this will work fine. But if the user submits a name like "Apos'trophe", then it will become
    PHP Code:
    $result mysql_query("SELECT email, password FROM table_name WHERE username='Apos'trophe'"); 
    which is a syntax error. Worse, an attacker could submit a malicious name to make the query do something entirely different (an "SQL injection attack"). The correct way to do this is
    PHP Code:
    $result mysql_query("SELECT email, password FROM table_name WHERE username='" mysql_real_escape($_GET['username']) . "'"); 
    mysql_real_escape() serves a similar purpose to htmlspecialchars() for HTML.
    Here's my current code:
    PHP Code:
    $username stripslashes($username);
    $password stripslashes($password);
    $username mysql_real_escape_string($username);
    $password mysql_real_escape_string($password); 
    Quote Originally Posted by Simetrical View Post
    Why don't you just send a different Location header depending on whether it was successful? E.g.,
    PHP Code:
    $successful try_to_login();

    if ( 
    $successful ) {
        
    header'Location: http://mysite.com/different_page.php' );
    } else {
        
    header'Location: http://mysite.com/index.php' );

    This is what confuses me. How can I edit the header if it's already been sent? I'll read into this more.

    Quote Originally Posted by Simetrical View Post
    The PHP script itself is dynamic. You don't need to output the same thing every time, just output different redirects in the different cases.
    Yeah, I still need to optimize the script to use "Or" which I didn't know even existed at the time. Thanks again for all the help!
    Last edited by Bolkonsky; March 05, 2011 at 09:24 PM.
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  18. #18
    Dragooon's Avatar Centenarius
    Join Date
    Mar 2010
    Location
    NCR, India
    Posts
    807

    Default Re: Question for PHP/MySQL Wizards

    Advising for PHP code while on an iPod generally doesn't work well, I'll try to give a better reply now

    This is what confuses me. How can I edit the header if it's already been sent? I'll read into this more.
    You cannot modify a header "after" it has been sent but in that case, you don't send the header. Basically, don't output anything until you check for the login input, and then send the redirection header. Unless something has been output, headers will be fine(You can send header after header, but not header after content). Basically you can have :
    PHP Code:
    header('Content-type: text/html');
    header('Location: http://example.com'); 
    but not
    PHP Code:
    header('Content-type: text/html');
    <
    html>piece of html code
    header
    ('Location: http://example.com'); 
    It'll throw an error on the location header part. Here's when the MVC model kind or basic source-template separation work well, basically process all the information before you start to output anything, this easily solves such redirection quirks and all. You don't even need(Or rather should) use HTML/JS redirection in this case, JS redirection is usually needed in case of AJAX after-response.

    Quote Originally Posted by Bolkonsky View Post
    Here's my current code:
    PHP Code:
    $username stripslashes($username);
    $password stripslashes($password);
    $username mysql_real_escape_string($username);
    $password mysql_real_escape_string($password); 
    Presuming the code is in direct continuation and no processing is being done in between, remove the stripslashes, they are just wasting processing power there.

  19. #19

    Default Re: Question for PHP/MySQL Wizards

    This is where I'm rather confused.

    This
    Spoiler for PHP page
    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <?php
    $con 
    mysql_connect("localhost","root","");
    if (!
    $con)
      {
      die(
    'Could not connect: ' mysql_error());
      }

    $username $_POST["username"];
    $password $_POST["password"];

    $username mysql_real_escape_string($username);
    $password mysql_real_escape_string($password);

     
    mysql_select_db("ig_website"$con);
     
    $result mysql_query("SELECT * FROM users
    WHERE username='
    $username'");

    while(
    $row mysql_fetch_array($result))
      {
      
    $saved_username $row['username'];
      
    $saved_password $row['password'];
      }
    mysql_close($con);
      
    $username_correct 1#1 = true
    $password_correct 1#1 = true

    if ($username==$saved_username)
      
    $username_correct 1;
    if (
    $password==$saved_password)
      
    $password_correct 1;
      
    if (
    $username_correct == 1)
    if (
    $password_correct == 1)
    {
    echo 
    "Login Success!  You will be redirected shortly...";  
    $login true;
    }
    if ((
    $username_correct == 0) || ($password_correct == 0))
    {
    echo 
    "Login Failed!  You will be redirected shortly...";
    $login false;
    }

    if (
    $login == true)
      
    header'Location: admin.html' );
    else
      
    header'Location: login.php' );
    ?>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Get Data</title>
    <link rel="shortcut icon" href="images/icon.ico"></link>
    </head>
    <body background="images/marble.jpg">

    </body>
    </html>

    returns with "Warning: Cannot modify header information - headers already sent by (output started at C:\xampplite\htdocs\get_data.php:2) in C:\xampplite\htdocs\get_data.php on line 48"

    Maybe I'm going insane, but I don't see any output there.
    Under the Patronage of Leonidas the Lion|Patron of Imperator of Rome - Dewy - Crazyeyesreaper|American and Proud

  20. #20
    Dragooon's Avatar Centenarius
    Join Date
    Mar 2010
    Location
    NCR, India
    Posts
    807

    Default Re: Question for PHP/MySQL Wizards

    You're outputting the doctype declaration, move the declaration before <html>. Some more piece of advice, I'd encrypt the password with sha256 or something similar just in case, so even if someone breaks into your DB they do not get your user's passwords.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •