Jump to content

serious connection problems


cubx

Recommended Posts

I'm using php 5.2 and mysql 5.1 on my fedora 5 server. Apache 2 and the mysql daemons are both running fine. But I am having constant problems getting php to connect to the mysql daemon on the same machine. It was working very briefly, then it stopped. I cannot find any errors that tell me much.

Here is the entire code:

<HTML>
<HEAD>
<TITLE>New Document</TITLE>
</HEAD>
<BODY>

<?php

// Have the username and password been filled out

function form(){
        echo "<table width=\"100%\" height=\"5%\" bgcolor=\"cyan\">";
        echo "<tr>";
        echo "<td bgcolor=\"white\" width=\"20%\"><font color=\"green\">&nbsp;&nbsp;&nbsp;<font size=+1><b>Step 1</b></font></td>";
        echo "<td>&nbsp;&nbsp;&nbsp;<font size=+1 color=\"white\"><b>Step 2</b></font></td>";
        echo "<td>&nbsp;&nbsp;&nbsp;<font size=+1 color=\"white\"><b>Step 3</b></font></td>";
        echo "<td>&nbsp;&nbsp;&nbsp;<font size=+1 color=\"white\"><b>Step 4</b></font></td>";
        echo "<td>&nbsp;&nbsp;&nbsp;<font size=+1 color=\"white\"><b>Step 5</b></font></td>";
        echo "</tr>";
        echo "<tr bgcolor=\"white\">";
        echo "<td bgcolor=\"red\" width=\"20%\">&nbsp;&nbsp;&nbsp;<b><i><font size=+1>LOG IN</i></b></td>";
        echo "<td></td>";
        echo "<td></td>";
        echo "<td></td>";
        echo "<td></td>";
        echo "</tr>";
        echo "</table>";

        echo "<br><br><br><br><br><br><br><br><br><center>";
        echo "<table border=\"0\" bgcolor=\"#66ccff\" cellpadding=\"10\">";
        echo "<form action='" .$_SERVER['PHP_SELF'] ."' method='post'>";
        echo "<tr><td>What username do you want?</td><td><input type='text' name='username'></td>";
        echo "<tr><td>Pick a password (5-15 characters):</td><td><input type='password' name='password'></td>";
        echo "<tr><td colspan=2 align=center><br><input type='image' name='Submit' value='Submit' src='submit.gif'>";
        echo "</form>";
        echo "</table></center>";
}
       
function connect_to_db() {
    $link = mysql_connect('localhost', 'root', 'rootpassword');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
        }
        else
    $db_selected = mysql_select_db('mydb', $link) or die(mysql_error());
    if (!$db_selected) {
        echo "Cannot use database<br>";
        echo "mysql_error()";
        }
        else
        return TRUE;
}

//function checklength($string, $min, $max) {
//  $length = strlen ($string);
//  if (($length < $min) || ($length > $max)) {
//    return FALSE; // too short or long
//  } else {
//    return TRUE;
//  }
//}

if (!isset($_POST['Submit']))
    form();
else
  while (connect_to_db())
  if (!empty($_POST['username']) && !empty($_POST['password']))
//      if(!checklength($_POST['password'], 5, 15)
//        echo "Password must be between 5-15 characters";

  // Query the database
  $sql = "SELECT username FROM accounts WHERE username = '{$_POST['username']}'";

  // Check if we got a result returned
  $result = mysql_query($sql);
  if (!$result){
      echo "Couldn't execute: $sql<br><br>\n" . mysql_error();
  }
  else {
  // Does the user exist, how many rows were retrurned
      if (mysql_num_rows($result) > 0){
        echo "Username already in use\n";
      }
      else {
        echo "Username doesn't exist\n";
      }
      echo "here is the form";
}

?>

</BODY>
</HTML>

When I pull up the IP address in Firefox, I get this BEFORE I even type anything into the fields:

Warning: mysql_query() [function.mysql-query]: Access denied for user 'daemon'@'localhost' (using password: NO) in /home/www/public_html/form2.php on line 75

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/www/public_html/form2.php on line 75
Couldn't execute:

Access denied for user 'daemon'@'localhost' (using password: NO)


I go ahead and type in a username and password, then get a blank screen. The database username is root, and it has worked before. But what I don't understand is why I get the error that the server connection could not be established, when the connect_to_db() isn't giving me an error.

Mysql loads and reads the database just fine from the command line.

Any suggestions on what to look for?
Link to comment
https://forums.phpfreaks.com/topic/29356-serious-connection-problems/
Share on other sites

Try specifying the link identifier with each mysql_query() call.  It sounds like you are triggering a new database connection when you don't specify it.

[code=php:0]mysql_query($sql, $link);[/code]


You'll also need to make $link global.  Add [code=php:0]global $link;[/code] in connect_to_db(), and inside each function that you use $link in.
I made these changes:

function connect_to_db() {
    global $link;

... rest of function code is the same ...

if (!isset($_POST['Submit']))
    form();
else
  while (connect_to_db())
  if (!empty($_POST['username']) && !empty($_POST['password']))
//      if(!checklength($_POST['password'], 5, 15)
//        echo "Password must be between 5-15 characters";

  // Query the database
  $sql = "SELECT username FROM accounts WHERE username = '{$_POST['username']}'";

  // Check if we got a result returned
  $result = mysql_query($sql, $link);
  if (!$result){
      echo "Couldn't execute: $sql<br><br>\n" . mysql_error();
  }
  else {
  // Does the user exist, how many rows were retrurned
      if (mysql_num_rows($result, $link) > 0){
        echo "Username already in use\n";
      }
      else {
        echo "Username doesn't exist\n";
      }
      echo "here is the form";
}

I added the $link to the mysql commands here. Nothing else. The globals variable is inside the connect function only. Now when I reload the page I get:

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/www/public_html/form2.php on line 76
Couldn't execute:

And that's all. I thought a global variable had to be outside of a function? It seems to me that the connect is there in the beginning, but as soon as I test usernames or queriers, the connection is dead.
A global variable needs to be specified in every function it is used in.  Other than that, it can be defined anywhere, inside or outside a function.

I'm a bit suspicious about your "while (connect_to_db())" .. what is that intended to do?  Why not just "if (connect_to_db()) { } else { echo "Couldn't connect"; }" ?
So a global variable MUST be defined inside each function I use it in, it's really not global then, right?

As for the while connected, I did that because I figured that would make sure the database was connected the whole time. Apparently that was the problem. I switched it to an if statement and now it's working.

Very strange, but you were correct.

My last question is when I bring up the form, before I even type in a name, it automatically has "Couldn't execute:" and "Query was empty", which are a little further down in the code. It seems like it is trying to execute those commands before I even hit submit, yet when I hit submit, it does work properly.

Is there a better way I can avoid this?
I think the problem was your while() .. If I include the implicit braces, your code is this:

[code=php:0] while (connect_to_db()) {
  if (!empty($_POST['username']) && !empty($_POST['password'])) {
    // Query the database
    $sql = "SELECT username FROM accounts WHERE username = '{$_POST['username']}'";
  } /* end of if */
} /* end of while */[/code]


What that will do is it will keep connecting to the db and setting $sql UNTIL THE DB CONNECTION FAILS, at which point it will continue.  It should be this:

[code=php:0] while (!connect_to_db());[/code]


That would keep running connect_to_db() until it returns true, then it'll end the loop.

Regarding global variables, they must be [b]specified[/b] in each function they are used in, but they are shared among all functions which specify them.  That's why they are global.

About your second question, I think you are missing braces.  You should do like this:

[code=php:0]if (condition) {
  blah;
  blah;
} else {
  blah;
  blah;
}[/code]
I changed that while to an if for the connection and that solved the problem. You were right. Man I thought I was fairly good in C.

I get the global variable thing now. Yes I knew what they were, but I had never heard of defining them in each function. That almost sounds like a PHP requirement. As for the code that was executing before submit, I did what you both said, wrapped that section in an if and now it works fine.

Thank you!!

Archived

This topic is now archived and is closed to further replies.

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