Solved

PHP connection with 'localhost' for ajax form validation.

Posted on 2012-04-11
10
848 Views
Last Modified: 2012-04-17
I've this php script as below.

First question: I'm using MAMP as 'localhost' 'root' and how do I connect or add 'localhost' 'root' in php as below? In order for form validation to work? I'm using Dreamweaver CC5.5.

Second question: I'll use collegeData.sql as well. Do I need collegeData.sql? The Username is studentID and that will end up in collegeData.sql

My database information is:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData.sql';



My problem php is:
<?php

if (@$_REQUEST['action'] == 'check_username' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    echo json_encode(check_username($_REQUEST['username']));
    exit; // only print out the json version of the response
}
?>

The HTML code is
<!DOCTYPE HTML>
<html lang="en">
      <head>
      <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
      <title>jQuery for Designers - Ajax Form Validation Example</title>
      <style type="text/css" media="screen">
<!--
BODY {
&#9;margin: 10px;
&#9;padding: 0;
&#9;font: 1em "Trebuchet MS", verdana, arial, sans-serif;
&#9;font-size: 100%;
}
H1 {
&#9;margin-bottom: 2px;
&#9;font-family: Garamond, "Times New Roman", Times, Serif;
}
TEXTAREA {
&#9;width: 80%;
}
INPUT, TEXTAREA {
&#9;font-family: Arial, verdana;
&#9;font-size: 125%;
&#9;padding: 7px;
}
LABEL {
&#9;display: block;
&#9;margin-top: 10px;
}
IMG {
&#9;margin: 5px;
}
#message {
&#9;border: 1px solid #ccc;
&#9;background-color: #ffa;
&#9;padding: 5px;
}
DIV.submit {
&#9;background: #eee;
&#9;border: 1px solid #ccc;
&#9;border-top: 0;
&#9;padding: 1em;
&#9;text-align: right;
&#9;margin-bottom: 20px;
}
-->
</style>
      <script src="jquery.js" type="text/javascript"></script>
      <script type="text/javascript">
      <!--
      $(document).ready(function () {
          // Username validation logic
          var validateUsername = $('#validateUsername');
          $('#username').keyup(function () {
              // cache the 'this' instance as we need access to it within a setTimeout, where 'this' is set to 'window'
              var t = this; 
              
              // only run the check if the username has actually changed - also means we skip meta keys
              if (this.value != this.lastValue) {
                  
                  // the timeout logic means the ajax doesn't fire with *every* key press, i.e. if the user holds down
                  // a particular key, it will only fire when the release the key.
                                  
                  if (this.timer) clearTimeout(this.timer);
                  
                  // show our holding text in the validation message space
                  validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif" height="16" width="16" /> checking availability...');
                  
                  // fire an ajax request in 1/5 of a second
                  this.timer = setTimeout(function () {
                      $.ajax({
                          url: 'ajax-validation.php',
                          data: 'action=check_username&username=' + t.value,
                          dataType: 'json',
                          type: 'post',
                          success: function (j) {
                              // put the 'msg' field from the $resp array from check_username (php code) in to the validation message
                              validateUsername.html(j.msg);
                          }
                      });
                  }, 200); // this 200? It can be removed.
                  
                  // copy the latest value to avoid sending requests when we don't need to
                  this.lastValue = this.value;
              }
          });
      });
      //-->
      </script>
      </head>
      <body>
      <div>

&#9;&#9;<form action="" method="post">
            <fieldset>
        <label for="username">Username, valid: a-z.-_</label>
        <input type="text" name="username" value="<?=@$_REQUEST['username']?>" id="username" />
        <span id="validateUsername">
  &#9;&#9;<?php if ($error) { echo $error['msg']; } ?>
  &#9;&#9;</span>
&#9;&#9;</fieldset>
 &#9;&#9;<input type="hidden" name="action" value="register" />
&#9;&#9;<input type="submit" name="register" value="Register" id="register" />
&#9;&#9;<!-- End form-->
&#9;&#9;</form>
        </div>

&#9;</body>
&#9;</html>

Open in new window

0
Comment
Question by:Redscrapbook
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 1

Expert Comment

by:chrisroch
Comment Utility

First Question

I am not 100% clear as to what you are asking here. Are you trying to find out how to connect to a database? If so, I would advice you to check out tutorials on the web that can give you details for connecting to a database from PHP,  for e.g. http://www.w3schools.com/php/php_mysql_intro.asp provides a decent tutorial for using php alongside mysql.


Second Question

Based on your question I will assume you are carrying out a username check against a database. However, it seems as if you have not created a database as yet, since you have set the database variable to the name of your SQL script file "collegeData.sql".  Ensure that you have created a database on your server that will be used by your application, and set the database variable in your script with the name of said database. You can refer to the link I provided above to guide you in this process.
0
 

Author Comment

by:Redscrapbook
Comment Utility

Second Question

The data is already in MySQL and it is stored in database objects in three moduleTable, lecturerTable and studentsTable from collegeData.mysql. I would appreciate if you can point out one example for moduleTable in a php script so I can fully be clear.

------------------------------------------------------
|  studentID  | firstName| lastName  |  
------------------------------------------------------
| 123             | Kermit      | Frog           |
| 124             | Gonzo      |Great           |
| 125             | Cookie     | monster      |
------------------------------------------------------
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
You have many thing wrong there.  First, do you get the default web page when you go to "http://locahost/" ?

Second, 'collegeData.sql' is not the Name of the database though 'collegeData' might be.  'collegeData.sql' should be the file that you imported into MySQL to create the database.

Third, $_SERVER['HTTP_X_REQUESTED_WITH'] is an unreliable variable.  It isn't necessarily set properly or preserved properly.

Fourth, there is no database access in the 'php page' you posted.  All you are doing is echoing something you're sending to the page.

If you need it, here http://us2.php.net/manual/en/book.mysql.php is the PHP page on using 'mysql'.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
Comment Utility
You might want to consider getting this book.  It will not make you a pro, but it is very readable and will give you some foundation in the way these things work.
http://www.sitepoint.com/books/phpmysql4/

A couple of "always and never" things that will make your life easier...

Add these lines to the top of EVERY script you run.
error_reporting(E_ALL);
ini_set('display_errors', TRUE);

NEVER use the @ notation -- it suppresses function error messages.  You really want to see the error messages, or else you will be guessing about whether the function worked.  And in this line, it's misplaced since it is prepended to a variable instead of a function.
if (@$_REQUEST['action']...

This line of code calls two PHP functions.  One of them is a native PHP function.  The other one, check_username() appears to be undefined, or at least omitted from the script posted here.  You'll want to check and be sure that function works.
echo json_encode(check_username($_REQUEST['username']));

Going forward with PHP and MySQL questions here at EE, one of the best things you can do to help get quick answers is show us the data you have and the data you want.   That means posting the CREATE TABLE statements along with some representative data so we can see what is in your data base and how it is organized.   Armed with that kind of information we can usually help very quickly.

The code snippet shows a little bit of the kind of PHP that you would use to check the user name against a data base.
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQL
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
// MAN PAGE: http://php.net/manual/en/function.mysql-query.php
// MAN PAGE: http://php.net/manual/en/function.mysql-errno.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php
// MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-array.php
// MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php



// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";


// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $err <br/>";
}

// SELECT THE MYSQL DATA BASE
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $err <br/>";
    die('NO DATA BASE');
}
// IF THE SCRIPT GETS THIS FAR IT CAN DO QUERIES




// ESCAPE ALL DATA FIELDS BEFORE USE IN MYSQL QUERIES
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, SHOW THE ERROR
if (!$res)
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/> $sql <br/>";
    die($err);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = mysql_num_rows($res);
$fmt = number_format($num);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/> $sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $fmt ROWS OF DATA ";
    echo "<br/> $sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    // ROW BY ROW PROCESSING IS DONE HERE
    var_dump($row);
}

Open in new window

HTH, ~Ray
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 50

Assisted Solution

by:Steve Bink
Steve Bink earned 250 total points
Comment Utility
DaveBaldwin's post highlights a few issues with your code and approach.  In addition, I would add that $_REQUEST might not be what you want (see $_GET, $_POST, and $_SERVER instead).  Using the information you provided about your database, here is a simple test you can run for connectivity:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData.sql';
if ($link=mysql_connect($dbhost,$dbuser,$dbpass,$dbname)) {
  echo "connected";
} else {
  echo "failed";
}
?>

Open in new window


If you see "failed", check the results of mysql_connect_error()/mysql_connect_errno() for why it failed and correct that issue.  

Finally, you're using the root account.  That is a huge no-no.  Create a separate account for your application, with only as much access as is required for it.  Make sure you assign a strong password (minimum 8 characters, with alphanumeric mixed-case *and* symbols).  While you're at it, give the root account one, too.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@routinet: Regarding the use of the root account, this kind of set up is common in classroom settings where each student has a Mac and an individual MAMP set up on his computer.  It would be a security exposure in the "real world" but in the classroom, the entire build for applications like these consists of copying the script into htdocs/ and clicking on the name.  Probably nobody else uses the computer, and probably the data model gets wiped clean every night.

:-)

~Ray
0
 
LVL 50

Expert Comment

by:Steve Bink
Comment Utility
@Ray: very true, but still good advice.

I was also going to point out that one of the things wrong here was the use of Dreamweaver, but that could just be me. ;)
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@routinet:  A few histrionics here, but also a few good points.
http://w3fools.com/  

They have a comment on Dreamweaver.  I agree about the use of Dreamweaver.  It's led too many would-be programmers into a morass of horribly written PHP code, with the result that they render themselves unemployable at any place that does not use Dreamweaver (ie: they are permanently excluded from all the high-value jobs).
0
 

Author Closing Comment

by:Redscrapbook
Comment Utility
Thank you to Ray and Routinet for the input. Routinet for test the connectivity and and it works, I was able to see instinct results.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now