Php And Mysql

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.

Hey guys,

I've been learning PHP and I need to know how to use PHP with MySQL. More specifically I need to know how to connect my app to the database and how to store content.

Thanks!

Joined: 11/28/2008
User offline. Last seen 2 years 33 weeks ago.
I would start with this and

I would start with this and proceed from there. One thing that really helps clean up your code and reduces repeating yourself is having database functions to perform common tasks, like connecting to a database, executing a query and fetching the results.

Edit: I also recommend using phpMyAdmin to manage the database as doing it all via command line can be more troublesome than helpful. I'm quite comfortable with MySQL and have been using it for around four years, but even I still like using phpMyAdmin because it really makes managing your databases so easy.

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
Yes, I'm using phpMyAdmin. I

Yes, I'm using phpMyAdmin. I didn't realize there was a difference between MySQL and phpMyAdmin.

How do I store information to the database now? Wordpress plugins use update_option() and get_option(), is that the same thing?

Thanks!

Joined: 11/28/2008
User offline. Last seen 2 years 33 weeks ago.
phpMyAdmin is simply an

phpMyAdmin is simply an interface for you to manage your MySQL database. You're still using MySQL.

update_option() and get_option() are simply WP functions that use database functions that insert and update rows in MySQL. You can look at this SQL Tutorial to see how insert and update work. You should also go here to use MySQL with PHP. It shows the functions you need to call.

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
User offline. Last seen 3 years 10 weeks ago.
Actually, to make life even

Actually, to make life even easier, I would suggest looking into using ADODB (found at http://adodb.sourceforge.net/). It is much better than just simply using the MySQL functions in PHP directly.

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
How would I work this? I'm

How would I work this? I'm trying to make it search and match up username and password from the user input and from the database but it doesn't like the while() in the if(). Any suggestions?

CODE
$statement = "SELECT username, password FROM users";
        $result_id = mysql_query ($statement);
        if(
            while ($row == mysql_fetch_array($result_id)){
                $_REQUEST['username'] == $row['Username'] && $_REQUEST['Password'] == $row['Password']
            }
        ){
            setcookie($_COOKIE['session'].'loggedin', TRUE, time()+3600);
            admin();
        }
            
            if($_REQUEST['username'] != $row['Username'] || $_REQUEST['password'] != $row['Password']){
                echo "Error: Invalid login<br /><a href='login.php'>Try again</a>";
            }
Joined: 11/28/2008
User offline. Last seen 2 years 28 weeks ago.
If I understand what you're

If I understand what you're trying to do, you should use a where clause, then count the amount of rows returned. Something along the lines of:

CODE
$rowsReturned = mysql_query(SELECT COUNT(*) FROM usertable WHERE username = form.username AND userpassword = form.userpassword);

if($rowsReturned == 1) {
    //login found, begin login logic
} else {
    //login not found, kick em out and call em names
}

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
I don't understand where it

I don't understand where it would call what the user submitted ($_REQUEST['username'] and $_REQUEST['password'])

skenow
skenow's picture
form.username and

form.username and userpassword represent what the user submitted on the login form. It is highly recommended you do not use the $_REQUEST variables without some kind of validation and sanitation. SQL injections are quite common in situations where this is not done.

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
Okay I don't understand why

Okay I don't understand why this isn't working.

CODE
include('config.php');
    $rowsReturned = mysql_query("SELECT * FROM users WHERE Username = form.username AND Password = form.password");
    if($_COOKIE['loggedin']){
        header('Location: admin_style.php');
    }

    else if($rowsReturned == 1) {
        setcookie($_COOKIE['session'].'adminloggedin', TRUE, time()+3600);
        header('Location: admin_main.php');
    }
    else {
        echo "Error: Invalid login<br /><a href='login.php'>Try again</a>";
    }

Config.php has the database info.

Joined: 11/28/2008
User offline. Last seen 2 years 33 weeks ago.
Elaborate on the "isn't

Elaborate on the "isn't working" portion. What does $rowsReturned give you?

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
User offline. Last seen 2 years 28 weeks ago.
At first glance, I don't

At first glance, I don't think it is working because you're trying to count rows without using the SQL Count function. Try changing "*" in your sql statement to "COUNT(*)" and see what happens. Outside of that, I think I'll need a little more info.

Joined: 11/28/2008
User offline. Last seen 2 years 33 weeks ago.
Now that I'm awake I have a

Now that I'm awake I have a little more sense. $rowsReturned would be a resource, not the fetched results or the number of rows. If you want the number of rows (assuming everything is operating correctly), you'll want to do:

CODE
$result = mysql_query("SELECT * FROM users WHERE Username = form.username AND Password = form.password");
$rowsReturned = mysql_num_rows($results);

Also, I'm assuming form.username and form.password is not what you're trying to use, is it? If so, you need to use the values listed in $_POST. I'm guessing that your field names are form.username and form.password; this will prevent SQL injections.

CODE
$username = mysql_real_escape_string($_POST['form.username']);
$password = mysql_real_escape_string($_POST['form.password']);
$result = mysql_query("SELECT * FROM users WHERE Username = '$username' AND Password = '$password'");

Other than this, need. more. info. /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
I don't understand how the

I don't understand how the form.username and form.password work. I tried it and echoed $_POST['form.username'] and it didn't return anything, even when my input field was named "form.username".

What I mean by "doesn't work" is it doesn't log in.

Right now I'm getting these errors with the code below

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\cms\login.php:5) in C:\xampp\htdocs\cms\login.php on line 17

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\cms\login.php:5) in C:\xampp\htdocs\cms\login.php on line 18

CODE
line 17: setcookie($_COOKIE['session'].'adminloggedin', TRUE, time()+3600);
line 18: header('Location: admin_main.php');

I also echoed $rowsReturned and it's always returning the value 1 no matter what.

Please elaborate on what more info you need.

Thanks guys!

CODE
File: login.php

<?php

    include('config.php');
    if($_REQUEST['login']){
        echo $_POST['username'];
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);
        $results = mysql_query("SELECT COUNT(*) FROM users WHERE Username = '$username' AND Password = '$password'");
        $rowsReturned = mysql_num_rows($results);
        echo $rowsReturned;
        
        if($_COOKIE['loggedin']){
            header('Location: admin_style.php');
        }
    
        else if($rowsReturned == 1) {
            setcookie($_COOKIE['session'].'adminloggedin', TRUE, time()+3600);
            header('Location: admin_main.php');
        }
        else {
            $error = "Error: Invalid login<br />";
        }
    }
    
?>

<html>
    <head>
        <title>Login</title>
        <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
    </head>
    <body>
        <?php echo $error; ?>
        <form action='' method='post'>
            <div class='title'>Username</div><input type='text' name='username' /><br />
            <div class='title'>Password</div><input type='password' name='password' /><br />
            <input type='submit' name='login' value='Login' />
        </form>
        
        <p>Forgot password? | <a href="register.php">Register</a></p>
        
        <p><a href="index.php">Home</a> &gt; Login</p>
        
        <p>&nbsp;</p>
        <p><a href="admin/index.php">Administration Pannel</a></p>
    
    </body>
</html>

skenow
skenow's picture
As soon as you send any

As soon as you send any output, you can no longer use several functions - header and setcookie are among them, see the PHP manual. You are sending output using the echo command.

Because your sql uses the count() function, it will always return a single row, even if the count is zero. Try it without count(*), just use SELECT * FROM users WHERE Username = '$username' AND Password = '$password'

Joined: 11/28/2008
User offline. Last seen 2 years 33 weeks ago.
Follow what skenow said and

Follow what skenow said and also check your cookies when you first access the login page, not after a person has attempted to login.

To clarify on form.username and username, these are the names of the form fields (<input name="username" />). Anytime you access $_POST or $_GET form items, it will always be by the name of the form item. You mentioned changing the field to match form.username but it not displaying; I'd have to see the code to see what was really going on.

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
Thanks guys!So how would I go

Thanks guys!

So how would I go about putting a function in here?

CODE
if($rowsReturned == 1) {
    
}
CODE
File: login.php

<?php

    include('config.php');
    
    if($_COOKIE['loggedin']){
        header('Location: admin_style.php');
    }
    else if($_REQUEST['login']){
        echo $_POST['username'];
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);
        $results = mysql_query("SELECT * FROM users WHERE Username = '$username' AND Password = '$password'");
        $rowsReturned = mysql_num_rows($results);
        echo $rowsReturned;

         if($rowsReturned == 1) {
            
        }
        else {
            $error = "Error: Invalid login<br />";
        }
    }
    
?>

<html>
    <head>
        <title>Login</title>
        <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
    </head>
    <body>
        <?php echo $error; ?>
        <form action='' method='post'>
            <div class='title'>Username</div><input type='text' name='username' /><br />
            <div class='title'>Password</div><input type='password' name='password' /><br />
            <input type='submit' name='login' value='Login' />
        </form>
        
        <p>Forgot password? | <a href="register.php">Register</a></p>
        
        <p><a href="index.php">Home</a> &gt; Login</p>
        
        <p>&nbsp;</p>
        <p><a href="admin/index.php">Administration Pannel</a></p>
    
    </body>
</html>

Joined: 11/28/2008
User offline. Last seen 2 years 33 weeks ago.
Why would you need a

Why would you need a function? If the user successfully logs in, you want to redirect them; that's where your header redirect should go (which means remove echo $rowsReturned;)

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
User offline. Last seen 38 weeks 6 days ago.
Okay I see, it didn't like

Okay I see, it didn't like the echo $rowsReturned. Thanks guys!

Joined: 11/28/2008
User offline. Last seen 3 years 10 weeks ago.
What I would recommend is

What I would recommend is first of all learning how to use SQL language - without php. That way you can get a clear understanding of what SQL is and how to use it. Then after that use an ORM.

First result for "learn SQL" (I skimmed it and it looks like a very good introduction to basic SQL): http://www.w3schools.com/sql/default.asp

You can find out more about what an ORM is and some good reasons to use one on wikipedia: http://en.wikipedia.org/wiki/Object-relational_mapping
This looks like a good ORM for use with php: http://www.phpdoctrine.org/

I hope that helps!

My blog about web development.
And my site about game development.

>>> math.sqrt(-1) == joey101
True