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.
Related
i have this function separated in my working page.
public function countRow(){
$id = $_SESSION['id'];
$num = 1;
$query = "SELECT count(*) from `auditsummary` where bizID=? AND statusID=?";
$sql = $this->db->prepare($query);
$sql->bindParam(1,$id);
$sql->bindParam(2,$num);
$sql->execute();
}
what i'm really trying to do in this function is to count the number of rows that are results of the query but i don't know how to do it and also how to return the value.
As you use a PDOStatement for your query, after the execute, you can use
$count = $sql->rowCount();
More information:
http://php.net/manual/en/pdostatement.rowcount.php
And to return the result, you can just do:
return $count;
Information for this:
http://php.net/manual/en/function.return.php
Use
$query = "SELECT count(*) AS getCount from `auditsummary` where bizID=? AND statusID=?";
And get the values as you normally does
$count = $row["getCount"];
Here's how I do it:
$count = "SELECT * FROM yourtable WHERE x='x' and y='y'";
$result = $dbconn->prepare($count);
$result->execute();
$t_count = $result->rowCount();
echo $t_count;
I'm trying to fetch a list of values from MySQL table using query1 and then use them in query2 to fetch values. Query1 gives 4 values however Query2 gives output matching the last value of Query1.
Following is my controller code
public function example_ctl(){
$data['result'] = $this->some_model->example();
}
Following is my model code
public function example() {
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids = implode(',', $value);
}
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_ids.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
}
I'm not able to understand where I'm going wrong. Please help.
try changing your code into this
<?php
$queue_id = array();
foreach ($res->result_array() as $value) {
$queue_id[] = $value;
}
$queue_id = implode(",",$value);
?>
$queue_id is overridden inside the loop each time loop executes that is why you get last value
This is how I fixed this issue.
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids[] = $value['queue_id'];
}
$queue_id = implode(',', $queue_ids);
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_id.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";
I need to do a SELECT * FROM table_X , the problem is table_X is the result of another query, I don't know how to do it, perhaps with two loop, something like this :
<?php
$query1 = mysql_query("SELECT * FROM table_ref");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query(" SELECT * FROM '$name' ");
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
?>
The tables are all similar & I can't do joint there's no keys. So what I want is to show only the results of the second query from each results of the first query !
So, what's your structure? I don't understand. You have column table_name where are listed a lot of tables? If so, just use backquotes on your $name:
$query2 = mysql_query(" SELECT * FROM `$name` ");
Apart from the obvious that has been pointed out in the comments, you're overwriting $row in the second loop.
Also, you're trying to read an array ($data) that is not defined.
The following will work much better (but still isn't ideal):
$query1 = mysql_query("SELECT `table_name` FROM `table_ref`");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query("SELECT `itime` FROM `$name`");
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
just change your quotes to have the query ready to be started
change
$query2 = mysql_query(" SELECT * FROM '$name' ");
to
$query2 = mysql_query(" SELECT * FROM `".$name."` ");
i would also rather sugest to check this part
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
you already used variable $row to fetching previus query so better to change to something else, look like $data is matching your needs because you already used but you did not declare it
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
Try this query:
select x.* from ( SELECT table_name FROM table_ref) as x
I'm using the following code to sort MySQL queries into time/date:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user']);
}
instead of having the PHP run through and show all the values in the table can I have it show the values from an array?
So, you want to find specific users in the SQL query to return? Build your query programmatically:
$users = array('User1','John','Pete Allport','etc');
$sql = "SELECT * FROM `users_newest_post` WHERE ";
$i = 1;
foreach($users as $user)
{
$sql .= "`username` = '$user'";
if($i != count($users))
{
$sql .= " OR ";
}
$i++;
}
$sql .= " ORDER BY `users_date_post` DESC";
$result = mysql_query($sql);
Which would get you a query like:
SELECT * FROM `users_newest_post`
WHERE `username` = 'User1'
OR `username` = 'John'
OR `username` = 'Pete Allport'
OR `username` = 'etc'
ORDER BY `users_date_post`
DESC
So, you want to find all posts for a certain date or between two dates, kinda hard to do it without knowing the table structure, but you'd do it with something like this:
//Here's how to find all posts for a single date for all users
$date = date('Y-m-d',$timestamp);
//You'd pull the timestamp/date in from a form on another page or where ever
//Like a calendar with links on the days which have posts and pass the day
//selected through $_GET like page.php?date=1302115769
//timestamps are in UNIX timestamp format, such as you'd get from time() or strtotime()
//Note that, without a timestamp parameter passed to date() it uses the current time() instead
$sql = "SELECT * FROM `posts` WHERE `users_date_post` = '$date'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
echo $row['post_name'] . $row['users_date_post']; //output something from the posts
}
//Here's how to find all posts for a range of dates
$startdate = date('Y-m-d',$starttimestamp);
$enddate = date('Y-m-d',$endtimestamp);
//Yet again, date ranges need to be pulled in from somewhere, like $_GET or a POSTed form.
//Can also just pull in a formatted date rather than a timestamp and use it straight up instead, rather than going through date()
$sql = "SELECT * FROM `posts` WHERE `users_date_post` BETWEEN '$startdate' AND '$enddate'";
//could also do:
//"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$endate'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
//output data
}
To find posts for a specific user you would modify the statement to be something like:
$userid = 5; //Pulled in from form or $_GET or whatever
"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$enddate' AND `userid` = $userid"
To dump the result into an array do the following:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row=mysql_fetch_assoc($result))
{
$newarray[]=$row
}
What you probably want to do is this:
$users = array("Pete", "Jon", "Steffi");
$users = array_map("mysql_real_escape_string", $users);
$users = implode(",", $users);
..("SELECT * FROM users_newest_post WHERE FIND_IN_SET(user, '$users')");
The FIND_IN_SET function is a but inefficient for this purpose. But you could transition to an IN clause with a bit more typing if there's a real need.
$sql = 'SELECT * FROM `users_newest_post` WHERE username IN (' . implode(',', $users) . ')';