0

In my example I have a PHP script that, from AJAX, does a tally of everyone named 'Richard.' I would like to further modify this by counting the people named Richard, that match the age of some input value, as shown in $theirage.

Specifically, I would like to sum up the two ages, and only show the ones that equal 20 in my array. $row[age] corresponds to the value age in my DB, while $theirage is a user input.

At the end I want to only tally the summed ages that equal to 20, in this case.

    $theirage = $_GET['theirage'];
    $query = mysqli_query($con, "SELECT count(*) as cnt FROM members WHERE
    name = 'Richard'
    ");
    $row = mysqli_fetch_assoc($query);
    $bow = $row['age'] + $theirage;
    $if ($bow = 20){
    $person = $row['cnt'];} 

echo json_encode( array(
    'person' => $person
) );    

How might I go about this?

1 Answer 1

1

I suggest you query members table to count all who are matching your criteria: specific name 'Richard' and specific age $_GET['theirage']:

<?php
$theirAge = $_GET['theirage'];

// This is important: since we're using $theirAge in query string, we need to escape it
$theirAge = mysqli_escape_string($theirAge);

// Let's query all members whose name is Richard and age is equal to $_GET['theirage']
$query = mysqli_query($con, "SELECT count(*) FROM members WHERE name = 'Richard' AND age + $theirAge = 20");

$row = $query->fetch_row();

$totalRichardsOfGivenAge = $row[0]; // here is your result.

// And now let's return JSON
echo json_encode($totalRichardsOfGivenAge)
Sign up to request clarification or add additional context in comments.

3 Comments

Yes but I am summing up the two ages and seeing if the result = 20. This is why, as far as I understand it, I can't just do this in mySQL.
Could you please clarify that? You would like to get count of all Richards who has age + someVariable equal to 20?
I've updated the code. We count only Richards, whose age + theirAge = 20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.