PHP duplicate staffID - php

staff table
code
<?php
//db configuration
$q = "select * from staff";
$r = mysqli_query($dbc, $q);
$num_rows = mysqli_num_rows($r);
$staffID = array();
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$staffID[] = $row['staffID'];
}
for($i = 0; $i < $num_rows; $i++)
{
if($staffID[$i] == $staffID[$i+1])
{
$remark = "Not OK. Multiple staff ID selected.";
$i++;
}
else
{
$remark = "OK.";
}
$data[$i] = $staffID[$i].','.$remark.'<br />';
}
$list = array($data);
print_r($list);
?>
From above code, I want to check whether the staffID got duplicate.
Expected output
0001, OK.
0002, Not OK. Multiple staffID.
0003, OK.
0004, OK.
However, I get another error as below:
Undefined offset: 5 in play.php on line X.
How do I solve it?

By performing the correct query in the first place.
SELECT staffID
FROM staff
GROUP BY staffID
HAVING COUNT(staffID) > 1
Or if you need to know about all staff IDs:
SELECT staffID, COUNT(staffID) as qty
FROM staff
GROUP BY staffID

Just updating your code and i think you have to check the existence first :
if (isset($staffID[$i]) && isset($staffID[$i+!])) {
if($staffID[$i] == $staffID[$i+1])
{
$remark = "Not OK. Multiple staff ID selected.";
$i++;
}
else
{
$remark = "OK.";
}
$data[$i] = $staffID[$i].','.$remark.'<br />';
}

You get the error at this line:
if($staffID[$i] == $staffID[$i+1])
Say for example your $num_rows variable is 3. Then the $staffID array would have indexes 0, 1 and 2. But what happens at this line I noted is that once $i reaches 2 (which is a valid since it's less than 3) you go and do $i+1 which equals 3. And, as you can see, the index 3 is out of the bounds of the array.
If you wish to do this like you wrote your for loop should be like this:
for($i = 0; $i < $num_rows-1; $i++)
But, there is a better way without even doing the for loop. You can do it all in the while loop by making use of the in_array function. Or as Ignacio pointed out, you could do it all on the SQL level.

Not a good way to solve this problem. You should use GROUP BY query for this.
SELECT staffID, COUNT(staffID) as count
FROM staff
GROUP BY staffID
HAVING count > 1
And also about your error. It's because of
if($staffID[$i] == $staffID[$i+1])
on last iteration $i is equal 4 and $i+1 is 5. But $staffID array has no element with such key

Related

Undefined variable array

I get an error on line 15 that says "Undefined variable: row2". How can I resolve this?
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT name
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) || ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}
What I'm trying to do is get a number from the first table (it only results to just Greg's row). Then subtract it with the numbers from the results of the second table. The result of this is placed into the sub variable and it's check to see if it's <= 20. If yes, it prints out the row. If not, it goes back to while loop to check another row. Am I going about the right way so far?
You need to change the while() loop's condition. Consider this example:
$a = 1;
if ($a == 1 || $b = 2) {
var_dump(isset($b));
}
Output of var_dump() will be boolean false because $b does not exist, which is the same case why your $row2 is undefined.
The thing is, while evaluation conditions with ||, PHP will stop evaluating other conditions once the match is found, so other comparisons or assignments on the right side will not be performed.
Change your while to be like this, you need both $row1 and $row2 anyway:
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
(note the && instead of ||)
Also, looks like you may want to use SELECT c.* in your second query, too, because you're only selecting the name column, and trying to use num too.
Note : Select all columns in your 2nd Query if num is already available in your columns so your problem will be solved then.!
Note : Try to replace || with && and you will be good to go.
By using || or OR as in conceptional language as I would say it.You are making the code like in a way that either and only one will pass but if you are passing both ones so then you should replace || with && so that's why your $row2 will be already created then so it will be available for more operation.!
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT *
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}

Multiple while loop in two queries

I have 2 queries.
and 2 while loops.
my problem is that When I call out the values. only one query and one loop is correct. the other loop is displaying duplicate values.
here is what I have :
$query1=mysql_query("SELECT * FROM table1");
$query2=mysql_query("SELECT * FROM table2");
while($row1=mysql_fetch_array($query1)){
while($row2=mysql_fetch_array($query2)){
echo $row1['nameofattribute'] ;
echo $row2['nameofattribute'] ;
}
}
the output of query 1 is correct. but the output of query 2 is duplicate values.
for example :
query 1= $row1=2 $row1=3 $row1=4
query 2= $row2=3 $row2=3 $row2=3
instead it should be
query 1= $row1=2 $row1=3 $row1=4
query 2= $row2=1 $row2=2 $row2=3
on top is my simple translation of the code. here is my real code :
$query1 = mysql_query("SELECT remarks FROM passed_deliverable WHERE user_id=$uid && deliverable_category_id=4");
$query2=mysql_query("SELECT
deliverable_id, deliverable_title, deliverable_desc, adviser_id ,deliverable_category_id
FROM deliverable d
WHERE d.deliverable_category_id=4
&& EXISTS (
SELECT 'X'
FROM passed_deliverable pd
WHERE pd.deliverable_id = d.deliverable_id && user_id='".$_GET['edit']."' && adviser_id='".$_SESSION['user_id']."' ) ");
while($x=mysql_fetch_array($query1)){
while($deliverable=mysql_fetch_assoc($query2)){
echo "
{$deliverable['deliverable_desc']}
{$x['remarks']}
";
try this :
other answer or loop from mr. hellcode
it shows that you can also use array values instead of just using array
$a1 = 0[];
$a2 = 0[];
while($x=mysql_fetch_array($query1)) {
$a1[] = $x['remarks'];
}
while($deliverable=mysql_fetch_assoc($query2)) {
$a2[] = $deliverable['deliverable_desc'];
}
for($i=0; $i < count($a1) and $i < count($a2); $i++) {
echo "\n\n".$a2[$i]."\n".$a1[$i];
}
Assuming that you just want to combine the resulting rows of both tables in their appearing order (ignoring results that exceed the other table):
$a1 = array();
$a2 = array();
while($x=mysql_fetch_array($query1)) {
$a1[] = $x['remarks'];
}
while($deliverable=mysql_fetch_assoc($query2)) {
$a2[] = $deliverable['deliverable_desc'];
}
for($i=0; $i < count($a1) and $i < count($a2); $i++) {
echo "\n\n".$a2[$i]."\n".$a1[$i];
}
Deprecation of mysql_ functions . Please avoid mysql_ function . Anyway your query seems to unusual. because we don't see any WHERE clause in your queries . That means it will return duplicate value. Table1 each row will be check all rows of Table2 .

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 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

PHP/MySQL Count() Issue

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" }
}

Categories