Ajax mysql query not producing any data - php

Im very inexperienced with php and myadmin and have been trying to utilise some tutorials to use ajax to query a database.
I firstly want to loop through the database to give me a drop down list of options to choose from ie:
Food
Petrol
Shopping
Entertainment
Then I want the user to be able to select one of the dropdown options and this then will query the database and produce a table with data on that selection
ie if they choose petrol it will produce a table
Payee Amount Date
Tesco 23.00 27/10/13
Sainsbury 20.00 20/10/13 etc
Here is my code for the ajax
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("output").innerHTML="";
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("output").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","catagory.php?catagory="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$server = 'localhost';
$user='root';
$pass='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $pass, $db);
$query = $mysqli->query("SELECT distinct `catagory` FROM `transactions`");
while($array[]= $query->fetch_object());
array_pop($array);
?>
<h3>Transactions</h3>
<select name="the_name" onchange="showUser(this.value)">
<?php foreach ($array as $option): ?>
<option value="<?php echo $option->Transaction; ?>"><?php echo $option -> catagory;?></option>
<?php endforeach; ?>
</select>
<div id="ouput"<b>Transactions:</b></div>
<?php
$query-> close();
?>
</body>
</html>
And here is my code to query the database:
<?php
$q = $_GET['catagory'];
$con = mysqli_connect('localhost','root','','finance_checker');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"finance_checker");
$sql="SELECT `ThirdParty`, `Credit`,`Date` FROM `transactions` WHERE `catagory` = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Payee</th>
<th>Amount</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ThirdParty'] . "</td>";
echo "<td>" . $row['Credit'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The initial code is producing the correct dropdown options, however when I select one of the options I do not get anything reproduced.
I thought I had understood what was going on but clearly somewhere I have missed something would anyone be able to offer further guidance?

Since you only...
SELECT distinct `catagory` FROM `transactions`
...$option->Transaction would always be undefined.

When you load data in select box please check the select query. Try below one
$query = $mysqli->query("SELECT distinct `catagory`,`Transaction` FROM `transactions`");

Related

problems with ajax, only displays the header and not the records

I have a problem with this code.
I created a drop-down menu that directly takes the categories from the database. so far everything is ok.
When, however, I choose the type, it only displays the header of the table and not the records.
can you tell me why?
I think the problem is "q" but I do not know how to modify it becouse I tried to do the query without 'Where' and correctly displays the records.
<html>
<script>
var xmlhttp;
function mostraInfo(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="2.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("info").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
<form>
Seleziona Categoria:
<select name="users" onChange="mostraInfo(this.value)">
<option value="">Seleziona categoria:</option>
<?php
//Seleziono quelli che sono i dipendenti
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$query = "SELECT distinct tipologia FROM gruppi ORDER BY tipologia ASC";
$result = mysql_query($query);
while($riga = mysql_fetch_array($result)){
echo "<option value='$riga[nome_gruppo]'> $riga[tipologia] </option>";
}
?>
</select>
</form>
<br />
<div id="info"></div>
</html>
----- file 2(2.php)------
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
$result = mysql_query($sql);
echo "<table border='2'>
<tr>
<th> Nome Gruppo </th>
<th> Email </th>
<th> Tipologia </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nome_gruppo'] . "</td>";
echo "<td>" . $row['email_gruppo'] . "</td>";
echo "<td>" . $row['tipologia'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
It seems your problem is the query,you are using double quotation inside single quote, Try this instead :
$sql="SELECT * FROM gruppi WHERE tipologia = '{$q}'" ;
From the code, you've provided, I don't see where is $q defined.
So I believe in the end your query looks like:
"SELECT * FROM gruppi WHERE tipologia = ''"
You can always dump something in order to check what's really going on by inserting temporary code like this:
var_dump($sql);exit;
Just don't forget to remove/comment it after debugging ;)
Solution:
You need to get "q" parameter from the GET request:
$q = mysql_real_escape_string($_GET['q'], $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
mysql_real_escape_string function is there to prevent some simple SQL injections. Please check this out http://php.net/manual/en/function.mysql-real-escape-string.php
But it would be better to use at least PDO class instead of outdated "mysql_" functions.
Complete code of 2.php with fix:
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$q = mysql_real_escape_string($_GET['q'], $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
$result = mysql_query($sql);
echo "<table border='2'>
<tr>
<th> Nome Gruppo </th>
<th> Email </th>
<th> Tipologia </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nome_gruppo'] . "</td>";
echo "<td>" . $row['email_gruppo'] . "</td>";
echo "<td>" . $row['tipologia'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>

retrieve data using Ajax and mysql

I'm trying to retrieve data from multiple table. So when the user clicks and select an item php file to retrieve the data from the corresponding table.
this is my first try on Ajax used w3 school code and trying to modify, I guess the way I'm using if condition is the problem? Before I try with the multiple table it worked.
My Script
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "Please Select type of users to view";
return;
} else {
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","get_users.php?q="+str,true);
xmlhttp.send();
}
}
</script>
My Form
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
</select>
</form>
My PHP Page
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','X','X','X');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
if ($q='Admin')
{
$sql="SELECT * FROM admin";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Mobile</th>
<th>Address</th>
<th>Password</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
}
echo "</table>";
else if ($q='Staff')
{
echo "This is from Database B
}
else
{
echo "This is from database C";
}
mysqli_close($con);
?>
You're using $q = intval($_GET['q']); with a string value for your assignments.
intval() "Get the integer value of a variable"
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
and using an assignment rather than a comparison for both if ($q='Admin') and else if ($q='Staff') both being strings, as opposed to integers in your options.
which should read as and with 2 equal signs if ($q=='2') and else if ($q=='1') in order to match your select's numerical value options.
Or, change them accordingly with your options to read as Staff and Admin (and Customers) in the values, while removing the intval() from the GET array; the choice is yours.
You also don't need mysqli_select_db($con); since you've declared your 4 parameters in your initial connection and would fail for another reason; technically you didn't select a database for it.
You're also missing a quote and semi-colon in (a parse syntax error)
echo "This is from Database B
which should read as
echo "This is from Database B";
Footnotes:
The page which I believe you based yourself on, seems to be http://www.w3schools.com/php/php_ajax_database.asp
If so, then I suggest you follow their example completely and modify it slowly to fit your needs. I myself have used that demo (in the distant past) before with success.
Their example uses a WHERE clause also.
$sql="SELECT * FROM user WHERE id = '".$q."'";
Edit: Just for the record, there is a missing brace for this condition:
if ($q='Admin')
{

Run SQL query and update form on drop-down selection

So I have two drop-down lists Category and Sub-category. Sub-category has to be populated by an SQL query once a Category is selected.
I know how to populate from an SQL query:
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table";
$result = mysql_query($sql);
echo "<select name='col'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
But I don't know how to run the query and update list in jQuery:
function updateList(){
//QUERY&fill based on selection//
.val($('select[name="category"] option:selected').val());
}
I spent an hour or so on google and couldn't manage to solve this.
you have to create onchange function in selecting main category and pass it to either jquery or javascript ajax request response to get value from another file having subcategory output with sql where condition as main category value.
echo "<select name='col' onchange='loadXMLDoc()'>";
the above of main cat drop down and its ajax javascript reqest response whould be as below
<script>
function loadXMLDoc()
var maincat=document.getElementByName("col").val();
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("maincat_var=maincat");
}
Create a div with id as myDiv in your main page.
and the other page should have
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table where main_cat=$_POST['maincat_var']";
$result = mysql_query($sql);
echo "<select name='col2'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
You can try using jquery and ajax to load values of subcategory .
Try modifying and using the below code. This code may guide you..
$(document).ready(function(){
$('#submit').click(function() {
$.ajax(
{
url:"subcat.php?id='something'", // Here you can write php variableto pass to next page
success:function(result){
$("#div1").html(result);
}
});
return false;
});
});
onclicking the main category some page will be executed and its output will be displayed in a html element.

Error when using drop menu to change database value

When i select a drop menu option to change a value in my database to the selected value it gives this error:
SyntaxError: missing ) after argument list changeGroup("email#email.com")
Basically what im trying to do is I have an app that stores contacts, in the ungrouped contacts section it has the drop menu and when u select a value from it it submits the values and uses the value to update the database. I use the:
action='javascript:changeGroup(".$contactDetails.")
to tell the update statement which contact to update.
my code:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<!--Links to CSS file for formatting-->
<link href="Contacts.css" rel="stylesheet" type="text/css"/>
<!--Links to Javascript file for the for action to change the group of a contact-->
<script src="ajax.js" language="javascript"></script>
<?php
$contactDetails = $_GET['contactDetails'];
$cdquery="SELECT * FROM `contacts` WHERE `newEmail` = '$contactDetails'";
$cdresult=mysql_query($cdquery) or die ("Query to get data from first table failed: ".mysql_error());
while ($row = mysql_fetch_assoc($cdresult))
{
echo "" . $row['newFname'] . " " . $row['newLname'] . "'s " . "Details:";
echo "<table>";
echo "<tr>";
echo "<th>Name:</th>";
echo "<th>Email Address:</th>";
echo "<th>Phone:</th>";
echo "<th>Postal Address:</th>";
echo "<th>Group:</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['newFname'] . " " . $row['newLname'] . "</td>";
echo "<td>" . $row['newEmail'] . "</td>";
echo "<td>" . $row['newPhone'] . "</td>";
echo "<td>" . $row['newAddress'] . "</td>";
echo "<td>" . $row['group'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<form action='javascript:changeGroup(".$contactDetails.")' method='get'> Add contact to
<select id='group' name='group' onchange='this.form.submit(value=this.options[this.selectedIndex].value)'>
<option>Select a group...</option>
<option value='Family'>Family</option>
<option value='Friends'>Friends</option>
<option value='Colleagues'>Colleagues</option></select>
group.</form>";
mysql_close($link);
?>
ajax function:
function changeGroup(str)
{
document.getElementById("content02").innerHTML="";
if (str=="")
{
document.getElementById("content02").innerHTML="";
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("content02").innerHTML=xmlhttp.responseText;
document.getElementById("content02").innerHTML = "";
}
}
xmlhttp.open("GET",'getChangeGroup.php?contactChange='+contactChange+'&group='+group,true);
xmlhttp.send();
xmlhttp.onreadystatechange = changeReload;
xmlhttp.send(null);
}
php:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<!--Links to CSS file for formatting-->
<link href="Contacts.css" rel="stylesheet" type="text/css"/>
<?php
$contactChange = $_GET['contactChange'];
$group = $_GET['group'];
$cdquery="UPDATE `contacts` SET `group` = '$group' WHERE `newEmail` = '$contactChange'";
$cdresult=mysql_query($cdquery) or die ("Query to get data from first table failed: ".mysql_error());
mysql_close($link);
?>
I don't really know what your code does, nor do I have the patience to completely replicate it on my end, but as it stands you are passing a variable to your function, instead of a string, on this line:
echo "<form action='javascript:changeGroup(".$contactDetails.")' method='get'> Add contact to
To fix that, you need to quote your string as an actual string:
echo "<form action='javascript:changeGroup(\'".$contactDetails."\')' method='get'> Add contact to
I would assume this is your main issue. Without those quotes, javascript treats your echoed variable as a js variable, instead of a string.
In regards to your db interaction...
Also, you are using a deprecated.. and soon to be removed database interaction API. I recommend PDO to replace it, it prevents injection attacks and won't be removed in the near future, learn more about it here.

Retrieve mySQL Data On Radio Button Click

Through some very much appreciated help from users of this site I've been able to put together a script that upon a radio button click will populate a table with user details.
I thought that I'd be able to adapt it even further, but, quite possibly because of my lack of experience, unfortunately I've come across another problem, hence why I've added a new post.
Pulling the data from a mySQL database I'm using the code below to create a list of dates with an associated radio button.
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
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","getuser2.php?="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 GROUP By dateoftrip ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
echo"<table>\n";
while (list($userid, $dateoftrip) =
mysql_fetch_row($result))
{
echo"<tr>\n"
.
"<td><input type='radio' name='show' dateoftrip value='{$userid}' onClick='showUser(this.value)'/></td>\n"
."<td><small>{$dateoftrip}</small><td>\n"
."</tr>\n";
}
echo'</table>';
}
?>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Then with the following code I want to populate a table with the associated 'findname' details for the radio button clicked.
<?php
$q=$_GET["q"];
$con = mysql_connect('hostname', 'username', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database', $con);
$sql="SELECT * FROM finds WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Find Name</th>
</tr>";
while($row = mysql_fetch_array($sql))
{
echo "<tr>";
echo "<td>" . $row['findname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I can get the first part of the script to work, i.e. the creation of the date list and radio buttons, but when I select the radio button, the table appears with the correct column heading, but I receive the following error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/2/d333603417/htdocs/development/getuser2.php on line 21 with line 21 being this line: while($row = mysql_fetch_array($sql)).
As I said earlier the other users that answered my first post were great, but I just wondered if someone could perhaps have a look at this please and let me know where I've gone wrong.
Updated Code
Form
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
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","getuser2.php?="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.findid, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.locationid=detectinglocations.locationid AND finds.userid = 1 GROUP By dateoftrip ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
echo"<table>\n";
while (list($findid, $dateoftrip) =
mysql_fetch_row($result))
{
echo"<tr>\n"
.
"<td><input type='radio' name='show' dateoftrip value='{$findid}' onClick='showUser(this.value)'/></td>\n"
."<td><small>{$dateoftrip}</small><td>\n"
."</tr>\n";
}
echo'</table>';
}
?>
<br />
<div id="txtHint"></div>
</body>
</html>
PHP
<?php
//$q=$_GET["q"];
$con = mysql_connect('hostname', 'username', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database', $con);
$sql="SELECT * FROM finds";
$result = mysql_query($sql);
// This is helpful for debugging
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo "<table border='1'>
<tr>
<th>Find Name</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['findname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
while ($row = mysql_fetch_array($result))
not
while ($row = mysql_fetch_array($sql))
mysql_fetch_array accepts a mysql result object (which you get from the mysql_query function call), not a string
In $row = mysql_fetch_array($sql)
$sql is a string, you should use $result instead, which is a mysql_result object.

Categories