Solved

Ajax using php/mysql

Posted on 2011-09-23
7
441 Views
Last Modified: 2012-05-12
I am building a web page using ajax to pull some data from my server which is a php/mysql server.
I am very weak in php so I expect I have something wrong in that area.

Starting at the beginning:

I have a dropdown where the user select a part number from the list.  On change I am calling my javascript function showUser.


<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  alert("str==empty");
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

This in turn call the getuser.php file on the server.

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'gdsquirrel', 'gdcart');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("dgsquirrelcart", $con);

$sql="SELECT * FROM Products WHERE Part_no = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Bullet 1</th>
<th>Bullet 2</th>
<th>Bullet 3</th>
<th>Bullet 4</th>
<th>Bullet 5</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['Bullet_1'] . "</td>";
  echo "<td>" . $row['Bullet_2'] . "</td>";
  echo "<td>" . $row['Bullet_3'] . "</td>";
  echo "<td>" . $row['Bullet_4'] . "</td>";
  echo "<td>" . $row['Bullet_5'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

My mysql info.

username  => gdsquirrel
passward => gdcart
db name   => gdsquirrelcart
table name => Products
row to fetch => Bullet_1 ..... Bullet_5

As far as I can tell I am getting into mysql,  I am getting the table heading to table to build, but I don't seem to be able to get the data back.

I don't really know how to bebug this,  so I hope it is something obvious to you guys.


0
Comment
Question by:jws2bay
  • 4
  • 2
7 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 400 total points
ID: 36590622
I would start with just getting the PHP and MySQL correct, then adding the AJAX layer later.  This code snippet shows the right ways to do some things in MySQL an PHP.  Read it over and see if it is helpful.  And if you're new to PHP, this book is a great learning resource.
http://www.sitepoint.com/books/phpmysql4/
<?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



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


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

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




// ESCAPE AN EXTERNAL DATA FIELD FOR 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)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// 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);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/>$sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $num ROWS OF DATA ";
    echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    var_dump($row);
}




// A WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];
$fmt = number_format($num);
echo "<br/>THERE ARE $fmt ROWS IN THE TABLE";




// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES ('$safe_username')";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
$id  = mysql_insert_id($db_connection);
echo "<br/>YOU JUST INSERTED A RECORD WITH AUTO_INCREMENT ID = $id";

Open in new window

0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 100 total points
ID: 36590624
try directly : http://www.youdomainname.com/path/to/getuser.php?q=1

update the part in bold

replace the << 1 >> with a valid Part_no


0
 

Author Comment

by:jws2bay
ID: 36590656
leakim971

When I try the direct call I get the sane results but not on my page.  Just the header table is generated.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:jws2bay
ID: 36590659
Bullet 1 Bullet 2 Bullet 3 Bullet 4 Bullet 5
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36590698
Please post the CREATE TABLE statement for the Products table.
0
 

Author Comment

by:jws2bay
ID: 36590706
Ray
I read the you info.  I modifed my code to give me the feedback on if I was connecting to the db.  I wasn't.  I spelled the name wrong.  I had dgsquirrelcart, and it should be gdsquirrelcart.

Thanks for the help

0
 

Author Closing Comment

by:jws2bay
ID: 36590714
Both experts helped me isolate the problem.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

708 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

17 Experts available now in Live!

Get 1:1 Help Now