I have a MySQL Query like this:
$sql = "SELECT team, sum(points) as allpoints FROM table WHERE [...] GROUP BY team ORDER BY allpoints";
Enetering it inside phpMyAdmin, I get the expected result. (and I see there is neither a duplicate in allpoints nor a duplictae in team!)
Now I want to know, if the rows for two names are directly neighbour rows.
Therefore I did this:
$result=mysqli_query($con, $sql);
$doCount=false;
$counter=0;
while($row = mysqli_fetch_array($result)) {
if(strcmp($team1, $row['team'])==0 OR strcmp($team2, $row['team'])==0){
$doCount=switchBool($doCount);
}
if($doCount){
$counter++;
}
}
if($counter < 2){
return true;
}else{
return false;
}
function switchBool($thebool){
if($thebool){
return false;
}else{
return true;
}
Description: As soon as I catch one of the two teams, $doCount switches to true and my $counter increases to value 1. When I catch the second team, $doCount switches back false and $counter stop increasing. So if one team appears directly after the other team in my while-loop, $counter should only be 1 and it should return true. But it always returns true, even when I'm sure it shouldn't. What's my mistake?
Related
I am trying to perform a wildcard search query using CI.
I am checking for loggedin sessions. If a user is logged into more than one device, a popup is displayed. To check if the user is logged in from any other device, I perform a wildcard query to check the existence of its user id in the user_data column and return the number of rows. The problem I am facing is, even if I am logging in for the first time, it goes to the else clause and not to if or if-else clause.
In my controller, I am checking if it reaches the else clause, display a popup. However, it is going to the else clause even if someone is logging in for the first time.
Model:
public function update_bool($id) {
$this->db->select('user_data');
$this->db->from('ci_sess');
$this->db->like('user_data', $id, 'both');
$counter = $this->db->get()->row();
if (empty($counter)) $counter = 0;
else if($counter === 1) $counter = 1;
else $counter = 3;
return $counter;
}
Controller:
$counter = $this->ion_auth_model->loggedin_status_update_bool($userId);
if($this->ion_auth_model->loggedin_status_update_bool($userId) === 3) {
warning('multiple_session_title', 'multiple_session_text');
}
You need to count number of rows return by the query. And based on no of records, your condition will work. Currently its returning one row of type array. And $counter as array to match else if condition will always fail.
I hope this will help you.
....
$query = $this->db->get();
$counter = $query->num_rows();
if (empty($counter)) {
$counter = 0;
}else if($counter === 1) {
$counter = 1;
} else {
$counter = 3;
}
return $counter;
I think your shorthand might be off a little and if I understand what you mean then there would be multiple sessions for the same user in the table meaning you couldn't get it using ->row().
Try like this:
public function update_bool($id) {
$this->db->select('user_data');
$this->db->from('ci_sess');
$this->db->like('user_data', $id, 'both');
$query = $this->db->get();
return $query->num_rows(); // This will give you now many times this user exists in the database, eg 0, 1, 2, 3
}
Then clean up your controller so you're not calling the database twice:
$counter = $this->ion_auth_model->loggedin_status_update_bool($userId);
if($counter == 3) {
warning('multiple_session_title', 'multiple_session_text');
}
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.
I have a PHP page with 3 dropdownlists on it. Everytime with an 'onchange' event a javascript docs get's the selected value's and transfers it to a php function, where I can transfer them to my mysql-database and get results out of them. This thing works perfect, but not when I apply my logic to define which function I should call
My php page contains the effective logic (see code-box) and underneed there are the 2functions with the actions. The function do work, but the problem is this. There's the possibility in the if-else construction that the functions can be called on 2 different moments. The first time in the if-else construction both of the calls are succesfull and the result is what it should be, the second moments it seems that the $result parameter is empty?
$result = mysql_query($sql) or die("Query failed with error: ".mysql_error());
$aantal = mysql_num_rows($result);
if($amount == 0){
echo "<p>This combination does not exist</p>";
}
else {
// lists are empty
if($soort == 'Empty' && $land == 'Empty' && $jaar == 'Empty'){
}
else {
if ($aantal > 2){
maketable($aantal, $result); // -> **succesfull call**
}
else if($aantal == 1){
makedetails($result); // -> **succesfull call**
}
else {
$first = mysql_result($result, 0);
$second = mysql_result($result, 1);
if (($second - $first) == 1){
makedetails($result); // -> **does not work**
}
else {
maketable($aantal, $result); // -> **does not work**
}
}
}
}
function maketable($aantal, $result) { … }
function makedetails($result){ … }
greetings
You don't show your query, so we can't tell what's going on. But mysql_result by default returns the FIRST field in the specified row, if you don't explicitly state which field to use, so unless your query is
SELECT somenumber FROM yourtable ...
then your mysql_result is going to be fetching who knows what. Note that you're also comparing that default 'first' value from two different rows - are you sure the query is actually returning 2+ rows of data?
$aantal is the number of rows affected by the query. Your logic does not work because you're trying to use query results when there are no rows affected.
Your logic:
$result = mysql_query($sql);
$number_of_rows = mysql_num_rows($result);
if ($number_of_rows > 2)
{
//do something
}
else if ( $number_of_rows == 1)
{
//Do something else
}
else if( $number_of_rows == 2 OR $number_of_rows == 0)
{
// Do something else (the part which fails)
}
The only way to reach that part and not fail is if the rows affected are exactly 2. When they are 0, the query didn't return anything and you are trying to access an empty result set.
Had to fetch my result once more to make it possible to loop through my array once again.
$first = mysql_result($result, 0);
$second = mysql_result($result, 1);
$result = mysql_query($sql) or die("Query failed with error: ".mysql_error());
But thanks for the help!
greetings
I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.
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" }
}