Page 1 of 3 123 LastLast
Results 1 to 10 of 24

Thread: Strange error re user_id when adding entries to database

  1. #1
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Strange error re user_id when adding entries to database

    I have a simple PHP program and a small MySQL database. When I add a new entry to the database, using a form, I often get the following error: "Undefined index: user_id"

    My personal user id in the database is 1. When I get this error, it usually means that the entry has been entered in the database as if from user 0. There is no actual user 0. Sometimes the entry is entered in the database as if from user 0 (who doesn't exist); sometimes as if from user 1 (me). I cannot detect any pattern in when it goes one way or the other.

    Does that make any kind of sense to anyone? Is there a way that I could plug this hole so that there would be no future entries attributed to user 0? and a way to ensure that all my future entries are attributed to user 1?

    - - - - -

    In case it helps, my database looks something like this:

    1st table - users:

    Code:
    Field 		Type 		        Null 	        Default     Auto_increment 
    
    user_id 	smallint(5) 	        No		yes          auto_increment
    email 		varchar(40) 	No     
    password 	varchar(40) 	No     
    first_name 	varchar(15) 	No     
    last_name 	varchar(30) 	No     
    active 	char(32) 	        Yes
    registration_date datetime 	No
    2nd table - temperatures:

    Code:
    Field 		       Type 		Null 	Default  
    
    user_idm 	       smallint(5) 	No     
    temp_rating	       char(2) 	No     
    notes        	       text 	        Yes	NULL
    time_entered	datetime 	No     
    time_entered2	timestamp	No 
    CURRENT_TIMESTAMP
    Last edited by Anne Arbor; 01-26-2014 at 05:12 AM.

  2. #2
    Join Date
    Jan 2007
    Location
    Davenport, Iowa
    Posts
    1,691
    Thanks
    82
    Thanked 89 Times in 87 Posts

    Default

    Information about your database is helpful, but the PHP that you are using to enter the data into your database would be more helpful and what we really need to see here.
    To choose the lesser of two evils is still to choose evil. My personal site

  3. #3
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default

    Thank you, James. I was hoping it was a database problem. But no such luck. ;-)

    Here's what I have, with all its faults:

    Code:
    <?php // add_entry.php
    
    ob_start(); 
    require_once ('./includes/config.inc.php'); 
    include ('./includes/header.html');
    $page_title = 'Add New Entry';
    
    ?> 
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
    	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
    	<title>Add New Entry</title>
    </head>
    
    <body>
    
    <style type="text/css" media="screen">@import "./includes/layout.css";</style>
    
    </head>
    
    <body>
    
    <?php // Ullman Script 12.6 - entry.php #2
    
    /* This script adds a log entry to the database. It now does so securely! */ 
    
    if (isset($_POST['submitted'])) { // Handle the form.
    
    require_once ('../mysql_connect_temp1.php'); // Connect to & select the database.
    
    	// Validate and secure the form data:
    	$problem = FALSE;
    	if (!empty($_POST['temp_rating'])) {
    		$temp = mysql_real_escape_string(trim($_POST['temp_rating']));
    		$notes = mysql_real_escape_string(trim($_POST['notes']));
    
    	} else {
    		print '<p style="color: red;">Please submit a temperature rating.</p>';
    		$problem = TRUE;
    	}
    
    	if (!$problem) {
    
    		// Define the query:
    		$query = "INSERT INTO temps (user_idm, temp_rating, notes, time_entered)
                      VALUES ('$_SESSION[user_id]', '$temp', '$notes', NOW())";
    
    		// Execute the query:
    		if (@mysql_query($query)) {
    			print '<p>The entry has been added!</p>';
    
    		} else {
    			print '<p style="color: red;">Could not add the entry because:<br />' . mysql_error() . '.</p><p>The query being run was: ' . $query . '</p>';
    		}
    	
    	} // No problem!
    
    	mysql_close();	
    } // End of form submission IF.    // Display the form:
    ?>
    
    <p><br><br>
    <FORM action="add_entry.php" method="post"> 
     <center><TABLE border="1">
       <TR bgcolor="#CCCCFF">  <TH>Name</TH>   <TH>Value</TH>
       </TR>
    
       <TR>
        <TD>Temp rating:</TD>
        <TD>
         <select name="temp_rating">
          <option></option>
          <option>0 F</option>
          <option>10 F</option>
          <option>20 F</option>
          <option>30</option>
          <option>40</option>
          <option>50</option>
          <option>60</option>
          <option>70</option>
          <option>80</option>
          <option>90</option>
          <option>100</option>
         </select>
        </TD>
       </TR>
    
       <TR>
        <TD colspan="2">Notes:<BR>
         <textarea name="notes" cols="50" rows="4"></textarea>
        </TD>
       </TR>
       <TR>
    
        <TD colspan="2" align="center">
         <input type="submit" name="submit" value="Post this entry!">
         <input type="hidden" name="submitted" value="true" />
    
        </TD>
       </TR>
    
      </TABLE></center>
    </FORM> 
    
    <?php
    include ('./includes/footer.html');
    ?> 
    
    </BODY>  </HTML>

  4. #4
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default

    James, just so you know, my actual program does not work with temperatures. I've been trying to preserve a bit of privacy about the real topic. The temperature analogy is very close, however, and the code provided here is otherwise absolutely identical.
    Last edited by Anne Arbor; 01-26-2014 at 10:48 PM.

  5. #5
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    If you don't wish to share your actual code, you will need to make sure your example code demonstrates the same problem, in the same way. This includes your database schema, etc..

    "undefined index" means that you're trying to get "user_id" from an array, but the array has no such index. At the most basic level, you could (should) simply check if this is the case, and provide a value if needed. e.g.:
    PHP Code:
    $user_id = isset( $_SESSION["user_id"] )? $_SESSION["user_id"]: 1
    However, the fact that you expect the user_id to be in the session would imply that the user is supposed to be logged in (or authenticated in some way). If there is no user_id in the session, I would worry that this has not happened: therefore, I would not accept the form submission at all, because it might come from an unauthorized user.

  6. #6
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default

    Traq, thank you very much for your reply. The only change from my actual code is that I am using "temp" here and the actual code uses a different word. Otherwise, everything is identical.

    My site does have a user registration feature and a log-in page. Those work almost correctly -- except that sometimes after I log in and make an entry, the entry gets entered properly for me as 'user_1' and sometimes gets entered improperly as 'user_0', even though there is no actual user_0.

    I'd be glad of any way to solve this problem. One way that had occurred to me was there might be some way of plugging the "user_0" hole. Is there some way that I could assign that to someone (even me, using a different name)?

  7. #7
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default

    Traq, you seem to be suggesting that the problem might lie in the log-in code, so I'll supply that here:

    Code:
    <?php    // Ullman Script 11.4 (DWS) - login.php
    
    ob_start();   // Start output buffering.
    
    require_once ('./includes/config.inc.php'); 
    
    $page_title = 'Log in';
    
    include ('./includes/header.html');
    
    ?> 
    
    <!--
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
         <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
         <title>Login</title>
    </head>  --> 
    
    <body>
    
    <?php
    
    if (isset($_POST['submitted'])) {
    
    	require_once ('../mysql_connect_temp1.php');
    
    	if (!empty($_POST['email'])) {
        	         $e = escape_data($_POST['email']);
    
    	} else {
    
    		echo '<p><font color="red">You forgot to enter your email address.</font></p>';
    		$e = FALSE;
    
    	}
    	
    	if (!empty($_POST['password'])) {
     	   $p = escape_data($_POST['password']);
    
    	} else {
    		echo '<p><font color="red">You forgot to enter your password.</font></p>';
    		$p = FALSE;
    	}
    
    	if ($e && $p) { 
    
    		$query = "SELECT user_id, first_name FROM users WHERE email='$e' AND password=SHA('$p')";
    		
    		$result = @mysql_query ($query); // Run the query.
    
    		$row = mysql_fetch_array ($result, MYSQL_NUM); // Return a record, if applicable.
    
    		if ($row) { // A record was pulled from the database.
    
    				// Set the session data & redirect.
    
    			session_start();
    			$_SESSION['user_id'] = $row[0];
    
    			$_SESSION['first_name'] = $row[1];
    
    			ob_end_clean(); // Delete the buffer.
    
    			// Redirect the user to the loggedin.php page.
    			// Start defining the URL.
    
    			$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    
    			// Check for a trailing slash.
    
    			if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
    
    				$url = substr ($url, 0, -1); // Chop off the slash.
    			}
    
    		// Add the page.
    			$url .= '/loggedin.php';
    
    			header("Location: $url");
    
    			exit(); // Quit the script.
    
    		} else {
    
     // No record matched the query.
    
    			echo '<p><font color="red">The email address and password entered do not match those on file.</font></p>';
    
     // Public message.
    			echo '<p><font color="red">' . mysql_error() . '<br /><br />Query: ' . $query . '</font></p>';
    
    // Debugging message.
    		}
    
    	} else { // Errors.
    
    		echo '<p><font color="red">Please try again.</font></p>';
    
    	} // End of if ($e && $p) IF.
    		
    	mysql_close();
    
    } // End of the main Submit conditional.
    
    // Display the form.
    
    
    ?>
    
    <h2>Login</h2>
    
    <form action="login.php" method="post">
    
    	<p>Email Address: <input type="text" name="email" size="20" maxlength="40" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /> </p>
    
            <p>Password: <input type="password" name="password" size="20" maxlength="20" /></p>
    
    	<p><input type="submit" name="submit" value="Login" /></p>
    
    	<input type="hidden" name="submitted" value="TRUE" />
    
    </form>
    
    </body>
    
    </html>
    
    
    <?php
    
    include ('./includes/footer.html');
    
    ob_end_flush(); // Send everything to the Web browser.
    
    ?>
    Last edited by Anne Arbor; 01-27-2014 at 12:30 AM.

  8. #8
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default

    And here, fwiw, is the actual script for entering the data. A registered user arrives at this page after logging in.

    Code:
    /* This script adds a log entry to the database.  */ 
    
    if (isset($_POST['submitted'])) { 
    
    require_once ('../mysql_connect_temp1.php'); 
    
    	$problem = FALSE;
    	if (!empty($_POST['temp_rating'])) {
    		$temp = mysql_real_escape_string(trim($_POST['temp_rating']));
    		$notes = mysql_real_escape_string(trim($_POST['notes']));
    
    	} else {
    		print '<p style="color: red;">Please submit a temp rating.</p>';
    		$problem = TRUE;
    	}
    
    	if (!$problem) {
    
    		// Define the query:
    		$query = "INSERT INTO temps (user_idm, temp_rating, notes, time_entered)
                      VALUES ('$_SESSION[user_id]', '$temp', '$notes', NOW())";
    
    		// Execute the query:
    		if (@mysql_query($query)) {
    			print '<p>The entry has been added!</p>';
    
    		} else {
    			print '<p style="color: red;">Could not add the entry because:<br />' . mysql_error() . '.</p><p>The query being run was: ' . $query . '</p>';
    		}
    	
    	} // No problem!
    
    	mysql_close();	
    } // End of form submission IF.    
    
    // The script next displays the form. . . . .  
    
    
    ?>
    Last edited by Anne Arbor; 01-26-2014 at 10:51 PM.

  9. #9
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by Anne Arbor View Post
    Traq, you seem to be suggesting that the problem might lie in the log-in code, so I'll supply that here:
    More likely, it lies in your session management, and is not being carried between requests reliably. For example, this:
    PHP Code:
    // Set the session data & redirect.
    session_start
    should be giving you an error message along the lines of
    Notice: Use of undefined constant session_start - assumed 'session_start' …
    (problem being, you forgot the parenthesis after the function name, and so PHP thought you were trying to use a constant and not a function.)

    In fact, I don't see any part of that code where you start a session successfully, so I'd expect there to be no session at all. The fact that you say the problem is intermittent would indicate that a session is started successfully sometimes, however.

    Quote Originally Posted by Anne Arbor View Post
    And here, fwiw, is the actual script for entering the data. A registered user arrives at this page after logging in.
    That may be part of the problem: just because the user is supposed to arrive at this page after logging in doesn't mean that they can't end up there some other way. It also does not guarantee that they are logged in when they arrive - if the login is successful but the session is not, then you'd still be taken to that page, but there would be no way of knowing if you were logged in.

    The solution to this is to check if the user is logged in on the same page they're supposed to be logged in on. Write a script (or just a function) that does only that, and run it at the top of any page that requires you to be logged in. Stop the script if the check fails, show the page if it is successful.

    This will also tell you whether your login script is working properly, or if the problem lies elsewhere.

    Quote Originally Posted by Anne Arbor
    I'd be glad of any way to solve this problem. One way that had occurred to me was there might be some way of plugging the "user_0" hole. Is there some way that I could assign that to someone (even me, using a different name)?
    You could, of course, add a new user record to your database and manually assign that user id. I would definitely not recommend this, since it would cause every not-logged-in user to be treated as if they were you (and I'm assuming you're the "admin"). That would be a potentially disastrous security hole: 0, especially in dynamically typed languages like PHP, is widely used as a "FALSE"-ish value. That, combined with the fact that MySQL auto-increments usually start with 1, leads a lot of CMS's to use "1" as the super-admin id, and "0" as the not-logged-in id. You don't want those two confused.

    BTW, are you using a CMS? or is this something custom written for you? by you?

  10. The Following User Says Thank You to traq For This Useful Post:

    Anne Arbor (01-27-2014)

  11. #10
    Join Date
    Jul 2010
    Location
    Near Albany, NY
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default

    Traq, this is a program that I cobbled together several years ago, relying on a fairly popular "Write your own program in PHP and MySQL" textbook.
    It seemed like a miracle to me that it worked at all and I was thrilled that it did. Now, several years later, I'm trying to "bring it up to code," so to speak, and then I'd like to add more features to it.

    I'll have to re-read your answer a few times and see how much I can understand. I will say that *most* of the time a session does start; just not always.

Similar Threads

  1. Resolved Program stopped adding new entries at end of db; inserts them out of chrono order
    By Anne Arbor in forum MySQL and other databases
    Replies: 15
    Last Post: 01-23-2014, 02:51 AM
  2. Form entries are not populating in mysql database
    By paybadvenilesh in forum MySQL and other databases
    Replies: 1
    Last Post: 04-02-2013, 02:18 PM
  3. Resolved NULL Error When Adding to Database
    By SChaput in forum MySQL and other databases
    Replies: 6
    Last Post: 10-17-2008, 01:04 AM
  4. Replies: 6
    Last Post: 07-27-2006, 08:40 AM

Bookmarks

Posting Permissions

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