Php - mysql - Return number of rows - php

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?

Related

How to create a PDO query for fetch with variables

I am trying to build a PDO query for a large project to fetch SQL fetch queries. These SQL queries use variables to get values. I can't use the ones I get in the tutorials - I don't understand how to modify them to be able to use variables instead of :id for example. I have many many many files to update to PDO, because currently they are written using mysql()
An example of the query (one in of hundreds of files):
if(!$GLOBALS['this_brand']->id) return false;
if(!$GLOBALS['url_lang']) return false;
if(!$GLOBALS['this_region']->id) return false;
if(!$GLOBALS['this_type']->id) return false;
if(!$GLOBALS['this_user']->group) return false;
if(!$liveid = $GLOBALS['this_config']->get('config_live_id')) return false;
if(!$draftid = $GLOBALS['this_config']->get('config_draft_id')) return false;
if(!$archiveid = $GLOBALS['this_config']->get('config_archive_id')) return false;
if($GLOBALS['this_user']->is_admin()) {
$statussql = "AND (page.status = ".$liveid." OR page.status = ".$draftid." OR page.status = ".$archiveid.")";
}
else {
$statussql = "AND page.status = ".$liveid;
}
$the_statement = "SELECT * FROM page
LEFT JOIN _page_brand ON page.id = _page_brand.page_id
LEFT JOIN _page_language ON page.id = _page_language.page_id
LEFT JOIN _page_region ON page.id = _page_region.page_id
LEFT JOIN _page_type ON page.id = _page_type.page_id
LEFT JOIN _page_group ON page.id = _page_group.page_id
LEFT JOIN _page_section ON page.id = _page_section.page_id
WHERE _page_brand.brand_id = ".$GLOBALS['this_brand']->id."
AND _page_language.language_iso = '".$GLOBALS['url_lang']."'
AND _page_region.region_id = ".$GLOBALS['this_region']->id."
AND _page_type.type_id = ".$GLOBALS['this_type']->id."
AND _page_group.group_id = ".$GLOBALS['this_user']->group."
AND _page_section.section_id = ".$GLOBALS['this_section']->id."
".$statussql."
AND page.url = '".$this->url."'
ORDER BY page.status ASC, page.moddate DESC
LIMIT 1";
My PDO attempt (it looks really lame but I did try different ways, but removed the code once they didn't work):
public function fetchRaw($query){
$stmt = $this->db->query($query);
$arr = [];
foreach ($stmt as $row) {
$rarr = [];
foreach($row as $k=>$v) {
$rarr[$k] = $v;
}
$arr[] = $rarr;
}
return $arr;
}
I tried with the fetch(), the while loop etc. I cannot go and change each current query - there are thousands of them. Any help on how this should be approached will be appreciated. I am not an expert on PDO yet, and this huge project is a bit overwhelming, but I need to do this.

Query returing only last value in codeigniter

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.

How to get count of the sql search query?

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;

Only the last value from the list of values retrieved from MySQL is stored in the variable in codeigniter

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();

How can i join or implode the below array code?

In the below code i want to join or implode all arrays of $trackersurl in a single line. i am getting the results in different lines, so i want to join in a single line.
Can anyone help me out?
I am searching results in stackoverflow, but could not follow.
My code is in below:
$sql = "SELECT * FROM announce WHERE torrent = $id ORDER BY seeders DESC";
$query = #mysql_query($sql);
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['url'];
$trackersurl2 = "&tr=".$trackersurl1;
$trackersurl = array($trackersurl2);
}
Results of [var.trackersurl] in html page is below:
&tr=http:ajgdsjhg/ann
&tr=udp://iuysidfu/ann
&tr=udp:wutefghgw/ann
&tr=http://sdhgsjdhgj/ann
I want to join them in a single line below
&tr=http:ajgdsjhg/ann&tr=udp://iuysidfu/ann&tr=udp:wutefghgw/ann&tr=http://sdhgsjdhgj/ann
You should be careful of sql injection.
Are you looking to create an array['trackers'] with a string of all the trackers for a magnet link?
<?php
$sql = "SELECT * FROM announce WHERE torrent = ".mysql_real_escape_string($id)." ORDER BY seeders DESC";
$query = mysql_query($sql);
$tracker = null;
if(mysql_num_rows($query)>=1){
while ($result = mysql_fetch_array($query)) {
$tracker .= "&tr=".$result['url'];
}
}
$tracker = array('trackers'=>$tracker);
//$tracker['trackers'] = "&tr=a.com&tr=b.com&tr=c.com";
?>
Try this code
$newArray=array();
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['title'];
$newArray[] = "&tr=".$trackersurl1;
}
$urlString=implode('',$newArray);

Categories