I am trying to check if there were any records (more than 0) in my database table:
$ifExists = DB::select('SELECT COUNT(*) FROM `characters` WHERE userid = ?', array(Auth::id()));
Now I am checking if there are more than 0:
if($ifExists > 0){
return Redirect('/board');
}
else{
return view('intro');
}
It always takes me to the /board. But there are many rows in this database table.
The echo $ifExists; shows me [{"COUNT(*)":0}]
How do I check this number?
Try it this way:
$ifExists = DB::table('characters')->where('userid', Auth::id())->count();
If you do it like in your question, you will receive an array of objects.
If you only want to check for existens of entries and do not need the count, you can just use the exists() function whitch will return you a boolean:
$ifExists = DB::table('characters')->where('userid', Auth::id())->exists();
if($ifExists){
return Redirect('/board');
}else{
return view('intro');
}
Been a while since I've done PHP, but from the looks of it you get a result object from the database. That object is 1 object.
I think that's why it's always redirecting to /board.
Not sure how to do this in PHP, but you want to get the value of "COUNT(*)" from the object for your if statement. Hope that helps :)
Related
i have an issue gettin' the value from a query:
public static function sa() {
$resul = Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->execute();
$got = mysql_query($result);
$res = $got['MAX(id)'] + 1;
$rs='SA'.$res;
return "{$rs}";
}
it always return SA1, but i want get the last id and after plus 1 so in this case i have the next autoincremental id from my id column.
For example: i am creating a new registry with the field SA0000005. This number is calculated getting the last autoincremental value plus 1.
thanks for your valuable help
$resul = Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->execute();
$got = mysql_query($result); // what are you even doing here
Apart from typos, that's not how you are supposed to use the query builder. Have you read the documentation on the query builder?
The probable reason why you always get SA1, is because the $got['MAX(id)'] expression is NULL. You add 1 to that. You want something like this.
// returns false on no-result, MAX('id') otherwise
Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->queryScalar();
I have 2 tables in a database and they have a foreign key relation thru the column called id.
So I have the id (representing a user and is the primary key in the user table) from one table and want to check weather that user has existing data in the other table.
So I wish to run the id against the column called id in the other table and if the id exists in that column return value true.
I´m not getting any error at the moment but the method does not return any value. So I must be doing something wrong... Any help appreciated!
This is the class and method I have in one file:
class test {
public function dataExists ()
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$query = $db->prepare("`id` SELECT * FROM `data`");
if ($user == $query)
{
return true;
} else {
return false;
}
}
}
And the in my view file I have this:
$classTest = new test();
$exists = $classTest->dataExists();
if ($exists == true) {
echo '';
}
Currently you are checking if a mysqli_stmt object (returned from prepare()) equals a number. How do you think this comparison should work?
You can do this via num_rows, this is taken pretty straight forward from the manual
public function dataExists () {
//...
if ($statement = $db->prepare("SELECT * FROM `data` WHERE `id`=?")) {
$statement->bind_param("i", $user);
$statement->execute();
//...
return ($statement->num_rows > 0);
}
}
Since you are working with classes, you might want to store the results of the query somewhere - asking for their existence implies that you might want to use them.
I shortened the return statement as
if ($a==$b) {
return true;
} else {
return false;
}
is equal to
return ($a==$b);
Why not just use the query statement
SELECT count(*) FROM `data` where `id` = ?
and then just test for the value returned.
This has the benefit of only returning the number of records that match your query rather than matching and returning all the records that do. While that may be okay for a small number of records if your second table has 50,000 records that match you probably don't want to pull all of them just to find out that there are 50,000 of them!
I am trying to count rows of bookdetails table where display_id is as argument. Say i passed $id='3'. But i am not getting the output.
I think the code which i am trying is wrong. Please help me to write this query correctly
//--- Counting the rows of bookdetails of table where display_id is as argument-------------------------------------------------------------
public function record_count_for_secondtopBooks($id) {
$this->load->database();
return $this->db->count_all("bookdetails",array('display_id'=>$id));
}
count_all returns the number of rows in a particular
echo $this->db->count_all('my_table');
Try this
$this->db->where('display_id', $id);
$this->db->from('bookdetails"');
$this->db->count_all_results();
count_all accepts only one argument and that is table name. So you will get count of all records in that table. as written in manual:
Permits you to determine the number of rows in a particular table.
Submit the table name in the first parameter. Example:
$this->db->where('display_id',$id);
$result = $this->db->count_all("bookdetails");
or Chain em'
$result = $this->db->where('display_id',$id)->count_all("bookdetails");
check:
echo'<pre>';
print_r($result);
echo'</pre>';
Just try this,
$this->db->where('display_id', $id);
$query = $this->db->count_all('bookdetails');
return $query;
please try below code
public function record_count_for_secondtopBooks($id) {
$this->db->where('display_id',$id);
$q = $this->db->get('bookdetails');
return $q->num_rows();
}
try this
public function record_count_with_where($table_name,$column_name,$type)
{
$this->db->select($column_name);
$this->db->where($column_name,$type);
$q=$this->db->get($table_name);
$count=$q->result();
return count($count);
}
I have a strange mysql-thing going on here, it is about the following code:
$res = mysql_query("SELECT * FROM users WHERE group='".$group."'");
if (mysql_num_rows($res)==1) {
$row = mysql_fetch_assoc($res);
$uid = $row['uid'];
$user_update = mysql_query("UPDATE fe_users SET group = 5 WHERE group='".$group."'");
return 'ok';
} else {
return 'not ok';
}
I am checking, if there is a user with the group = $group. If so, the group is updated to 5 and after that the string "ok" is returned, if no user with group=$group exists, as you can see the string "not ok" is returned.
This should be very easy, but the problem now is, that if there is a user with group=$group, the update is done correctly, but instead of returning "ok", php returns "not ok", as if the change from the update is been taken into account for the above executed select retroactively. I dont understand this. Any help would be really appreciated.
Thanx in advance,
Jayden
I think 'group' is a reserved keyword that you have used as a field name, change it or use like
$res = mysql_query("SELECT * FROM users WHERE `group`='".$group."'");
and
$user_update = mysql_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
and you can use count($res)==1 instead of mysql_num_rows($res)==1 if it is a problem.
Reference: Mysql Reserved keywords.
I am not sure if this has any merit but try using this style in your SELECT and UPDATE commands: WHERE group='$group', without using string joins. Other than that I can't seem to see why you are getting an update and not being returned "ok".
You are checking if mysql_num_rows($res)==1, so you'll return ok if there is exactly one user on that group. If there are two or more users, it will return not ok. Probably not what you want, right? I think you should check if mysql_num_rows($res)>=1.
You might consider modifying the placement of your brackets, and changing your num_rows check, like so:
$res = mysqli_query("SELECT uid FROM users WHERE `group` ='".$group."'");
if (mysqli_num_rows($res)>0) {//there was a result
while($row = mysqli_fetch_assoc($res)){
// grab the user id from the row
$uid = $row['uid'];
// and update their record
$user_update = mysqli_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
if(mysqli_num_rows($user_update)==1){
return 'ok, updated user';
} else {
// database error
return 'not ok, unable to update user record';
}
}//end while row
}else{
return 'No results were found for this group.';
}
By selecting just the column you want, you reduce the query's overhead. By comparing the initial result to 0 instead of 1, you allow for groups with many members. By wrapping the update function in a while loop, you can loop through all the returned results, and update records for each one. By moving the test that returns 'ok'/'not ok' to check for success on the update operation, you're able to isolate database errors. The final else statement tells you if no update operation was performed because there are no members of the group.
BTW, for future-compatible code, I recommend using mysqli, as the "mysql_query" family of PHP functions are officially deprecated. See http://www.php.net/manual/en/mysqli.query.php for a quick start, it's largely the same thing.
I have a query like this:
SELECT * FROM configurations WHERE ID = userID
I then have logic like this:
if ($query->num_rows() > 0) {
foreach($query->result() as $row) {
// display data
}
else {
// display no data found message
}
But when I try to do this:
count($query->num_rows())
it is always 1, no matter how many results are returned. If 1 or more are returned the "if" is executed. If there are no results returned the "else" is executed. Yet, the count never changes. What is going on?
You can't count() a number, it works fine. If you only want number of records from table use COUNT() in SQL...
$sql = mysql_query("SELECT COUNT(0) AS count FROM configurations WHERE ID = userID");
$sql = mysql_fetch_assoc($sql);
$count = $sql["count"];
Otherwise just assign $count = $query->num_rows(); as #chriso stated.
Firstly else { should be } else { - you're missing a brace
Secondly, count() is used to count the number of elements in an array. Since $query->num_rows() returns a number rather than an array, you don't need to use count(). In your case, count() was telling you that there's one number, not what the actual number was!
Try:
$count = $query->num_rows();
echo $count;
You're getting an integer with $query->num_rows(), so when you run that integer through the count() function it is designed to return 1.
http://us2.php.net/manual/en/function.count.php
If var is not an array or an object
with implemented Countable interface,
1 will be returned. There is one
exception, if var is NULL, 0 will be
returned.