Hello i want to calculate three parameters.
one X two X three = Y

The one is the value of a <input type="number"> the second is default the value '1' and the third is the count of this

``````\$sql = "SELECT uid, username, name, profile_pic FROM users";

\$result = mysqli_query(\$db,\$sql) or die(mysql_error());
if(mysqli_num_rows(\$result))
{
echo '<ul class="list">';
while(\$row = mysqli_fetch_array(\$result))
{
echo '<li><a id="'.\$row['uid'].'"><img src="'.\$user_image.'" /> '.\$str.'</a></li>';
}
echo "</ul>";
}
``````

any help?

## All 33 Replies

Not tested yet, if you can't manage to make it work just send me an private message and i'll help you.

``````    \$sql = "SELECT uid, username, name, profile_pic FROM users";

\$result = mysqli_query(\$db,\$sql) or die(mysql_error());

\$count_z = mysql_num_rows(\$result);

if(mysqli_num_rows(\$result))
{
echo '<ul class="list">';
while(\$row = mysqli_fetch_array(\$result))
{
echo '<li><a id="'.\$row['uid'].'"><img src="'.\$user_image.'" /> '.\$str.'</a></li>';
}
echo "</ul>";
}

//\$y parameter u said that is by default 1 but u can change it.
function calculateValues(\$x, \$y = '1', \$z) {

//check if passed params in function they are of integer type,
if(is_int(\$x) && is_int(\$y) && is_int(\$z)){

if(!empty(\$x) && !empty(\$z)){

\$line = \$x + \$y + \$z;

} else {

print 'A value is empty!';
}

} else {

print 'Passed values are not numbers!';

}

return \$line;

}

//How to use it?

//If form is of GET type
\$x = filter_input(INPUT_GET, 'input_name_with_that_number', FILTER_SANITIZE_NUMBER_INT);
//if form is of POST type
\$x = filter_input(INPUT_GET, 'input_name_with_that_number', FILTER_SANITIZE_NUMBER_INT);

print calculateValues(\$x, '1', \$count_z);
``````
commented: thanks i will try it and let you know. +2

Please keep all work regarding this question on the thread. Conversing via PM just stops others from contributing or benefitting from your expertise. Thank you.

@simon

Hello i want to calculate three parameters.
one X two X three = Y
The one is the value of a <input type="number"> the second is default the value '1' and the third is the count of this

The "count of this" being the code you supplied? Your code is not spitting out any countable stuff. Where you thinking about the count of records?

No not the records from the db. I want to calculate three parameters the one from the input type number, the second is default '1' and the third is the result count from the users returned byt the mysql script: \$sql = "SELECT uid, username, name, profile_pic FROM users";

@quadmachine has said it right i am going to test it and post the answer for any other that wants the same.

sorry i didnt explain myself clearly. \$count_z returns all the rows from the database i want it to return only the ones that the user selects. Its an autocomplete script. Here is the code
index.php

``````  <script type="text/javascript">
\$.base_url='http://localhost/project/';
var mainHolder     = "#holder";
var inputBox   = "#inputbox";
var ajaxFilePath = \$.base_url+"ajax_autocomplete.php";
</script>
<span>Select Friends:</span>
<div id="holder">
<input type="text" name="friends" id="inputbox">
<input type='hidden' value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" /><br /><br />
</div>
<span>How many times?
<input type="number" name="howmanytimes" /> times</span>
<div>
``````

ajax_autocomplete.php

``````\$keyword = \$_POST['data'];
\$sql = "SELECT uid, username, name, profile_pic FROM users WHERE username LIKE '%".\$keyword."%' OR name LIKE '%".\$keyword."%' LIMIT 0,10";

\$result = mysqli_query(\$db,\$sql) or die(mysql_error());
\$count_z = mysqli_num_rows(\$result);
if(mysqli_num_rows(\$result))
{
echo '<ul class="list">';
while(\$row = mysqli_fetch_array(\$result))
{
\$final = str_replace(\$keyword,'<span class="matched">'.\$keyword.'</span>',\$str);
//\$final = '<span class="matched">'.\$first.'</span>'.\$last;
echo '<li><a href=\'javascript:void(0);\' id="'.\$row['uid'].'"><img src="'.\$user_image.'" width="30px" height="30px" style="text-align:center"/> '.\$final.'</a></li>';
}
echo "</ul>";

}
else
{
echo 0;
}
``````

Even so, lets say the number that \$count_z returns is 9 the script doesnt work, doesnt calculate. I am always getting* 'Passed values are not numbers' * .

I have no idea how many times I.ve said this. Your query is open to sql injection use a prepared statement instead. Your current sql allows a malicious user to lay bare your entire db.

ok diafol yes you told me again this in the past, thanks. I ll do that but this thread is for calculating values and i think it interests a lot of people

About the function issue: the form will send strings, so `filter_input()` will return strings or:

• FALSE when condition fails
• NULL when variable name is not set, i.e. when submitting a form with wrong/missing field name

so the `is_int()` check will always return boolean FALSE. You can convert the input through `intval()`, or change the conditional rules in the function to verify that the argument is not null or false. An example:

``````<?php

function f(\$x, \$y)
{
if(in_array(\$x, [null, false]) || in_array(\$y, [null, false]))
return FALSE;

return \$x + \$y;
}

print f(FALSE, "6");
print f("5", "6");
``````

there is a mistake in the code @cereal

is this correct? \$x = filter_input(INPUT_POST, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);

because my inputs are \$_POST

Hmm, it works fine for me. What you get? Could be the array, if using PHP version prior to 5.4 then replace `[null, false]` with `array(null, false)`.

yes thats was the error? But still nothing

this is the code. i havent put the third parameter just to see if it works with two parameters

``````\$y=1;
//How to use it?
//If form is of GET type
\$x = filter_input(INPUT_GET, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);
//if form is of POST type
\$x = filter_input(INPUT_POST, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);
function f(\$x, \$y)
{
if(in_array(\$x, array(null, false)) || in_array(\$y, array(null, false)))
return FALSE;
return \$x + \$y;
}
print f(\$x, \$y);
``````

It happens because of:

``````//If form is of GET type
\$x = filter_input(INPUT_GET, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);
//if form is of POST type
\$x = filter_input(INPUT_POST, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);
``````

If using a GET request, i.e.: `script.php?howmanytimes=2`, then `\$x` will be overwritten by the INPUT_POST check, by using a POST you won't notice the error. To avoid this use only one request method or use conditional statements:

``````<?php

\$y = 1;

if(\$_SERVER['REQUEST_METHOD'] == 'GET')
\$x = filter_input(INPUT_GET, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);

elseif(\$_SERVER['REQUEST_METHOD'] == 'POST')
\$x = filter_input(INPUT_POST, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);

else
\$x = FALSE;

function f(\$x, \$y)
{
if(in_array(\$x, array(null, false)) || in_array(\$y, array(null, false)))
return FALSE;

return \$x + \$y;
}

print f(\$x, \$y);
``````

You get that issue bcoz you will get value from form as string, php can handle them as integers by this way.

\$a = 45;
\$b = (int)\$var;
\$c = (float)\$var;
and so on..

``````        //\$y parameter u said that is by default 1 but u can change it.
function calculateValues(\$x, \$y = '1', \$z) {

//check if passed params in function they are of integer type,
if(is_int(\$x) && is_int(\$y) && is_int(\$z)){

if(!empty(\$x) && !empty(\$z)){

\$line = \$x + \$y + \$z;

} else {

\$line = 'A value is empty!';
}

} else {

\$line = 'Passed values are not numbers!';

}

return \$line;

}

//\$m_ids = \$_POST['selected_ids']; \$auto variable will be replace by this \$m_ids or whatever you will rename var.

\$auto = array(44, 120, 3);

\$value_ids = array();

foreach (\$auto as \$key => \$val) {

\$value_ids[] = \$val;

}

\$autocomplete = array_sum(\$value_ids);

print calculateValues(\$autocomplete, 1, \$db_result);
``````

You said that \$count_z variable is counting all results from that query, i see you have changed query to another one so you should use another condition where to look for those ids from autocomplete.

I was reading over and over your first post and i have realized that you are double counting same stats, the ids from multiple selected you will be passing to query and sum them again.
Anyway, your query should look like this.if it's not written wrong.

``````\$query = "SELECT uid, username, name, profile_pic FROM users WHERE username LIKE '%".\$keyword."%' OR name LIKE '%".\$keyword."%' LIMIT 0,10
AND uid = " .implode(',' \$_POST['selected_ids']);
``````

Let me now that you have atleast a results, then we can move on to query.

i dont know why it doesnt work. I get it for the query. Thats not my problem. I use parameters just to test the script from @quad and nothing

This is getting a little surreal. For a simple calculator. You validate or sanitize (or cast) data to variables and then pass to a calculator function (alternatively get the function itself to validate/sanitize). In order to know what to do with your "input" data, we need to know the source.

The first variable, `\$x` seems to come from the form `\$_POST['howmanytimes']` or `\$_GET['howmanytimes']`. You don't say which method you are using to submit the data from the form. As you mentioned `'INPUT_POST'` in a thread post, I'll assume it's POST. For form data, you should use the `filter_input()` function. It's ajaxified from what I can see, so are you using `\$.post` or `\$.get` / `\$.getJson` or `\$.ajax` (set to either post or get) if jQuery or are you using vanilla javascript?

The second variable, `\$y` is simple set to `1` (for now). From this it is assumed that it is to be hard-coded somewhere in your code. If you need to validate/sanitize this, then a `filter_var()` function would be more appropriate.

The third variable, `\$z` is a simple count of the number of records from a query.

If you are not getting a return value, it could be due to a number of reasons. If you are testing the script directly from a traditionally submitted form (with form tags and submit button), then you should see a value. If you are using Ajax, then a lot of things could go wrong, without it being obvious - you need to check the Developer panel of your browser.

perhaps if you showed your Ajax code?

I am using Jquery but there is no Ajax code to show the result from the calculation. The Ajax code is used only to show the users from the autocomplete script, async. Its \$_POST. One other think i want to ask is that \$z is resulting from the ajax_autocomplete.php file that it's called from the `var ajaxFilePath = \$.base_url+"ajax_autocomplete.php";` on my index.php file. The index.php file is where i am doing the calculation.

My first question would be, what is your HTML for the submission? In your very first post, you said `<input type="number">`. There is NO type "number" for "input" tag. What is that???

of course there is http://www.w3schools.com/html/html_form_input_types.asp

i didnt explain my self.
this is as simple as i can put it.

``````<input type="number" name="howmanytimes" />
\$z= mysqli_num_rows(\$result);
\$x = filter_input(INPUT_POST, 'howmanytimes', FILTER_SANITIZE_NUMBER_INT);
\$y=0.1;
\$u= \$x * \$y * \$z;
echo \$u;
``````

now the thing is 1. it doesnt return async as it should be where the user is filling the input type field with numbers.
I use jquery files to other AJAX scripts

Sorry, but this looks a bit squiffy. There are no form tags so data will not be sent to the server via traditional method. You state there is no Ajax code at all??

I am using Jquery but there is no Ajax code to show the result from the calculation.

Then...

The index.php file is where i am doing the calculation.

So are you passing the form data (howmanytimes input) to ajax_autocomplete.php ?

Sorry simonloa - this has totally stumped me, I can't see what you're trying to do - it's giving me a nosebleed. Best of luck with it.

Man, i thought my english where good. Why is cereal and quad are getting this right and everybody else just doesn't. At top of that, on my defence, i posted the complete code so i rest my case. Anyway i am going to mark this as solved because there is no use of it for future refference.

Anyway

to @diafol
1. No the input type="number" id="howmanytimes" is not called on ajax_autocomplete.php file but on index.php
2. So, no the calculation has not returned through AJAX, there is no AJAX code to display the \$x\$y\$z async. Thats what i dont know how to do.

I am going to find the solution and post it here anyway

Ok I will try to see if I understood also.

When you say calculate do you mean you just want to add three numbers ?

When you say that the third number is “third is the count of this” do you just want to count the rows in the users table? Something like “SELECT COUNT(uid) AS counter FROM users” ?

When you say that the first parameter is through an “<input type="number">” tag have you checked it server side (type=”number” is not supported or partial supported yet by many browsers @see http://caniuse.com/#feat=input-number) ?

e.g.

``````<?php
\$database = "test";

\$result = "";
\$y = 1;  // Your default value that we don't know how it produced or what it is there for

\$keyword = "";
if( !isset(\$_POST["data"]) ) // A you wrote the keyword variable you name it data in the form
{
\$result = "Please enter a keyword"; // Or what ever error message you like
}
else if( !isset(\$_POST["inputNum"]) || !is_numeric(\$_POST["inputNum"]) ) // You didn't wrote how you name you input number in the from so lets call it inputNum
{
\$result = "Input number must be a number"; // What ever error message you like
}
else
{
\$keyword = "%" . \$_POST["data"] . "%";
\$inputNum = \$_POST["inputNum"];

\$countSql = "SELECT COUNT(uid) AS counter FROM users WHERE username LIKE ? OR name LIKE ?";
\$statement = \$db->prepare(\$countSql);
\$statement->execute(array(\$keyword,\$keyword));
\$r =  \$statement->fetchAll(PDO::FETCH_ASSOC);
\$counter = \$r[0]["counter"];
\$result = \$counter + \$y + \$inputNum;
}

echo \$result;
?>
``````

I just noticed that somewhere in the mixed code you name the inputNum as howmanytimes , is so just replace the `\$_POST["inputNum"]` with `\$_POST["howmanytimes"]` .
Also if by X in you first post and by calculate you mean mutliply just replace the
`\$result = \$counter + \$y + \$inputNum;`
with:
`\$result = \$counter * \$y * \$inputNum;`

OK @Jkon i've got this but how will this run with ajax? I mean how this `\$result = \$counter + \$y + \$inputNum;` will run async? When a user selects 1 or 2 or 3 from the <input type="number" /> below there should be a number that changes async everytime the user selects another value (1,2,3,4,5 etc)

i dont know how to put this more directly
I think we are lost in traslation here.

SimonIoa I am writing this with my best mood , and if you want keep my advice , else if you don't want through it away . We are not lost in traslation if you don't understand a problem you can't explain it to others either. There is no need for a person to be magician to reply.

Before moving to how to do it with an AJAX call is this code working for you ?
Is there a textfield that you name "data" that is the keyword ?
When do you want the AJAX call to be done ? When the user enters both of the fields ?
( and a minor one: Did by calculation you meant add after all ?)

Now i understand what you want, to async the sum on the same page.Simonloa next time try harder and without any complications to explain the problem more better, i had no clue what you were talking about on the first page so i was like a blind old men.Anyway, i'll post the solution next day because at the moment is 10:05 PM (Romania, local hour) and i'll rest for next 8/10 hours.

Why is cereal and quad are getting this right and everybody else just doesn't. At top of that, on my defence, i posted the complete code so i rest my case.

Sorry, but even quad said he didn't understand what you were getting at. Please don't blame contributors if they got the wrong end of the stick. Notice how many "solved threads" we have between us. This is what we do - try to solve other people's problems. If we're unable to understand what you're trying to do, then perhaps you should look at your own explanations. Posting your entire code is besides the point - and in our defence, you didn't mention it was the complete code. OK, will leave you in the capable hands of those who understand what you want. Best wishes and happy thoughts.

ok. i was just humoring the whole thread by saying lost in translation.

As for me don't think about it , I use also this phrase (although you didn't answered in any of my questions) . Did you solved this ? . Sometimes we have taken a completely wrong path and we are asking the wrong questions , that if somebody put them together will not make any sense.
It is better (except from asking the question) to explain in short were you would like to go , maybe the question isn't “how do I make water explode and rip rocks apart” thinking (but not mentioning) that you would like to make a tunnel to a mountain in order just to pass to the other side , and the only thing you have with you is water. Maybe where you want to go is a very known place and asking - naming the place , others might inform you that there is already a highway that goes there.

this is what i ve done so far but i having trouble counting the \$_POST['selected_ids']. The javascript works async returns as wanted.

the values from the `<input type='text' value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />` are returned like this 1,4,67,32 so i thought of explonding the ids and then count them but it doesnt count them.

here is the code

``````    <input type='text' value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
<?php
\$s = explode(\$_POST['selected_ids'], ",");
\$f=count(\$s);
?>
</div>
<div class="txtMult">
<input type="number" name="txt" class="val1"  />times
<span class="multTotal">0.00</span>
</div>
<script type="text/javascript">
\$(".txtMult input").keyup(multInputs);

function multInputs() {
var mult = 0;

\$("div.txtMult").each(function () {

var \$val1 = \$('.val1', this).val();
var \$val2='<?php echo \$f; ?>';
var \$total = (\$val1 * 1) * (\$val2 * 1) * 0.1
\$('.multTotal',this).text(\$total);
mult += \$total;
});
}
});
</script>
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.