I have a table called "guesses" that stores peoples guesses whether a baby is a boy or a girl. Those are the two possible things in the "sex" column (i.e. "boy" or "girl).
There are 4 guesses in the table for this poolid. So if I run this code below...
$sql = "SELECT
FROM guesses
WHERE poolid = '$poolid'
ORDER BY $sort, createddate";
$getguesses = mysqli_query($connection, $sql);
if (!$getguesses) {
die("Database query failed: " . mysqli_error($connection));
} else {
//Get total number of guesses
$numguesses=mysqli_num_rows($getguesses);
echo "NUMGUESSES: $numguesses";
while ($row = mysqli_fetch_array($getguesses)) {
//code to grab other info about guesses, not relevant, works fine
}
}
It outputs
NUMGUESSES: 4
And also spits out 4 lines (one for each guess) with other info that isn't relevant.
I would like to count the total number of girl guesses vs. boy guesses, for use later in a pie chart. So I did the following...
$sql = "SELECT *, COUNT(CASE WHEN `sex` = 'girl' then 1 ELSE NULL END) as 'totalgirls', COUNT(CASE WHEN `sex` = 'boy' then 1 ELSE NULL END) as 'totalboys'
FROM guesses
WHERE poolid = '$poolid'
ORDER BY $sort, createddate";
$getguesses = mysqli_query($connection, $sql);
if (!$getguesses) {
die("Database query failed: " . mysqli_error($connection));
} else {
//Get total number of guesses
$numguesses=mysqli_num_rows($getguesses);
echo "NUMGUESSES: $numguesses";
while ($row = mysqli_fetch_array($getguesses)) {
echo "GIRLS:". $row['totalgirls'];
echo "BOYS:". $row['totalboys'];
//code to grab other info about guesses, not relevant
}
}
This outputs
NUMGUESSES: 1
GIRLS: 4
BOYS: 0
And also spits out ONLY ONE line (for only one of the four existing guesses)
All four guesses are girls, so the GIRLS total and the BOYS total are correct. But why is it only seeing NUMGUESSES as 1 now? It should be 4 and should show 4 lines of guesses.
Something with the COUNT() is throwing something off. Any ideas?
You're asking mysql to count, so it outputs one line ; )
Try this instead:
$sql = "SELECT COUNT(*), SUM(CASE WHEN `sex` = 'girl' then 1 ELSE 0 END) as.....
Beware of including NULL values in a count!
Related
Currently, I'm stuck here in this part of my program. I want to fetch the data from the table I created which named enrollment_confirm. I want to add the total of female students and male students then the total combined of the two gender.
Here is my code so far in MySQL.
include_once('samplesf1-db.php');
$pdo = Database::connect();
$query1 = "SELECT
COUNT(CASE WHEN UPPER(Gender) = 'TOTAL MALE' THEN 1 END) Male,
COUNT(CASE WHEN UPPER(Gender) = 'TOTAL FEMALE' THEN 1 END) Female,
COUNT(CASE WHEN Gender IS NULL THEN 1 END) 'Not Assigned',COUNT(LRN) AS 'COMBINED' FROM enrollment_confirm";
$result = mysqli_query($con, $query1);
while($row = mysqli_fetch_array($result)){
echo $row['Gender'];
}
Database::disconnect();
?>
Is there anything
So, when I run the code. This is what it says.
enter image description here
Can you tell me if I did something wrong in the query?
Right, I'll be specific as possible here - I'll first outline what I need, then what I've done - I can usually plod on with these so bear in mind I'm only asking as my brain is fried!
I have a table in my database - we only need to know it has these fields (gender - male or female, layout - 0 or 1)
I want to find the most used layout (0 or 1) for males - I've done this by:
$result = mysqli_query($conn, "SELECT layout,COUNT(*) as num
FROM style where gender = 'male' group by layout order by num DESC
LIMIT 1" );
I want to check if the returned result (so most frequent) is 0 or 1, so i can use that in an IF statement (so far i'm just using an echo to test)
I'm sorry if this if very trivial, or if i've missed anything out - if you need any extra info let me know.
Your code is fine for determining whether males prefer layout 0 or 1, you just need to look at the output value:
$result = mysqli_query($conn, "SELECT layout, COUNT(*) as num
FROM style
WHERE gender = 'male'
GROUP BY layout
ORDER BY num DESC
LIMIT 1" );
$row = mysqli_fetch_assoc($result);
if ($row['layout'] == 0)
echo "males prefer layout 0";
else
echo "males prefer layout 1";
PHP:
$DTB->new mysqli($Mysql_Server,$Mysql_User,$Mysql_Password,$Mysql_Database);
$Layout0=($DTB->query("SELECT layout FROM style WHERE gender ='male' AND layout=0 "))->num_rows;
$Layout1=($DTB->query("SELECT layout FROM style WHERE gender ='male' AND layout=1 "))->num_rows;
IF ($Layout0>$Layout1){
...
}
$resultResource = mysqli_query($conn, 'SELECT layout,COUNT(*) as num FROM style where gender = "male"');
while ($row = mysqli_fetch_assoc($resultResource)){
$maleCount = $row['num'];
}
$resultResource = mysqli_query($conn, 'SELECT layout,COUNT(*) as num FROM style where gender = "female"');
while ($row = mysqli_fetch_assoc($resultResource)){
$femaleCount = $row['num'];
}
if ($femaleCount > $maleCount){
//more females in database
}elseif($femaleCount < $maleCount){
//more males in database
}else{
//same amount of both;
}
I've a table that has three columns id, points, rank. Timely I update data for all fields so points go up and down but old rankings remains same, so I'm trying to find out a way that entitles each id its deserving rank based on points earned.
I've got more than 2000 rows in this table. I wish to do it in php5+ with mysqli? I think I've a solution but it times out even with 1200 seconds timeout setting and memory gets exhausted.
I think my solution works accurately but any of the loops needs some doctor. Here my rough target is 'update' query to go accurate that takes all points in desc order, and awards id a rank against the points earned:
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
$a2= mysqli_query($link, "SELECT COUNT(*) as count FROM p1");
$b2 =mysqli_fetch_array($a2);
$count = $b2['count'];
$i=1;
while($i<=$count){
$a1= mysqli_query($link, "SELECT points FROM p1 ORDER BY points DESC LIMIT $i");
if(!$a1){
echo mysqli_error($link);
}
while($po = mysqli_fetch_array($a1)){
$ross[] = $po;
}
foreach($ross as $pot){
$points=$pot['points'];
}
$a5a= mysqli_query($link, "SELECT id FROM p1 WHERE points = '$points'");
while($popo = mysqli_fetch_array($a5a)){
$idi=$popo;
}
foreach($idi as $idm){
$id=$idm['id'];
$rank = $i;
$update = mysqli_query($link,"UPDATE p1 SET rank = '$rank' WHERE points = '$points' AND id ='$id'");
}
if(!$update){
echo "Error updating Rank".mysqli_error($link);
} else {
echo "Succuessul for where id = '$id' and points = '$points' set rank = '$rank'<br/>";
}
$i++;
}
?>
I have replaced my original answer with much leaner and shorter code, you can of course include modification to the rank counter if consecutive users have same points but you can figure this yourself
This code have just one loop and is conserving memory and your DB as well
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
$a = mysqli_query($link, "SELECT id, points, rank FROM p1 ORDER BY points DESC "); // lets get users in new ordering
$rank = 1; // new ranks
while($line = mysqli_fetch_array($a)){
if ($rank != $line["rank"]) { //if old rank is different we will hit db with new value
echo "updating id ".$line["id"]." from rank ".$line["rank"]." to rank ".$rank." <br>";
if(!mysqli_query($link,"UPDATE p1 SET rank = '".mysqli_real_escape_string($link,$rank)."' WHERE id ='".mysqli_real_escape_string($link,$line["id"])."'")) {
echo "Error updating Rank".mysqli_error($link);
}
}else { //if its the same we just leave the message for now
echo "ignoring id ".$line["id"]." previous rank ".$line["rank"]." , new rank ".$rank." <br>";
}
$rank++; // next user so lets increment the counter
}
?>
Recently went through same kind of issue and found a simple solution like below after struggling a lot. I would like to clear it out that, it depends on your input and expected result as well which you didn't mention in your post.
if (preg_match('/"'.<value>.'"/i' , json_encode(<your array>))) {
echo "Match";
} else {
echo "Doesn't match";
}
Please replace values accordingly when trying! Thanks for reading it.
The following answer code takes all points, and relevant ids and sets high to low ranks against high to low points respectively. However, it does not assign same rank for same points holder id as it keeps rolling with Rank+1 until end. That could be done, but isn't presently required.
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php'; //connection to the DB
$a1= mysqli_query($link, "SELECT id, points FROM p1 ORDER BY points DESC"); //Selecting High to low all points
if(!$a1){
echo mysqli_error($link);
}
while($po = mysqli_fetch_array($a1)) {
$rose[] = $po;
}
$rank=0;//set rank 0
foreach($rose as $ro) { //splitting each row of array with unlimited rows
$points=$ro['points'];
$id=$ro['id'];
$rank++; //adding 1 each time foreach loops repeats itself until no row left
$update = mysqli_query($link,"UPDATE player1 SET rank = '$rank' WHERE points = '$points' AND id ='$id'"); //sending update command
if(!$update) { //echoing out what the hell this code is f******
echo "Error updating Rank".mysqli_error($link);
} else {
echo "Succuessul for where id = '$id' and points = '$points' set rank = '$rank'<br/>";
}
}
?>
I'm trying to do 2 things.
1) Get the amount of rows in this query
SELECT
COUNT(*)
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
As you can see that is no problem ^^
2) Determine the number within the range of rows that is returned by id
Ex: ID 765 is Item 4 of 7 where column_1 = 152 and column_3 = 42
Does anyone have any basic solutions to this problem with almost pure MySQL? I'd like to avoid iterating through all the rows and setup a counter to increment until it matches current id like this:
$sql = '
SELECT
*
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
';
$query = mysqli_query($sql);
$current_id = 2523;
$i = 1;
while ($row = mysqli_fetch_assoc($query)) {
if ($row['id'] == $current_id) {
$current_position = $i;
}
$i++;
}
print 'Current position in range is: '. $current_position;
Also please don't worry about the actual syntax, I won't be using this exact script, but you get the logic that I'd like to avoid using. If anyone has a better solution, please let me know. Thanks in advance!!
I have a query like this
$sql = "SELECT SUM(CASE WHEN jr_softwarecheck LIKE \'%sony\' AND
jr_othersoftware LIKE \'%sony%\' THEN 2 ELSE 1 END) AS totalcount FROM
jos_jreviews_content WHERE jr_softwarecheck LIKE \'%sony%\' OR
jr_othersoftware LIKE \'%sony%\'";
I want to output results in HTML pages. I run a Joomla based site.
How can I do that?
Sorry but I'm not so skilled in PHP, I'm learning.
Expected result in HTML page (frontend), example:
SONY Products: 105
Thanks in advance to all!
In your case, use it like this:
$sql = "SELECT SUM(CASE WHEN jr_softwarecheck LIKE \'%sony\' AND jr_othersoftware LIKE \'%sony%\' THEN 2 ELSE 1 END) AS totalcount FROM jos_jreviews_content WHERE jr_softwarecheck LIKE \'%sony%\' OR jr_othersoftware LIKE \'%sony%\'";
$res = mysql_query($sql); // This will run the query on the connected datababse
if($row = mysql_fetch_array($res)){ // Since you are using just a SUM to count results, you don't need to loop
echo "Sony Products: ".$row['totalcount']; // $row['totalcount'] is the result of the totalcount from your MySQL query put into the $row variable
}
I hope this helps you out :)
$result = mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
//do something
}