Jump to content

Recommended Posts

Since I don't know enough of either PHP or MySQL to write my own, code, I copied some out of this tutorial on how to make a register/login application.

 

I used his code exactly:

 

<?php

        // dbConfig.php is a file that contains your
        // database connection information. This
        // tutorial assumes a connection is made from
        // this existing file.
        include ("dbConfig.php");


//Input vaildation and the dbase code
        if ( $_GET["op"] == "reg" )
  {
  $bInputFlag = false;
  foreach ( $_POST as $field )
        {
        if ($field == "")
    {
    $bInputFlag = false;
    }
        else
    {
    $bInputFlag = true;
    }
        }
  // If we had problems with the input, exit with error
  if ($bInputFlag == false)
        {
        die( "Problem with your registration info. "
    ."Please go back and try again.");
        }

  // Fields are clear, add user to database
  //  Setup query
  $q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
        ."VALUES ('".$_POST["username"]."', "
        ."PASSWORD('".$_POST["password"]."'), "
        ."'".$_POST["email"]."')";
  //  Run query
  $r = mysql_query($q);
  
  // Make sure query inserted user successfully
  if ( !mysql_insert_id() )
        {
        die("Error: User not added to database.");
        }
  else
        {
        // Redirect to thank you page.
        Header("Location: register.php?op=thanks");
        }
  } // end if


//The thank you page
        elseif ( $_GET["op"] == "thanks" )
  {
  echo "<h2>Thanks for registering!</h2>";
  }
  
//The web form for input ability
        else
  {
  echo "<form action=\"?op=reg\" method=\"POST\">\n";
  echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";
  echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16\"><br />\n";
  echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
  echo "<input type=\"submit\">\n";
  echo "</form>\n";
  }
        // EOF
        ?>

 

I got as far as to put the registration form up, here. And when I put in my info and press the submit button, it just cleared the form and nothing else happened (except that it appended "?op=reg" at the end of the URL).

 

So I added

 

ini_set('display_errors', 1);

error_reporting(E_ALL);

 

to the top of the code, and now I'm getting these errors:

 

Notice: Undefined index: op in /home1/thrrive2/public_html/fledgepress/register.php on line 14

 

Notice: Undefined index: op in /home1/thrrive2/public_html/fledgepress/register.php on line 58

 

Please help - and if you can tell me WHY it isn't working, for my future reference, please do.

Link to comment
https://forums.phpfreaks.com/topic/242033-code-from-phpmysql-tutorial-doesnt-work/
Share on other sites

I think QuickOldCar meant this:

 

if ( !$r) 

 

About those messages you're seeing, those are harmless - they say that the "?op=reg" was not present when your script looked for it.  It's saying it can't find index "op" in the $_GET array.  This is one of the most annoying and unnecessary "notices" in php, and never should have been included in E_ALL.

The only way the posted form processing code will redisplay the form is if the GET parameter on the end of the URL is not seen by the php code.

 

Are you doing an URL rewriting that might be not be carrying the the GET parameters on the end of the URL?

 

What do you get after the form has been submitted from the following code -

 

echo "<pre>";
echo "GET:";
print_r($_GET);
echo "POST:";
print_r($_POST);
echo "</pre>";

The only way the posted form processing code will redisplay the form is if the GET parameter on the end of the URL is not seen by the php code.

 

Are you doing an URL rewriting that might be not be carrying the the GET parameters on the end of the URL?

 

I didn't do anything other than copy the code, save it as a php document, and call it as an include().

 

What do you get after the form has been submitted from the following code -

 

echo "<pre>";
echo "GET:";
print_r($_GET);
echo "POST:";
print_r($_POST);
echo "</pre>";

 

Where should I put that in the code?

It would probably be a good idea if you posted ALL the code on the page or you need to make a page that just consists of the code that you posted at the start of this thread.

 

Edit: Also tell us which browser you are using because the page you posted a link to and the form code you posted here contain a far number of HTML markup errors that could prevent the form from being seen as a form by the browser.

user.php:

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
    <title>Fledge Press - Login</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <link rel="stylesheet" type="text/css" href="/fledge_styles.css">  
    <style type="text/css">
    </style>
</head>

<body>

<?php include("http://fledgepress.com/nav_ads.php"); ?>

<div id="main">

<h4>Register or login below:</h4>

<?php include("http://fledgepress.com/register.php"); ?>

</div>

<?php include("http://fledgepress.com/bottom.php"); ?>

</body>

</html>

 

"register.php" is what I posted in the OP. The other two included files are just sidebar and bottom navigation and aren't relevant.

 

And here is dbConfig.php which is included in register.php:

 

<?
$host = "localhost";
$user = "UserName";
$pass = "Password";
$db   = "dbName";

$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
        {
        echo "Error connecting to database.\n";
        }

mysql_select_db($db);
?>

 

Except of course I have my actual user name, password, and database name in the version I'm using.

You are including the code using a URL. That doesn't include the php code into the main page, it includes the OUTPUT from the php code, the same as if you browsed to that file being included.

 

You need to use a file system path to include php code so that it becomes part of the main page.

 

Edit: Also by using a URL, each include statement takes about 200+ ms. Using a file system path will only take about 10-20ms at the most.

 

 

I would probably be a good idea to post the current register.php code or use the original unmodified version (I tested what you posted, as best as possible without a database, and it should 'work' the way it was.)

There's nothing in the original that would produce the posted error - Notice: Use of undefined constant r - assumed 'r' in /home1/thrrive2/public_html/fledgepress/register.php on line 52

 

Without the actual line 52 code, cannot help you.

It would be line 52 of register.php, which I posted in the OP:

 

if ( !r)
        {
        die("Error: User not added to database.");
        }
  else
        {
        // Redirect to thank you page.
        Header("Location: register.php?op=thanks");
        }
  } // end if

 

EDIT: Oh wait, I did change it to that from the original. Forgot about that. /facepalm

 

Let me change it back and see what happens.

That means the the mysql_insert_id() was a zero (no auto-increment generated by the insert query) or a FALSE (the query failed due to an error or there is no connection to the database server.) Unfortunately, the code has no error checking logic to pin down if the query executed with an error or not before it attempted to check if the INSERT worked.

 

Use the following code to determine what is happening with the query. The first statement (four lines setting the $q query variable) and the last statement (  } // end if ) are your existing code. Everything in between those two statements should be replaced -

 

  $q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
        ."VALUES ('".$_POST["username"]."', "
        ."PASSWORD('".$_POST["password"]."'), "
        ."'".$_POST["email"]."')";

if(!$r = mysql_query($q)){
// query error, display debugging information -
die("Query failed with an error: " . mysql_error());
} else {
// query executed without any error
// Make sure query inserted user successfully
if ( !mysql_insert_id() )
{
	die("Error: User not added to database.");
} else {
	// Redirect to thank you page.
	Header("Location: register.php?op=thanks");
	exit;
}
}

  } // end if

 

 

 

Got this:

 

"Query failed with an error: No database selected"

 

And just for convenience, here is the code for database access.

 

<?

$host = "localhost";
$user = "thrrive2";
$pass = "**********";
$db   = "thrrive2_dbUsers";

$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
        {
        echo "Error connecting to database.\n";
        }

mysql_select_db($db);
?>

I rewrote some of this, it works ok.

 

to create the database

CREATE TABLE dbUsers
(
id int NOT NULL AUTO_INCREMENT,
username varchar(16) Unique,
password char(32),
email varchar(25),
PRIMARY KEY (id)
)

 

dbConfig.php

<?php
//use your database connection information
$host = "localhost";//usually localhost,change if need different
$db_username = "dbuser";//change database user name
$db_password = "dbpass";//change database password
$db_name = "dbname";//change database name

$db = mysql_pconnect($host, $db_username, $db_password);
if ( !$db )
        {
        echo "Error connecting to database.\n";
        }

mysql_select_db($db_name,$db);
?>

 

index.php

<?php
session_start();
include('nav.php');
echo "This is the index page";
?>

 

login.php

<?php
session_start();
include('dbConfig.php');

if(isset($_POST)){
$username = trim($_POST['username']); 
$password = trim($_POST['password']);
$md5pass = md5($password);

if (!empty($_POST["username"]) || !empty($_POST["password"])) {
  
$sql_query = mysql_query("SELECT * FROM dbUsers WHERE username='$username'"); 
$row = mysql_fetch_array($sql_query) or die(mysql_error());
$user_id = $row['id'];
$user_name = $row['username'];
$user_password = $row['password'];

if($username == $user_name && $md5pass == $user_password) {
// Login good, create session variables
$_SESSION["valid_id"] = $user_id;
$_SESSION["valid_user"] = $user_name;
$_SESSION["valid_time"] = time();
        
//change where to redirect after login
//header("Location: index.php");
header("Location: members.php");
} else {
$message = "Invalid Login.";
}
} else {
$message = "Insert user name or password.";
}
include('nav.php');
  
  echo "<form action='' method='POST'>";
  echo "Username: (16 Characters Max) <input name='username' size='16'><br />";
  echo "Password: (16 Characters Max) <input type='password' name='password' size='16'><br />";
  echo "<input type='submit' value='Login'>";
  echo "</form>";
  
echo $message;

}

?>

 

logout.php

<?php
session_start();
session_unset();

session_destroy();
// Logged out, return home.
header("Location: index.php");
?>

 

members.php

<?php
session_start();
if (!$_SESSION["valid_user"])
        {
        // User not logged in, redirect to login page
        header("Location: login.php");
        }
include('nav.php');

// Member only content
// ...
// ...
// ...

// Display Member information
echo "<p>User ID: " . $_SESSION["valid_id"];
echo "<p>Username: " . $_SESSION["valid_user"];
echo "<p>Logged in: " . date("m/d/Y", $_SESSION["valid_time"]);

// Display logout link
echo "<p><a href=\"logout.php\">Click here to logout!</a></p>";
?>

 

nav.php

<a href="index.php"> HOME </a> <a href="members.php"> Members </a> <a href="login.php"> Login </a> <a href="logout.php"> Logout </a> <a href="register.php"> Register </a>
<br />

 

register.php

<?php
        // dbConfig.php is a file that contains your
        // database connection information. This
        // tutorial assumes a connection is made from
        // this existing file.
        include ("dbConfig.php");


//Input vaildation and the dbase code
        if ( $_GET["op"] == "reg" )
  {
  $bInputFlag = false;
  foreach ( $_POST as $field )
        {
        if ($field == "")
    {
    $bInputFlag = false;
    }
        else
    {
    $bInputFlag = true;
    }
        }
  // If we had problems with the input, exit with error
  if ($bInputFlag == false)
        {
        die( "Problem with your registration info. "
    ."Please go back and try again.");
        }

  // Fields are clear, add user to database
  //  Setup query
  $q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
        ."VALUES ('".$_POST["username"]."', "
        ."PASSWORD('".md5($_POST["password"])."'), "
        ."'".$_POST["email"]."')";
  //  Run query
  $r = mysql_query($q);
  
  // Make sure query inserted user successfully
  if ( !r )
        {
        die("Error: User not added to database.");
        }
  else
        {
        // Redirect to thank you page.
        header("Location: register.php?op=thanks");
        }
  } // end if


//The thank you page
        elseif ( $_GET["op"] == "thanks" )
  {
  echo "<h2>Thanks for registering!</h2>";
  echo "Redirecting you to log in<br />";
  echo "<meta http-equiv='refresh' content='5;url=login.php'>";
  }
  
//The web form for input ability
        else
  {
include('nav.php');
  
  echo "<form action=\"?op=reg\" method=\"POST\">\n";
  echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";
  echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16\"><br />\n";
  echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
  echo "<input type=\"submit\">\n";
  echo "</form>\n";
  }
        // EOF
?>

 

Hope this helps some people, and I'm sure can use some improvements as well.

"Query failed with an error: No database selected"

 

The mysql_select_db statement is probably failing. Is "thrrive2_dbUsers" the actual name of your database?

 

When you put in the ini_set('display_errors', 1); error_reporting(E_ALL); statements, did you put those before the include ("dbConfig.php"); statement so that any php detected errors in the dbConfig.php code would be reported and displayed?

Alright, I fixed it.

 

This does need more error checking for a few items.

 

Use everything I have here and it should work.

 

create table

CREATE TABLE dbUsers
(
id int NOT NULL AUTO_INCREMENT,
username varchar(32) Unique,
password char(32),
email varchar(32),
PRIMARY KEY (id)
)

 

dbConfig.php

<?php
//use your database connection information
$host = "localhost";//usually localhost,change if need different
$db_username = "user";//change database user name
$db_password = "password";//change database password
$db_name = "database";//change database name

$db = mysql_pconnect($host, $db_username, $db_password);
if ( !$db )
        {
        echo "Error connecting to database.\n";
        }

mysql_select_db($db_name,$db);
?>

 

index.php

<?php
session_start();
include('nav.php');
echo "This is the index page";
?>

 

login.php

<?php
session_start();
include('dbConfig.php');

if(isset($_POST)){
$username = trim($_POST['username']); 
$password = trim($_POST['password']);
$md5pass = md5($password);

if (!empty($_POST["username"]) || !empty($_POST["password"])) {
  
$sql_query = mysql_query("SELECT * FROM dbUsers WHERE username='$username'"); 
$row = mysql_fetch_array($sql_query) or die(mysql_error());
$user_id = $row['id'];
$user_name = $row['username'];
$user_password = $row['password'];

if($username == $user_name && $md5pass == $user_password) {
// Login good, create session variables
$_SESSION["valid_id"] = $user_id;
$_SESSION["valid_user"] = $user_name;
$_SESSION["valid_time"] = time();
        
//change where to redirect after login
//header("Location: index.php");
header("Location: members.php");
} else {
$message = "Invalid Login.";
}
} else {
$message = "Insert user name or password.";
}
include('nav.php');
  
  echo "<form action='' method='POST'>";
  echo "Username: (32 Characters Max) <input name='username' size='32'><br />";
  echo "Password: (32 Characters Max) <input type='password' name='password' size='32'><br />";
  echo "<input type='submit' value='Login'>";
  echo "</form>";
  
echo $message;

}

?>

 

logout.php

<?php
session_start();
session_unset();

session_destroy();
// Logged out, return home.
header("Location: index.php");
?>

 

members.php

<?php
session_start();
if (!$_SESSION["valid_user"])
        {
        // User not logged in, redirect to login page
        header("Location: login.php");
        }
include('nav.php');

// Member only content
// ...
// ...
// ...

// Display Member information
echo "<p>User ID: " . $_SESSION["valid_id"];
echo "<p>Username: " . $_SESSION["valid_user"];
echo "<p>Logged in: " . date("m/d/Y", $_SESSION["valid_time"]);

// Display logout link
echo "<p><a href=\"logout.php\">Click here to logout!</a></p>";
?>

 

nav.php

<a href="index.php"> HOME </a> <a href="members.php"> Members </a> <a href="login.php"> Login </a> <a href="logout.php"> Logout </a> <a href="register.php"> Register </a>
<br />

 

register.php

<?php
        // dbConfig.php is a file that contains your
        // database connection information. This
        // tutorial assumes a connection is made from
        // this existing file.
        include ("dbConfig.php");


//Input vaildation and the dbase code
        if ( $_GET["op"] == "reg" )
  {
  $bInputFlag = false;
  foreach ( $_POST as $field )
        {
        if ($field == "")
    {
    $bInputFlag = false;
    }
        else
    {
    $bInputFlag = true;
    }
        }
  // If we had problems with the input, exit with error
  if ($bInputFlag == false)
        {
        die( "Problem with your registration info. "
    ."Please go back and try again.");
        }
$user = mysql_real_escape_string(trim($_POST['username']));
$pass = md5(mysql_real_escape_string(trim($_POST['password'])));
$mail = mysql_real_escape_string(trim($_POST['email']));

  // Fields are clear, add user to database
  //  Setup query

$r = mysql_query("INSERT INTO dbUsers 
(username, password, email) VALUES('$user', '$pass', '$mail' ) ") 
or die(mysql_error());  
  
  // Make sure query inserted user successfully
  if ( !$r )
        {
        die("Error: User not added to database.");
        }
  else
        {
        // Redirect to thank you page.
        header("Location: register.php?op=thanks");
        }
  } // end if


//The thank you page
        elseif ( $_GET["op"] == "thanks" )
  {
  echo "<h2>Thanks for registering!</h2>";
  echo "Redirecting you to log in<br />";
  echo "<meta http-equiv='refresh' content='5;url=login.php'>";
  }
  
//The web form for input ability
        else
  {
include('nav.php');
  
  echo "<form action='?op=reg' method='POST'>\n";
  echo "Username: <input name='username' MAXLENGTH='32'><br />\n";
  echo "Password: <input name='password' MAXLENGTH='32'<br />\n";
  echo "Email Address: <input name='email' MAXLENGTH='32'><br />\n";
  echo "<input type='submit'>\n";
  echo "</form>\n";
  }
        // EOF
?>

Thanks, QuickOldCar. The registration seems to writing to the database. However, after registration it gives me this error from "login.php":

 

Warning: Cannot modify header information - headers already sent by (output started at /home1/thrrive2/public_html/fledgepress/user.php:9) in /home1/thrrive2/public_html/fledgepress/login.php on line 49

 

And this from "register.php":

"Duplicate entry 'macfall' for key 'username'"

 

Also, when I try to log in I get the same "duplicate entry" from login.php .

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.