How to get count of the sql search query
$u = new user();
$sql = "SELECT a.id FROM `accounts` AS a LEFT JOIN `users` AS u ON a.id = u.id WHERE a.id IS NOT NULL ";
$gender = $this->input->post('gender');
if($gender != NULL)
{
$sql .= "AND u.gender = '".$gender."' ";
}
$u->query($sql);
How to get count of the query results in $u->query($sql); .I need to set a validation on it. If the query results count is 0 , i need to set a message. Im using PHP Codeigniter ,datamapper library.
Thank you!!!
Just using count() function like this
...
$result = $u->query($sql);
$total_data = count($result);
if($u->exists())
{
echo "Found" // Do something
}
else
{
echo "Nothing found" //Do something
}
$result = $this->db->get();
For Codeigniter use $count = $result->num_rows(); // HERE IS YOUR COUNT
For OOP PHP use $count = $result->num_rows;
Related
I am new to CI/PHP/development. Im stuck on this problem. It seems to be really basic but i just cant get it right!
I am able to returning only last value while sql excecution .
controller
$data['leadd']= $this->dashboard_model->countt($this->session->userdata('user_id'));
foreach ($data['leadd'] as $q) { $date = $q['followup_date'];
$data['lead']= $this->dashboard_model->lead_count($this->session->userdata('user_id'),$date); }
$data['count'] = count($data['lead']);
Model
public function countt($userid)
{
$sql = $this->db->query("SELECT followup_date FROM tg_partner_data WHERE assign_to = '$userid' AND active = 'Y'");
return $sql->result_array();
}
public function lead_count($userid,$date)
{
$sql1 = $this->db->query("SELECT * FROM tg_partner_data
WHERE assign_to = '$userid' AND followup_date = '$date'
AND active='Y'");
//echo $this->db->last_query();
return $sql1->result_array();
}
First you select all followup dates from one table by executing this: "SELECT followup_date FROM tg_partner_data WHERE assign_to = '$userid' AND active = 'Y'".
Then for each followup_date, you execute another query but you don't merge prevoius results just overwrites them in foreach loop.
Foreach loop should look like this:
$data['lead'] = array();
foreach ($data['leadd'] as $q) {
$date = $q['followup_date'];
$data['lead'][] = $this->dashboard_model->lead_count($this->session->userdata('user_id'),$date));
}
You can also rewrite SQL query:
SELECT COUNT(*) FROM tg_partner_data WHERE assign_to = '$userid' AND followup_date = '$date' AND active='Y'"
It will allow you to get number of rows directly from DB.
I have the following query
SELECT fixtures.Fixture_ID, fixtures.Home_Score,
fixtures.Away_Score, predict.Fixture_ID, predict.pHome_Score, predict.pAway_Score
FROM fixtures INNER JOIN predict
ON fixtures.Fixture_ID=predict.Fixture_ID
I want to count the number of times the following condition is met
fixtures.Home_Score=predict.pHome_Score
AND fixtures.Away_Score=predict.pAway_Score
AND fixtures.Fixture_ID=predict.Fixture_ID
I tried using a 'COUNT()' then 'Having count()>1' but cant get the syntax to work
I have also tried to count the number of times the if condition is met in the following php. I'm not sure if this is possible, so I thought the count might have to done within as SQL statement
<?php
$current = $user->data()->id;
$sql2 = "SELECT fixtures.Home_team, fixtures.Away_Team, fixtures.Home_Score, fixtures.Away_Score, predict.pHome_Score, predict.pAway_Score FROM fixtures
INNER JOIN predict
ON fixtures.Fixture_ID=predict.Fixture_ID WHERE predict.id='".$current."'";
echo "The number of detected predictions:", '<br>';
$predictions = DB::getInstance()->query($sql2);
foreach ($predictions->results() as $rows) {
$rows= get_object_vars($rows);
$num_rows= $predictions->count();
}
for($count=0;$count<$num_rows;$count++){
$r_home_score = $predictions->results()[$count]->Home_Score;
$p_home_score = $predictions->results()[$count]->pHome_Score;
$r_away_score = $predictions->results()[$count]->Away_Score;
$p_away_score = $predictions->results()[$count]->pAway_Score;
$p=0;
if($r_home_score==$p_home_score&&$r_away_score==$p_away_score){
$p++;
echo $p;
}
}
The output is:
The number of detected predictions:
111111
I want to output 6
If you just want a single count returned from the database, you could just do a query like this:
SELECT COUNT(*) AS mycount
FROM fixtures f
JOIN predict p
ON p.Fixture_ID = f.Fixture_ID
AND p.pHome_Score = f.Home_Score
AND p.pAway_Score = f.Away_Score
FOLLOWUP
$dbh = DB::getInstance();
$sql = "SELECT COUNT(*) AS mycount
FROM fixtures f
JOIN predict p
ON p.Fixture_ID = f.Fixture_ID
AND p.pHome_Score = f.Home_Score
AND p.pAway_Score = f.Away_Score
WHERE p.id = ?";
if ($sth = $dbh->prepare($sql)) {
$sth->bindParam(1, $current, PDO::PARAM_INT);
if ($sth->execute()) {
if ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['mycount'];
} else {
// this should never happen with a COUNT(*) query
echo "query returned 0 rows";
}
} else {
echo "PDO error on execute: ";
print_r($dbh->errorInfo());
} else {
echo "PDO error on prepare: ";
print_r($dbh->errorInfo());
}
I am trying to get the number of friends that a user has, but I can't seem to get it to work, so i'm really hoping that you can help me.
Here is the php
$findFriendssql = "select u.firstName, u.id from friends f, user u
where (f.u_ID1 = '$loggedId' and u.id = f.u_id2)
or (f.u_id2 = '$loggedId' and u.id = f.u_id1)";
$all_friends_sql = $db->getRows($findFriendssql);
//$number_of_friends = mysql_num_rows($all_friends_sql);
if ($all_friends_sql) {
$number_of_friends = mysql_num_rows($all_friends_sql);
$friends = "";
foreach ($all_friends_sql as $one_post) {
//doing stuff here.
and here is the get rows function
public function getRows($sql) {
$result = array();
$table = mysql_query($sql, $this->db_link);
if (!$table) {
die("\"$sql\" seems to be an invalid query: " . mysql_error());
}
while ($row = mysql_fetch_assoc($table)) {
array_push($result, $row);
}
return $result;
}
whatever I try - I get the error that the num rows expects parameter 1 to be resource.
thank you in advance
$findFriendssql = "select u.firstName, u.id from friends f, user u where (f.u_ID1 = '$loggedId' and u.id = f.u_id2)
or (f.u_id2 = '$loggedId' and u.id = f.u_id1)";
$all_friends_sql = $db->getRows($findFriendssql);
//$number_of_friends = mysql_num_rows($all_friends_sql);
if (count($all_friends_sql)>0) {
$number_of_friends = mysqli_num_rows($all_friends_sql);
$friends = "";
foreach ($all_friends_sql as $one_post) {
The num row is supposed to happen immediatelly after this:
$table = mysql_query($sql, $this->db_link);
$totalFirends = mysql_num_rows($table);
Use $table as input parameter. $table is supposed to be a resource. to be able to use mysql_num_rows.
The following in your function changes $table not to be a resource anymore. Besides you do not need this code to know how many friend the user has:
while ($row = mysql_fetch_assoc($table)) {
array_push($result, $row);
}
return $result;
}
Also if you just need the number then the query should change to SELECT COUNT(some-field)
And I do not know what is the content of $loggedId hope you tested that the query returns what is supposed to return. is correct the output of the query with a sample data, let say in phpmyadmin?
I need to store the results from an SQL COUNT query in a PHP variable.
I know ModX uses PDO to run its SQL queries but I am unsure of how to go about creating this.
So far I have tried:
$sql = "SELECT COUNT (*) FROM `table` WHERE x = $x";
$results = $modx->query($sql);
$count = mysql_fetch_array($results);
echo $count;
and:
$sql = "SELECT COUNT (*) FROM `table` WHERE x = $x";
$results = $modx->getCount($sql);
echo $results;
but with no results.
Would anyone know the correct way to do this in ModX (Revo) and PDO?
A couple different methods
$results = $modx->query("select `username` from modx_users");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetchAll(PDO::FETCH_ASSOC);
echo count($r);
print_r($r);
}
$results = $modx->query("select count(id) as uids from modx_users where id >= '1'");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetch(PDO::FETCH_ASSOC);
echo 'uids = '.$r['uids'];
}
So, I am wondering how I can compare the result of one query to the result of another query in a if-statement. Like this:
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
if($team==$lplayer){
//Do something
}
else{
//Do something else
}
This does not work... Why?
Now, why doesnt this work:
$tleague = mysql_query("SELECT teamId from team
WHERE leagueId=(SELECT leagueId FROM league WHERE leagueName='$leagueName')");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$row1 = mysql_fetch_array($tleague);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId']){}
else{}
You need to use mysql_fetch_assoc() on the query, and compare the returned values. Something like the below. What you're comparing is the two returned resource objects:
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$t = mysql_fetch_assoc($team);
$p = mysql_fetch_assoc($tplayer);
if($t['teamId'] ==$p['teamId']){
//Do something
}
else{
//Do something else
}
However, you shouldn't be using mysql_* methods, instead look at using MySQLi // Tutorial.
You are not fetching any result from queries. Do something like
$team_result = mysql_fetch_array($team);
$tplayer_result = mysql_fetch_array($tplayer);
Then use fetched result to make your if condition
if($team_result['teamId'] == $tplayer_result['teamId'])
{
//do something
}
Also please stop using mysql as it is deprecated, switch to PDO or mysqli for new projects
Update
The new query have mistake. Why don't you use a join
$tleague = mysql_query("SELECT a.`teamId` from `team` a LEFT JOIN `league` b ON a.`leagueId` = b.`leagueId` WHERE b.`leagueName` = '$leagueName'");
$tplayer = mysql_query("SELECT `teamId` FROM `player` WHERE `playerName`='$playerName'");
$row1 = mysql_fetch_array($tleague);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId'])
{
// do something
}
else
{
// do something else
}
UPDATED AGAIN
I merged all queries in one and i encapsuled data in the query '".$playerName."' and '".$leagueName."'
$query = mysql_query("SELECT a.`teamId` from `team` a LEFT JOIN `league` b ON a.`leagueId` = b.`leagueId` LEFT JOIN `player` c ON b.`teamId` = c.`teamId` WHERE b.`leagueName` = '".$leagueName."' and c.`playerName`= '".$playerName."'");
if($row = mysql_fetch_array($query))
{
echo 'Found: ' . $row['teamId'];
}
else
{
echo 'Not Found.';
}
It does not work, because it's not the result of the query. You need to pass to a variable the mysql_result i.e.:
$result1 = mysql_result($team, 0);
$result2 = mysql_result($tplayer, 0);
if ($result == $result2) { ...
Try like this
$teamQuery = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$lplayerQuery = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$team = mysql_fetch_assoc($teamQuery);
$lplayer = mysql_fetch_assoc($lplayerQuery);
if($team['teamId']==$lplayer['teamId']){
//Do something
}
else{
//Do something else
}
do it like that
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$row1 = mysql_fetch_array($team);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId']){
//Do something
}
else{
//Do something else
}
EDIT:
on your second edit your problem is in the query itself .
try this one
$tleague = mysql_query("SELECT t.teamId from team inner join league l On t.leagueId = l.leagueId
WHERE t.leagueName='".$leagueName."' ");