PHP/MySQL Count() Issue - php

I am trying to create a class registration system for a client that utilizes PHP and MySQL. I have the database and table all set up and that part works just fine, however, the client has requested that upon registration, if there are 3 or fewer students enrolled to warn that the class may not run.
I'm trying to use the count() function as well as passing a dynamic variable from a cookie, set from the registration PHP script. However, I've hit a roadblock. I can't seem to get the count() function to actually count the rows. My select statement is below. Any help would be greatly appreciated.
$class = $_COOKIE["class"];
$min_check = "SELECT class_list, COUNT(class_list) as count
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING count < 20";
$result = mysql_query($min_check);
$count = mysql_num_rows($result);
if ($count < 4)
{
echo "IF THERE ARE 3 OR FEWER PEOPLE SIGNED UP FOR THIS CLASS, IT MAY NOT RUN.\n";
echo "THERE ARE CURRENTLY " . $count . " PEOPLE SIGNED UP.\n";
}
else if ($count > 4)
{
echo "There are currently " . $count . " people signed up for this class.";
}
?>

Your SQL query is returning a list of the class_list values, along with a count of each specific instance, where there are less than 20 people registered.
$count = mysql_num_rows($result);
...is getting the number of records returned in the resultset, not the alias count value, which is why you aren't seeing the output you expect. You need to read into your resultset to get the value:
while ($row = mysql_fetch_assoc($result)) {
$count = $row['count'];
if($count < 4) { ... }
}

The count that you want is returned in the row of the query. the mysql_num_rows will count the rows returned, which is not what you want. Use this instead.
$result = mysql_query($min_check);
$count = mysql_fetch_row($result);
$count = $count[0];

On a first glance, the HAVING count < 20 is unnecessary.
You use the MySQL-count-function, but never retrieve it's value!? Use:
$firstRow = mysql_fetch_row($result);
$count = $firstRow[1]; // 1 indicates the second column (0 being the first)

I don't recommend using known MySQL identifiers like count. It's confusing.
$class = mysql_real_escape_string($_COOKIE["class"]);
$min_check = "SELECT class_list, COUNT(class_list) as mycount
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING mycount < 20";
Don't forget to escape the contents of that cookie!
The error is that count is a reserved word. You need to either surround it in backticks `count` or even better, use a different moniker. It's not an error per se, but it's just too confusing.
Next up, you are not actually retrieving the mycount result from the database. I suggest using code something like this:
$result = mysql_query($min_check);
while( $row = mysql_fetch_assoc($result) ) {
$people_count = $row['mycount'];
if ($people_count < 4) { echo "this" }
else { echo "that" }
}

Related

How to sum up values in a php column

Im trying to sum up all the values in this data base but for some reason i cant do i, I looked all over stack overflow and tried multiple methods but none seem to work. My current code is
<?php
error_reporting(0);
//INCLUDES//
include 'config.php';
//INCLUDES//
//DATA FETCH//
$rank=$_POST['R'];
$drank=$_POST['DR'];
//DATA FETCH//
//MYSQL STUFF//
$con=mysqli_connect($ip,$login,$password,$dbname);
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i'");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
echo $row[0];
}
?>
It connects to the database no problem. When I use echo $row[0]; it prints all the values of the column in order. Ive tried putting it into an array and printing it but it seems that doesnt work either. The only way it seems to work is when I add ALL the values in the column by removing WHERE rank='$i' in the SQL code which I dont want to do. Please help !
Try the following query :
$rankarr = array();
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$rankarr[] = $i;
}
$rankarr = implode(',', $rankarr);
$s=mysqli_query($con, "SELECT sum(rankprice) As myrank FROM cost WHERE rank in ($rankarr)");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
You now want to get the sum value of rankprice in one same rank. So the result of sum() will differ from the rank in one sql. You should tell mysql by adding group by clause, which group the table by rank and get the sum() of each group.
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i' GROUP BY rank ");

PHP/SQL Query find last result

I am running a while loop in PHP selecting data from a mysql database. How can i find out what the last record is,
for example:
$sql="SELECT * from table1 ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs))
{
echo $result["col1"].' - '.$result["col2"].'<br>';
}
then when it gets to the last record i want to display it like:
echo 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br>';
You basically need to record how many rows you have, and then set up a counter. You can do that using mysql_num_rows():
$sql="SELECT * from table1";
$rs = mysql_query($sql,$conn);
$numRows = mysql_num_rows($rs);
$i = 1;
while($result=mysql_fetch_array($rs))
{
echo ($i == $numRows) ? 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br />' : $result["col1"].' - '.$result["col2"].'<br />';
$i++;
}
You should note though that the mysql_*() family of functions is now deprecated. For security and longevity, you really ought to be using MySQLi or PDO.
Get the total count of rows returned and check use a flag variable for the loop iterations and check in loop if flag == total rows
$t=mysql_num_row($rs);
$i=0;
while($result=mysql_fetch_array($rs))
{
$i++;
if($t == $i){
echo "Last Record ";
}
echo $result["col1"].' - '.$result["col2"].'<br>';
}
mysql_num_rows
You can simply use the sql query itself to get the last value, based on whatever ordering you want (or just use DESC to get the bottom of the natural order):
SELECT * FROM table1
ORDER BY your_column DESC
LIMIT 1;
Edit: Since you're looking for the last row, you could check with mysql_num_rows
$numrows = mysql_num_rows($rs);
$i = 1;
// in while loop...
if ($i === $numrows) {
// print last result
} else {
// print normal result
}
$i++;
// end while loop
Essentially, you want a counter for the record you are on and then write when the number of rows is the same as the row number you are on (e.g. the last one)
$sql="SELECT * from table1 ";
$rs=mysql_query($sql,$conn);
$num_rows = mysql_num_rows ($rs);
for ($i=0; $i < $num_rows; $i++) {
$result=mysql_fetch_array($rs);
if ($i == ($num_rows - 1)) {
echo 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br>';
} else {
echo $result["col1"].' - '.$result["col2"].'<br>';
}
}
Future-proof this routine by doing it the "hard way":
while ($next_row = fetch_row(...)) {
if ($prev_row) { do_output($prev_row); }
$prev_row = $next_row;
}
if ($prev_row) { do_output($prev_row, FLAG_IS_LAST_ROW); }
Why? Future maintenance might make mysql_num_rows() unreliable, either because your result set gets too big, or because you want to interface with a variety of SQL backends.
By default, the MySQL client library pulls the entire result set into memory — that is how it knows the number of rows SELECTed without having to count fetches. This behavior is rather convenient for small result sets, but devastating for large result sets. This it is user-configurable. (The options are usually named something like "store_result v. use_result" or "buffered v. unbuffered.")
Additionally, most RDBMS interfaces do not make the size of the result set known in advance. If you want to interface with these some day in a reusable way, you'll need to change your approach.

Php how to check for duplicate results?

Hi I'm currently querying from a database base user ids for a contest, However I want to avoid choosing duplicates in my results_array, this function getrandomspecies receives a array_result, this array results iterates 7 times. How test that I don't put duplicates in my results_array? I have gotten several duplicates.
function getrandomspecies($array_result){
//database connection
$dbn = adodbConnect();
foreach($array_result as $possible){
//query the results
$querys= "select * from taxonomic_units where tsn = $possible";
$resultss = $dbn -> Execute($querys);
while($rowss=$resultss->FetchRow()){
$id = $rowss['tsn']; //there ID
$ranksss = $rowss['rank_id']; //ranking id, I choose 220 and 230
if($ranksss == 220 || $ranksss == 230){
$prelimary_array[] = $id;
}
}
//grab random index
$index = array_rand($prelimary_array,1);
//put result id into a variable
$newspecies = $prelimary_array[$index];
//put that variable in an array
$results_array[] = $newspecies; //there is 7 newspecies/winners at the end, I dont want duplicates
}
return $results_array;
}
MySQL should be the following :
select distinct tsn, rank_id from taxonomic_units where tsn = $possible
But you should ideally use prepared statements.
what about this? You may do it with one query:
$querys= "select DISTINCT tsn from taxonomic_units where tsn IN (".implode(",",$array_result).") AND rank_id IN (220,230) ORDER BY RAND() LIMIT 7 ";
Loop your result array and if it does not exists add it. If you end up with less than 7, do your big loop again.
replace this line :
$results_array[] = $newspecies;
by:
$loop_1_more_time=0;
if (isset($results_array)){
foreach($results_array as $result){
if ($result == $new_specie){
$loop_1_more_time=1;
}
}
}
if ($loop_1_more_time == 0){
$results_array[] = $newspecies;
}
//there, if $loop_1_more_time equals 1, start again. To start again and be sure you have seven instead of 6 or less, You could replace your big first "foreach" loop with a "for" loop that depends of the count() of the $array_result, and the $array_result would be array_result[$i] instead of $possible. $i would start at 0 and increment at each end of loop. It would not be incremented if ­­$loop_1_more_time==1;.
Example :
for ($i = 0; $i < count($array_result); $i++) {
//stuff
//if ($loop_1_more_time=1;) { $i--; }
}
Why don't you try shuffling the array, and then picking the first X numbers?
That way, rather than having to check the results array for duplicates, it will never come up in the first place

How do I get the first and last results from a query?

I am creating a pagination script and I need to get the first and last results in the database query so that I can determine what results appear when the user clicks a page to go to. This is the code that I have at the minute:
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
I think you have few problems there, but I try to tackle them for you. First, as comments say above, you are using code that it vulnerable to SQL injection. Take care of that - you might want to use PDO, which is as easy use as MySQL extension, and will save you from many trouble (like injection).
But to your code, lets go through it:
You should ask DB to get count of the rows, not using mysql function, it's far more effective, so use SELECT count(*) FROM mytable.
For $pages use ceil() as you want all rows to be printed, if you have $max 5 and have 11 rows, round will make $pages 2, where you actually want 3 (last page just contains that last 11th row)
in LIMIT you want to LIMIT row_count OFFSET offset. You can calculate offset from page number, so: $max = row_count but $offset = ($max * $page) - $max. In your code if $get is directly the page, it means you get $get'th row (Not sure though what happens in your JS nextpage. Bare in mind that not all use JavaScript.)
I have prepared simple example here which uses PDO, maybe that gives you idea how simple it's use PDO.
The selecting rows shows example how to put parameters in SQL, it would be perfectly safe in this case state, 'SELECT * FROM pseudorows LIMIT '.$start.','.$max by I wanted to make an example how easy it is (and then safe):
// DB config
$DB_NAME = 'test';
$DB_USER = 'test';
$DB_PASSWD = 'test';
// make connection
try {
$DB_CONN = new PDO("mysql:host=localhost;dbname=".$DB_NAME, $DB_USER, $DB_PASSWD);
$DB_CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e);
}
// lets say user param 'p' is page, we cast it int, just to be safe
$page = (int) (isset($_GET['p'])?$_GET['p']:1);
// max rows in page
$max = 20;
// first select count of all rows in the table
$stmt = $DB_CONN->prepare('SELECT count(*) FROM pseudorows');
$stmt->execute();
if($value = $stmt->fetch()) {
// now we know how many pages we must print in pagination
// it's $value/$max = pages
$pages = ceil($value[0]/$max);
// now let's print this page results, we are on $page page
// we start from position max_rows_in_page * page_we_are_in - max_rows_in_page
// (as first page is 1 not 0, and rows in DB start from 0 when LIMITing)
$start = ($page * $max) - $max;
$stmt = $DB_CONN->prepare('SELECT * FROM pseudorows LIMIT :start,:max');
$stmt->bindParam(':start',$start,PDO::PARAM_INT);
$stmt->bindParam(':max', $max,PDO::PARAM_INT);
$stmt->execute();
// simply just print rows
echo '<table>';
while($row = $stmt->fetch()) {
echo '<tr><td>#'.$row['id'].'</td><td>'.$row['title'].'</td></tr>';
}
echo '</table>';
// let's show pagination
for($i=1;$i<=$pages;$i++) {
echo '[ '.$i.' ]';
}
}
mysql_fetch_array returns an associative array
Which means you can use reset and end to get the first and last results:
$pqa = mysql_fetch_array($pq);
$first = reset($pqa);
$last = end($pqa);
I don't see how you plan to use the actual results, just page numbers should be sufficient for pagination.
Still, hope it helps. And yes, upgrade to mysqli, so your code doesn't get obsolete.

generate get next unique number from mysql ID

I need to generate a unique extension for each user (this is separate from the ID but works much the same) the number should be 100 or greater and can be overwritten/custom set. Right now I am taking the next id and if it's less than 100 add 100.
So if the next id is 5 the number would be 105 but it the next id is 105 the number would just be 105. The problem is that because i'm letting the user pick their own extension if a user choose 105 before I want to make it automatically jump to the next number in this case 106. Now if there is 105, 106, and 108 I would want to jump to 107 then jump to 109. Here is the code I'm using to generate the numbers. I think the problem is with my while loop. I'm not sure how to make it keep on checking for unique numbers.
Here is the code, I'm sure I'm overcomplicated things A LOT.
$result = mysql_query("SELECT MAX(id)
FROM USERS");
$row = mysql_fetch_row($result);
$sql_extention = intval($row[0]);
//make sure it's at least 100
$extension = ($sql_extension < 100) ? $sql_extension+100 : $sql_extension;
//check to see if the extention is in use
$qry = "SELECT `extention`
FROM users
WHERE extention = '$extention'";
$result2 = mysql_query($qry);
//if the extention is in use then find the next available one (this isn't currently working)
if($result2) {
//get all results greater or equal to our extention
$qry3 = "SELECT `id`,`extention`
FROM admin_users
WHERE extention >= '$extention'";
$result3 = mysql_query($qry3);
//this loop needs to be rewritten somehow to get the next number by checking if the next number exist if not return that as the extention
$new_extention = $extention+1;
while($extention_data = mysql_fetch_array($result3)) {
if($new_extention != $extention_data['extention']+1) {
$extention = $new_extention;
}
$new_extention++;
}
I came up with this, haven't tested it thoroughly but i think it should return the next available value correctly
SELECT (a.extention + 1) as avail
FROM admin_users a LEFT JOIN admin_users b on ( (a.extention + 1) = b.extention )
WHERE a.extention >= 105 and b.extention is null
ORDER BY avail ASC
LIMIT 1
So if this works as expected you wont need the last few lines of code at all.
Edit:
Revised the query because i realized i was approaching it from the wrong side.
Shoddy attempt at PHP/pseudocode example as per my comment:
//nicer way to get the id of the user you just inserted!
$id = mysql_insert_id();
$sql = "SELECT `extension` FROM users ORDER BY `extension` ASC";
$res = mysql_query($sql);
$i=0;
while($n = mysql_fetch_array($res)){
if($i==0){
$i=$n['extension'];
}
if($i==$n['extension']){
$i++;
} else {
break;
}
}
//No existing users, start at 100
if($i==0){
$i=100;
}
Then use $i as your extension.
Ok, so you need the next available extention higher then a given number, that is not already in the database.
So, you ideally want an array from the database that has all available extentions higher then a given key sorted ascending. Then you loop from the given number increasing by one, until it does not match. You don't mention a max number of extention. I would do it like this:
<?php
$rs = mysql_unbuffered_query("SELECT extention, MAX(extention) FROM admin_users WHERE extention > '$extention' ORDER BY extention ASC");
$unavailable = array();
$max = 0;
while( ($row = mysql_fetch_row($rs)) )
{
$unavailable[] = $row[0];
if( !$max ) $max = $row[1];
}
mysql_free_result($rs);
// Optimization for the quite common case where no more extentions are available
if( count($unavailable) > 0 )
{
while($extention <= $max+1)
{
if( !in_array($extention, $unavailable) )
break;
$extention++;
}
}
else
$extention = $max+1;
// Worst case: $extention now is max + 1 and we looped through almost everything.
?>

Categories