php count error - php

As you see I have created drop down and give it name the field name, and I have also the count function.
What I want to do is, if some select drop down menu..show the how many result found in number like 10, 20,.. if the second dropdown selected it will check the two drop down selected and pass the result count..like that continuous..if you want to see example what exactly I want is go here and choose car the count will update..
http://en.comparis.ch/Carfinder/marktplatz/Search.aspx
I have the ajax and working well but I can't get the exact PHP code to count in live time.
AJAX Code..
var xmlHttp
function showCount(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="phpApplication.php";
url=url+"?action=count2";
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("countR").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP Code
function dropdown($field, $table)
{
//initialize variables
$oHTML = '';
$result = '';
//check to see if the field is passed correctly
if (($field == "")||($table == ""))
{
die("No column or table specified to create drop down from!");
}
$sql = "select distinct($field) from $table";
//call the db function and run the query
$result = $this->conn($sql);
//if no results are found to create a drop down return a textbox
if ((!$result) ||(mysql_num_rows($result)==0))
{
$oHTML .= "<input type='text' name='$field' value='' size='15'>";
}elseif (($result)&&(mysql_num_rows($result)>0)){
//build the select box out of the results
$oHTML .= "<select name='$field' onchange='showCount(this.value)'>\n<option value='all'>All</option>\n";
while ($rows = mysql_fetch_array($result))
{
$oHTML .= "<option value='".$rows[$field]."' name='".$rows[$field]."'>".$rows[$field]."</option>\n";
}
$oHTML .= "</select>\n";
}
//send the value back to the calling code
return $oHTML;
}//end function
function count1(){
$sql2 = "SELECT SQL_CALC_FOUND_ROWS * from produkt_finder_table where Bauform_d ='".($_POST['Bauform_d'])."' ";
$query = $this->conn($sql2);
$result = mysql_query( $query );
$count = mysql_result( mysql_query( 'SELECT FOUND_ROWS()' ), 0, 0 );
echo $count;
//$sql2 = "SELECT COUNT(Bauform_d) from produkt_finder_table where Bauform_d = 'mobil' ";
//echo var_dump($result1);
while($row = mysql_fetch_array($query))
{
// echo $row['COUNT(Bauform_d)'];
}
//echo mysql_num_rows($query);
// if (isset($_POST['Bauform_d']))
//{
/* if (mysql_num_rows($result)==0) {
echo '0';
} else {
echo mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $result;
echo $row['COUNT(Bauform_d)'];
// }
}*/
}
$action = $_GET['action'];
$proFin = new Application();
switch($action) {
case 'show':
$proFin->show_form();
break;
case 'search':
$proFin->search();
break;
case 'searchAll':
$proFin->searchAll();
break;
case 'count2':
$proFin->count1();
break;
}

What parts have you debugged?
Change the count1() function to just echo back the time or something using time().
Then if it returns the correct value you know your JS is working and your PHP script is calling the correct function.
I assume that the PHP code doesnt work as the SQL query is looking for $_POST['Bauform_d'] which isnt set when you call the xmlHTTP Request. Run a simple print_r($_POST); to make sure you are passing all the data you expect in the query. If it is not then change your JS code to pass the value - when you are sure your php script is being passed all the correct variables then begin to add back in your SQL query etc.

debug debug
Jacob's answer is the key.

Related

Check if two column match on SQL PHP

I have a form where the user has to enter their reservation id and last name. If these two values match in the database then I need to return the corresponding values from the database.
I have two files, one that is html where I use ajax and one php file. When clicking on the button, nothing is being returned, I am not seeing any specific errors and I am sure that the value I put in are correct.
<script>
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
if(reservation_id)
{
var param = "?reservation_id=" + reservation_id + "&guest_last_name=" + guest_last_name;
var url = "test04.php";
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
var guest_full_name = document.getElementById('guest_full_name');
var unit_number = document.getElementById('unit_number');
var floor = document.getElementById('floor');
var key_sa = document.getElementById('key_sa');
if(!!ajax.responseText) {
var result = JSON.parse(ajax.responseText);
if(!!result){
guest_full_name.innerHTML = (!!result.guest_full_name) ? result.guest_full_name : '';
unit_number.innerHTML = (!!result.unit_number) ? result.unit_number : '';
floor.innerHTML = (!!result.floor) ? result.floor : '';
key_sa.innerHTML = (!!result.key_sa) ? result.key_sa : '';
}
}
}
}
</script>
<p id='employee_name'></p>
<p id='employee_age'></p>
<p id='safe_code'></p>
My test04.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id = mysqli_real_escape_string($conn, $_GET['reservation_id']);
$guest_last_name = mysqli_real_escape_string($conn, $_GET['guest_last_name']);
$query = "SELECT reservation_id, guest_full_name, guest_last_name unit_number, floor, key_sa FROM reservations2 INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg) INNER JOIN unit USING (unit_id) where reservation_id ='".$reservation_id."'AND guest_last_name ='".$guest_last_name."";
$result = mysqli_query($conn, $query) or die(mysql_error());
$response = array();
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$response['guest_full_name'] = ($row['guest_full_name'] != '') ? $row['guest_full_name'] : '';
$response['unit_number'] = ($row['unit_number'] != '') ? $row['unit_number'] : '';
$response['floor'] = ($row['floor'] != '') ? $row['floor'] : '';
$response['key_sa'] = ($row['key_sa'] != '') ? $row['key_sa'] : '';
}
}
echo json_encode($response, true);
?>
I am not seeing any specific errors
Where are you looking?
Did you check the raw response from the PHP script or just look at what was rendered in your browser?
Did you verify that error logging is working and did you check your logs?
The logic of your PHP is unclear - your JSON data and the PHP array can't handle multiple records yet you process multiple records. It would be nice to implement REST properly. This should also apply authentication and use CSRF for security - but I'll assume you left those out for illustrative purposes.
Your code is not written to handle failures or missing data. Consider (noting all the differences with what you posted):
<?php
$conn = mysqli_connect("","","","");
$response = array();
$reservation_id = mysqli_real_escape_string($conn, $_GET['reservation_id']);
$guest_last_name = mysqli_real_escape_string($conn, $_GET['guest_last_name']);
$query = "SELECT reservation_id, guest_full_name
, guest_last_name unit_number, floor, key_sa
FROM reservations2
INNER JOIN guest
ON (reservations2.reservation_id=guest.reservation_idg)
INNER JOIN unit USING (unit_id)
WHERE reservation_id ='".$reservation_id."'
AND guest_last_name ='".$guest_last_name."";
$result = mysqli_query($conn, $query);
if (!$result) {
$response['status']=503
$response['msg']="Error";
trigger_error(mysql_error());
finish($response);
exit;
}
$response['status']=200;
$response['msg']='OK';
$response['guest_full_name'] = htmlentities($_GET['guest_last_name']);
$response['reservations']=array();
while($row = mysqli_fetch_assoc($result)) {
$response['reservations'][]=array(
'unit_number'=>$row['unit_number'],
'floor'=>$row['floor'],
'key_sa'=>$row['floor_sa']);
}
}
finish($response);
exit;
function finish($response)
{
header("HTTP/1.1 $response[status] $response[msg]");
header("Content-type: application/json");
echo json_encode($response, true);
}

MySQL query result doesn't show using AJAX

I have a database called opera_house with a table called room that has a field room_name and a field capacity. I want to show the room_name 's that have a capacity larger than the one entered by the user.
The Available Room text disappears, but my code only shows the MySQL query if I echo it, but I'm not sure if it is reaching to search the database.
This is my script code:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function showRoom(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
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 (this.readyState === 4 && this.status === 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_events.php?q="+str,true);
xmlhttp.send();
}
}
This is my html:
<body>
<form>
<input type="text" name="room" onkeyup="showRoom(this.value)">
</form>
<br>
<div id="txtHint"><b>Available Room...</b></div>
</body>
This is my php:
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= '".$q."'";
echo $sql;
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['room_name'] . "</td>";
}
?>
My php file is called ajax_events.php
And my dbconnect.php is one that I constantly use to connect to this database.
Would really appreciate some help!!
I propose an answer using jquery. You've embedded it in your question but you're not using it ...
Explanations : You call the following url ajax_events.php with the parameter "q" only if str is defined, otherwise it fills the selector txtHint with nothing.
AJAX
if (str != "") {
$.ajax({
type: 'GET',
url: 'ajax_events.php',
dataType: 'JSON',
data : {
q: str
}
}).done(function (data) {
$('#txtHint').text = data;
}).fail(function() {
alert('Fatal error');
})
} else {
$('#txtHint').text = '';
}
With this configuration, it is important to return result with echo json_encode in your server side code.
PHP
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection, "opera_house");
$sql = 'SELECT room_name FROM room WHERE capacity >= '.$q; // Some corrections
$result = mysqli_query($connection, $sql);
$return = '';
while($row = mysqli_fetch_array($result)) {
$return .= '<td>' . $row["room_name"] . '</td>';
}
echo json_encode($return); // Return Json to ajax
?>
While thinking of JS it's fine. I think the problems are in the php code. Try this one.
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= " . $q;
$result = mysqli_query($connection,$sql);
if (!$result) {
echo mysqli_error();
exit();
} // this is to do debugging. remove when you get it fixed
$ret = ""; //variable to hold return string
while($row = mysqli_fetch_array($result)) {
$ret .= "<td>" . $row['room_name'] . "</td>";
}
echo $ret;

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

change css class after an if else statement of PHP query

The program refreshes the values of $pat_no every 5 seconds, what i want to know is, how can i change the css class property of the div being refreshed after the query is made. after comparing the values, the class will change accordingly(like changing the background color) if the value is changed in the database so that the changed value is easily noticed and reverts back to its old class after 5 seconds too.
Here's the code
<?php
include 'connect.inc.php';
$query = "SELECT patno, compare, cubeno FROM tblcube WHERE cubeid = '1'";
if($query_run = mysql_query($query)){
while($row = #mysql_fetch_assoc($query_run)){
$com = $row['compare'];
$pat_no = $row['patno'];
$cube_no = $row['cubeno'];
if($com == $pat_no){
//change css class of <th>
echo "<th>".$pat_no."</th>";
}
else if ($com != $pat_no){
//change css class of <th>
echo"<th>".$pat_no."</th>";
$query2 = "UPDATE tblcube set compare = '$pat_no'where cubeid = '1'";
if($query_run= mysql_query($query2)){
}
}
}
}
?>
Here is the JS code
function AJAX(){
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
}
also, here is the portion of index.php
<head><script src="ajax1.js"></script>
<script type = "text/Javascript">
refreshdiv_c1v();</script>
<body>
//cubicle1
$query = "SELECT patno, cubeno FROM tblcube where cubeid = '1'";
if($query_run = mysql_query($query)){
while($row = mysql_fetch_assoc($query_run)){
$pat_no = $row['patno'];
$cube_no = $row['cubeno'];
echo " <tr class = 'rows' id = 'cub1'>
<th class = 'name'>".$cube_no."</th>
<th class = 'num'><div id = 'c1v'>".$pat_no."</div></th>
</tr>";
}}
</body>
My guess is it would go something like this in your php file...
if($com==$pat_no){
return json_encode(array("msg"=>true,"data"=>$pat_no));
} else {
$query2 = "UPDATE tblcube set compare = '$pat_no'where cubeid = '1'";
if($query_run= mysql_query($query2)){
return json_encode(array("msg"=>false,"data"=>$pat_no));
}
}
And something like this in your jquery...
function checkPat(){
$.getJSON('yoururl.php',function(data){
if(data.msg==true){
// Update your class here
$('.theTRthatchanged').addClass('yourClass');
//Remove after 5 seconds
setTimeout(function(){
$('.theTRthatchanged').removeClass('yourClass');},5000);
} else if(data.msg==false){
//Do nothing I guess.
}
});
}
//Set the checker to fire every 2 seconds or whatever interval seems best.
setInterval(checkPat,2000);
Not quite exactly like this, but this is the main idea of how it would work. How you would go about selecting the tr that changed is up to you, and might be a bit tricky. You'll have to maybe attach data-id attributes or something of the sort, and send that back with the json.
But you get the idea.

Why am I getting duplicate items from MySQL query?

I am using an Ajax call to a PHP file to get data from MySQL database and populate select options in HTML. The problem is that duplicate items in the options and I don't know why. I tried the query in workbench and it brings back what I need.
PHP file:
<?php
$q=$_GET["q"];
// open db connection code
$query = "select * from r2rtool.materialtype where type = 'FE' and tools like '%".$q."%'";
$result = mysql_query($query);
$option = "";
while($row = mysql_fetch_array($result))
{
$mat = $row["Material"];
$option.="<option value=\"$mat\">".$mat."</option>";
echo $option;
}
// close db connection
?>
Ajax function:
function populatematerial(str)
{
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// 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","phpfile.php?q="+str,true);
xmlhttp.send();
}
while($row = mysql_fetch_assoc($result))
{
$option .= "<option value=\"{$row[Material]}\">{$row[Material]}</option>";
}
echo $option;
All you need to do is to move the echo $option; out of the while loop, like so:
while($row = mysql_fetch_array($result))
{
$mat = $row["Material"];
$option.="<option value=\"$mat\">".$mat."</option>";
}
echo $option;
You should output the HTML after you built it, not while you build it.
use mysql_fetch_assoc instead of mysql_fetch_array because array returns value in numbers and name both format, so it will twice data,
where mysql_fetch_assoc returns array as only name element of array ..
for more understanding
try
<?php
$query = mysql_query("some query ");
$row = mysql_fetch_array($row);
$assoc = mysql_fetch_array($row);
print_r ($row);
echo "<br>";
print_r ($assoc);
echo "<br>";
?>

Categories