MySQL row selection - php

I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.

Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row

You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1

You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.

You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"

Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}

Related

Diffrence in mysql query speeds

Suppose i have 1kk records in my database.
Now i need to select some data, and also i need to know how many fields did i select, so my question is:
Is it better to run one query to count data like this:
SELECT COUNT("id") from table where something = 'something'
And after that run one more querio for selection like this:
SELECT 'some_field' from table where something = 'something';
Or Maybe it's better to just select data and then just count it with php like:
count($rows);
Or maybe there is even better ways to do it, for example do it all in one query?
Reading between the lines, I think what your are probably after is SQL_CALC_FOUND_ROWS. This allows you to select part of a result set (using a LIMIT clause), and still calculate the total number of matching rows in a single operation. You still use two queries, but the actual search operation in the data only happens once:
// First get the results you want...
$result = mysql_query("
SELECT SQL_CALC_FOUND_ROWS
FROM `table`
WHERE `something` = 'something'
LIMIT 0, 10
");
// ...now get the total number of results
$numRows = mysql_query("
SELECT FOUND_ROWS()
");
$numRows = mysql_fetch_row($numRows);
$numRows = $numRows[0];
If you fetch all that 1000 records then you can count while you are fetching:
$res=mysql_query("SELECT 'some_field' from table where something = 'something'");
while($r = mysql_fetch_*($res)) {
$count++;
//> Do stuff
}
This way you make only one query and you don't use mysql_num_rows();
One query would be:
SELECT Count(*) AS NumRows, some_field from table
GROUP BY some_field where something = 'something';

How to add a single column php/mysql

I'm trying to add a single column in a db query result. I've read about the SUM(col_name) as TOTAL, GROUP BY (col_name2).
But is there a way i can only SUM the column without any GROUPing? I a case whereby all col_name2 are all unique.
For example... I have a result with the following col headers:
course_code
course_title
course_unit
score
grade
Assuming this have 12 rows returned into an HTML table. Now i want to perform SUM() on all the values (12 rows) for the column course_unit, in other to implement a GPA school grading system.
How can i achieve this.
Thanks.
SELECT SUM(col_name) as 'total' FROM <table>
GROUP BY is required only if you want to sum subsets of the rows in the table.
You can find sum or any aggregate db functions (such as count, avg, etc) for most cases without using group clause. Your sql query may look something like this:
SELECT SUM(course_unit) as "Total" FROM <table_name>;
As comments below have already pointed out: SELECT SUM(course_unit) AS total FROM your_table;. Note that this is a separate query to the one with which you retrieve the table data.
This does it in php. I'm not sure how to do it with pure sql
$query = "SELECT * FROM table";
$result = mysql_query($query);
$sum = 0;
while($row = mysql_fetch_assoc($result))
{
$sum+= intval($row['course_unit']);
}
echo $sum;
SELECT
course_code,
course_title,
course_unit,
score, grade,
(select sum(course_unit) from TableA) total
from TableA;

Mysql Order by Tweak

I have a database with nearly 100 fields.
DB structure is
id | comment | time
I need to fetch only 5 newest record (I can get those records using ORDER by time DESC). But while printing them I need to print the oldest of those 5 records first and proceed in reverse in a way that the newest record will be printed last.
SELECT s.* FROM (
SELECT id, comment, time FROM table1
ORDER BY time DESC
LIMIT 5 ) as s
ORDER BY s.time ASC
Ok, after fetching result set in ascending order with a limit of number of rows
you can do this to print them in reverse order (descending order)
$data= array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
$records = array_reverse($data);
OR
This could be done with mysql_data_seek
Directly taken from here
for ($i = mysql_num_rows($resultset) ā€“ 1; $i >= 0; $iā€“) {
mysql_data_seek($resultset, $i);
$row = mysql_fetch_assoc($result);
echo $row['abc'] . ' ' . $row['xyz'] . "\n";
}
You can use PHP's array_reverse() function on your result list.
http://php.net/manual/en/function.array-reverse.php
You can use also something like this:
select * from (select * from table_name where 1=1 order by time desc
limit 5) as tbl order by tbl.time;
Edit if you have a lot of accesses to this statement it would be much better to represent it as materialized view. Though there are no materialized views in mysql it is possible to simulate them (http://lists.mysql.com/mysql/207808)
Using a materialized view or a simulated materialized view will seriously outperform the suggested php approaches. Most of the mentioned ones consume to much memory anyways .
I guess you could do something along the lines of (untested):
SELECT
*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
)
ORDER BY
time ASC
UPDATE
Apparently, the "derived table must have its own alias" (error #1248). Other answers have already done this, so I'll jump on the bandwagon. Below you'll find the revised (and tested) query:
SELECT
derived.*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
) AS derived
ORDER BY
derived.time ASC
By the way, this is supported as of MySQL 4.1.

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