CodeIgniter Wildcard Query - php

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');
}

Related

Simple PHP function not working strange enough

I have a very simple PHP function which checks the DB if the post is saved in the user's bookmarks or not. If it is saved as a bookmark in the table 'bookmarks', it should return a link to the bookmarks, if not, it should return a simple button.
This is the code that calls the function:
echo bookmark($id,'stories');
This is the PHP function:
function bookmark($id,$column) {
global $db_conx;
if($column = 'stories') { $col = 'storid'; }
elseif($column = 'discussions') { $col = 'discid'; }
elseif($column = 'articles') { $col = 'articleid'; }
elseif($column = 'videos') { $col = 'videoid'; }
else $col = 'resid';
$result = mysqli_query($db_conx, "SELECT * FROM bookmarks WHERE '$col'='$id' AND username='$log_username' LIMIT 1");
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
return "<a class='rllink' title='Saved in your bookmarks' href='https://hangar.flights/bookmarks'><i class='fa fa-bookmark'></i></a>";
}
else return "<a class='rllink' href="xxxx" title='Save this in your bookmarks'><i class='fa fa-bookmark-o'></i></a>";
};
For some weird reason, this doesn't seem to be working, although my other similar functions do work. Everywhere I call this function (with the correct parameters) it returns the else statement, even if the specific id is saved in the bookmarks and should return the first statement with a link to the bookmarks.
Anyone who sees what's wrong with it? I have tried adapting and changing it but nothing works.
You are using assignment-in-if:
if($column = 'stories')
When executed, this is what happens:
the value of $column becomes the string 'stories'
the if statement checks whether the new value of $column is truthy
This is almost certainly not what you want, and you'll probably want to do comparing-if statements that don't change the value(s) of the things you check:
if($column == 'stories')
This will check whether $column is currently equal to the string 'stories' without changing the value.

check if two rows are direct neighbours

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?

PHP - MySQL, think the $result is empty on some moments when there should be elements in

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

goto equivalent for php version < 5.3.0?

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.

MySQL consequent numbers

I use this function in my while loop to track the numbers of results.
$lvarcontributor = "SELECT * FROM dD_Contributors WHERE idAlbum = '".$idAlbum."' ORDER BY idContributor ASC";
$lvarresult=mysql_query($lvarcontributor);
$var = 0;
while ($lvarrow = mysql_fetch_array($lvarresult))
{
$var++;
//STUFF HERE...
}
How do I know the last result?
I need to know when $var++ is arrived at the last result. such as
If($var == "LAST RESULT") {
//do this
}
THANKS!
Use mysql_num_rows function - http://php.net/manual/en/function.mysql-num-rows.php
This function may be helpfull:
mysql_num_rows
if (($var + 1) == musql_num_rows($result))
{
//this is the last row
}
if( $var == mysql_num_rows($lvarresult) - 1 ) {
// this is the last row, do your thing
}
Maybe you want to check the mysql_num_rows function.
If you want to access only the last result, you should review your SQL query to fetch only this one (try messing with ORDER BY and LIMIT).
If you want to fetch every rows, but have a special treatment for the last result, then you can dut as follow:
$nextRow = mysql_fetch_array($lvarresult);
while ($nextRow)
{
$currentRow = $nextRow;
if($nextRow = mysql_fetch_array($lvarresult)) {
//Not the last row, data in $currentRow
}
else {
//Last row, data in $currentRow
}
}

Categories