mysql return numbers of specific row? - php

In my mysql table i have table that contain points, a want to return number of that table?
Can some one help me?
("select * from liv_sr")
Table contain(id,name,ip,port,*rank*....)
I want to "rank" return in numbers, specifik number
Etc.(1,2,3,500)
query[0]['rank']=1200 points=>1 on rank
query[1]['rank']=800 points=>2 on rank
query[2]['rank']=1 points=>500 on rank

You need to use a order by query
$sql="select * from table order by rank desc";
$point =1;
$result = mysql_query($sql);
$tableResult = array();
while($arrayresult =mysql_fetch_array($result))
{
$tableResult[] = array('id'=>$arrayresult['id'],'rank'=>$arrayresult['rank'],'point'=>$point);
$point= $point+1;
}

Don't know if this is already answered, but if you really want to achieve having only one result row, you could have a look at MySQL group_concat. In your example, you could get a result of say for example:
"1200, 600, 500" (comma seperated, ordered by ranked) with
SELECT GROUP_CONCAT(rank ORDER BY rank DESC SEPARATOR ', ') FROM liv_sr GROUP BY 'all'
In php, you could split the result with:
$myArray = explode(',', $result);
Also, note that there's 1024 byte limit on result. If you need more, than simple run:
SET group_concat_max_len = 2048

Related

Retrieving total count of matching rows along with the rows themselves using PDO

I have a PDO snippet that retrieves a bunch of rows from a MySQL table and assigns the field values (2 fields are returned per row) to two arrays like so:
$connect = dbconn(PROJHOST,'dbcontext', PROJDBUSER, PROJDBPWD);
$sql= "SELECT contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25";
$xleft = array();
$xright = array();
$countrows = 0;
$word = "[[:<:]]".$term."[[:>:]]";
$query = $connect->prepare($sql);
$query->bindParam(":word", $word, PDO::PARAM_STR);
if($query->execute()) {
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$pattern = '/\b'. $term .'\b/ui';
$replacer = function($matches) { return '<span class="highlight">' . $matches[0] . '</span>'; };
$xleft[$countrows] = preg_replace_callback($pattern, $replacer, $row['contextleft']);
$xright[$countrows] = $row['contextright'];
$countrows++;
}
$notfound = null;
}
$connect = null;
This works perfect. As you can see, I use the LIMIT clause to ensure only a maximum of 25 rows are extracted. However, there can actually be many more matching records in the table and I need to also retrieve the total count of all matching records along with the returned rows. The end goal is pagination, something like: 25 of 100 entries returned...
I understand I have 2 options here, both involving 2 queries instead of a single one:
$sql= "SELECT COUNT(*) FROM tblcontext WHERE contextleft REGEXP :word;
SELECT contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25";
or...
$sql= "SELECT SQL_CALC_FOUND_ROWS contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25;
SELECT FOUND_ROWS();";
But I am still confused around retrieving the returned count value in PHP. Like I could access the fields by running the fetchAll() method on the query and referencing the field name. How can I access the count value returned by either FOUND_ROWS() or COUNT()? Also, is there any way to use a single SQL statement to get both count as well as the rows?
If you have a separate query with the count, then you can retrieve its value exactly the same way as you read the values from any queries, there is no difference.
If you use SQL_CALC_FOUND_ROWS, then you need to have a separate query to call FOUND_ROWS() function:
SELECT FOUND_ROWS();
Since this is again a normal query, you can read its output the same way as you do now.
You can technically retrieve the record count within the query itself by adding a count(*) field to the query:
SELECT contextleft, contextright, (select count(*) from tblcontext) as totalrecords FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25
or
SELECT contextleft, contextright, totalrecords
FROM tblcontext WHERE contextleft, (select count(*) as totalrecords from tblcontext) t REGEXP :word LIMIT 0, 25
Limit affects the number of records returned, but does not affect the number of rows counted by the count() function. The only drawback is that the count value will be there in every row, but in case of 25 rows, that may be an acceptable burden.
You need to test which method works the best for you.

How to get Number of Rows after GROUPING (using GROUP BY) a SQL Query?

CODE:
$result = mysql_query("SELECT COUNT(`user_id`), `mac_add`, SUM(`duration`)/60 AS ConnTime, SUM(`download`)/1000000 AS TotalDown, SUM(`upload`)/1000000 AS TotalUp
FROM `cdr_data_january`
WHERE (`bs_id_site` LIKE '".$btsid."') AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
GROUP BY `user_id`
UNION
SELECT COUNT(`user_id`), `mac_add`, SUM(`duration`)/60 AS ConnTime, SUM(`download`)/1000000 AS TotalDown, SUM(`upload`)/1000000 AS TotalUp
FROM `cdr_data_february`
WHERE (`bs_id_site` LIKE '".$btsid."') AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
GROUP BY `user_id`");
I have such a MySQL Query that I need to run on PHP.
I need to get the Number of Row after GROUPING (i.e. after using GROUP BY).
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
This is returning me the Total Number of Rows (before GROUPING) in fact.
I am not understanding that what should be the code to receive the Row Number (after GROUPING).
Note for a Case: For a query it is returning 15 as $numrows, which is the total number of rows before GROUP BY, but I need that $numrows will return 5, which is the number of rows after GROUP BY.
If someone knows the solution please help me to solve it. Thanks.
You can use ...
$num_rows = mysql_num_rows($result);
... which returns total row count.

sort an $array of ints by repetition and remove repetitions

i need to do this in php
lets say i have [1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,9,9,9,9,9]
i would like [1,5,9,2,3,4]
but my situation its a bit different, it's result from a mysql query
i have only an asociative atribute 'id_deseada', so i do now
while($row = mysql_fetch_array($result){
$t = $row['id_deseada'];
}
so instead of that, i guess i'd have to do domething like the first example; sort $result ordered by times of repetition and maybe beetter in a new array with a new field 'count' ?
This all begins because of this query:
SELECT articles.id as id_deseada,tags.* FROM articles,tags WHERE tags.id_article = articles.id AND tags.name IN ('name one','name two','form search inputs','...)
the problem is that returns one result for every tag and i want on result for every article..
First, generate the value array like this:
$vals = array();
while($row = mysql_fetch_array($result){
$vals[] = $row['id_deseada'];
}
Then, count and sort:
$valCounts = array_count_values($vals);
arsort($valCounts);
$result = array_keys($valCounts);
You can actually do it using an SQL query. For example, we have this table:
create table lol (id_deseada int);
insert into lol values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(2),(3),(4),(5),(5),(5),(5),(5),(5),(5),(5),(5),(5),(5),(9),(9),(9),(9),(9);
You can select the id_deseada's from the database sorting by repetitions by using grouping and ordering.
SELECT id_deseada FROM lol
GROUP BY id_deseada
ORDER BY COUNT(*) DESC
Result: 1, 5, 9, 2, 3, 4.

Faster way to know the total number of rows in MySQL database?

If I need to know the total number of rows in a table of database I do something like this:
$query = "SELECT * FROM tablename WHERE link='1';";
$result = mysql_query($query);
$count = mysql_num_rows($result);
Updated: I made a mistake, above is my actual way. I apologize to all
So you see the total number of data is recovered scanning through the entire database.
Is there a better way?
$query = "SELECT COUNT(*) FROM tablename WHERE link = '1'";
$result = mysql_query($query);
$count = mysql_result($result, 0);
This means you aren't transferring all your data between the database and PHP, which is obviously a huge waste of time and resources.
For what it's worth, your code wouldn't actually count the number of rows - it'd give you 2x the number of columns, as you're counting the number of items in an array representing a single row (and mysql_fetch_array gives you two entries in the array per column - one numerical and one for the column name)
SELECT COUNT(*) FROM tablename WHERE link='1';
You could just do :
SELECT count(*) FROM tablename;
for your query. The result will be a single column containing the number of rows.
If I need to know the total number of rows in a table of database
Maybe I'm missing something here but if you just want to get the total number of rows in a table you don't need a WHERE condition. Just do this:
SELECT COUNT(*) FROM tablename
With the WHERE condition you will only be counting the number of rows that meet this condition.
use below code
$qry=SHOW TABLES FROM 'database_name';
$res=mysql_query($qry);
$output=array();
$i=0;
while($row=mysql_fetch_array($res,MYSQL_NUM)){
++$i;
$sql=SELECT COUNT(*) FROM $row[0];
$output[$i]=mysql_query($sql);
}
$totalRows=array_sum($ouptput);
echo $totalRows;
http://php.net/manual/en/function.mysql-num-rows.php You need this i think.
If you are going to use the following SQL statement:
SELECT COUNT(*) FROM tablename WHERE link='1';
Make sure you have an index on the 'link' column

saving a column in an array

I'm trying to fetch random no. of entries from a database by using
SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10
it returns a column of database.
If I want to save all the entries in a array, then which php function do I have to use to save the column.
Something along the lines of this?
$result = mysql_query("SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10");
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row[0];
}
Updated to not use the $i variable as pointed out in the first post and the comment.
Look at some examples for how to run a query and get a result set.
http://www.php.net/mysqli
Once you have the result in a variable, do this:
$myarray = array();
while($row = mysqli_fetch_row($result))
$myarray[] = $row[0];
With PDO:
$qryStmt = $dbc->query('SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10');
$a = $qryStmt->fetchAll( PDO::FETCH_COLUMN );
BTW: If you just want to get one row by random, this is much faster esp. for large tables:
select * from table limit 12345,1;
where 12345 is just a random number calculated from the count() of rows.
see here, which is more for rails, but have a look at the comments too.
But be careful: in limit 12345,2 - the second row is not random but just the next row after the random row. And be careful: When I remember right (eg. SQLServer) rand() could be optimized by databases other than mysql resulting in the same random number for all rows which makes the result not random. This is important, when your code should be database agnostic.
a last one: do not mix up "random" with "hard to predict", which is not the same. So the order by example "select top 10 ... order by rand()" on SQLServer results in two different result sets when run twice, BUT: if you look at the 10 records, they lie close to each other in the db, which means, they are not random.

Categories