OK so I have a table like this
Col1 Col2
10 30
20 40
50 60
I am querying the data like so
Query = ("SELECT * FROM TableName");
while ( $row= Mysql_fetch_array($query)) {
// code will go here
Code needs to get the prev row and the current row for every row in the table like:
This row['col1'] - prev row['col1'] = $wahatever
echo $whatever
}
I dont know whow to reference the prev row in php so as it looks through the while statment I need to say col1 - prev col1 and col2 - prev col2
Can Anyonw tell me how to do this. Its actually for working out complex mapping distcances which I can do, just cant work out how to call the prev rows data in the loop.
Any help would be greatfully apprceiated
Thanks for all your help but I dont think I asled the question properly.
What I am looking for is for a way to get each row and then minus col1 from col1 on the prev row and run through a loop untill the end.
You can try this completly in SQL solution
SELECT col1, col2,
col1 - #prev1,
col2 - #prev2,
#prev1 := col1, #prev2 := col2
FROM TableName, (select #prev1 := 0, #prev2 := 0) r
SQLFiddle demo
$prevRow = null;
while ( $row= Mysql_fetch_array($query)) {
if($prevRow != null){
//comparison here
}
$prevRow = $row;
}
Or, you could store your values first in an array like
$myArr = array(); $i=0;
while ( $row= Mysql_fetch_array($query)) {
// code will go here
$myArr[$i] = $row['col1'];
$myArr[$i] = $row['col2'];
$i++;
}
Then you would know that $i-1 is the previous row from db.
foreach($myArr as $i => $row) {
if( isset($myArr[$i-1]) {
$prevRow = $row;
}
// blah blah blah
}
You can use mysql_data_seek for changing pointer to current row and then fetch it, but I recommend to store previous value in each step
if you will compare 2 different rows most probably they will not be equal if they have id which is primary and auto incrementing but if you will just compare the specific data's in the row best way is to store them or you can query all column but not including the id
query the id-1 of the current query just make sure to make the id primary and auto increment for example
<?php
$que = "SELECT * FROM table ...'";
res = mysql_query($que, $con);
if(mysql_num_rows($res)>0){
while($row = mysql_fetch_array($res)){
$counter=1;//apply this so it will not compare the first row in the data to the previous
//one because there is nothing to compare
if($counter > 1){//determine if it is the 2nd row therfore do the comparison
$currentrow=$row['id']; //this is the id of the current row which is row 2
$previousrowid=$row['id']-1; //this is the id of the row 1 which you will need to query
//the datas on it to compare it
$que2 = mysql_query("SELECT value FROM table where id= '$previousrowid' ");//query of the previous row
$r = mysql_fetch_array($que2);
$previousdata=$r['data'];
$currentdata=$row['data'];
$counter++;
if($previousdata != $currentdata)
{
echo "They Are Not Equal";
}else{
echo "They Are Equal!";
}
}//ending of the counter
}}//ending of loop
?>
hopes this help
Related
I need to extract records from a database like this:
id
name
request1
request2
request3
request4
request5
time
request fields can be 0 or 1
and I have my SQL query SELECT * FROM table ORDER BY id ASC but I'm getting only one record for row, but I need to print the records like this:
id1 - name1 - request1
id1 - name1 - request2
id2 - name2 - request4
id2 - name2 - request5
this means having an extract for every single "request = 1"
How can I afford this?
require("datisql.php");
dbconnect();
mysql_query("SET CHARACTER SET 'utf8'");
$result2 = mysql_query("SELECT * FROM richieste ORDER BY id DESC");
while($row = mysql_fetch_array($result2)) {
$id="{$row['id']}";
$nominativo="{$row['nominativo']}";
$data="{$row['timestamp']}";
echo"<div>...........";
}
Here an abstract of the requests table: click me
My answer is based on the assumption that all of the requests columns are in one row. If I am wrong, I will change that. The way I would handle taking a recordset that looks like that would be to loop through each row and throw each row into a for loop like this:
// Add each of the request types to an array
$requestTypes = array('Interior','Exterior');
// Loop through the resultset
while( $row = mysql_fetch_array( $result2 ) ){
foreach($requestTypes as $type){
$id= $row['id'];
$nominativo = $row['nominativo'];
$requestedType = $row[$type];
$data = $row['timestamp'];
}
}
I have this php code - for loop and on every step , every increment search for data in mysql table aktivnosti
PHP:
for ($i=1; $i<=30; $i++;){
$temp = array();
$temp['ID'] = $i;
// ATTEMP TO GET DATA FROM aktivnosti WHERE id_activity = $i
$rs1 = $db->prepare('SELECT naziv FROM aktivnosti WHERE id_activity=:idd');
$rs1->bindParam(':idd', $i);
$rs1->execute();
$naz = $rs1->fetchColumn();
$temp['activity'] = '<button>'.$naz.'</button>';
$output['data'][] = $temp;
}
$jsonTable = json_encode($output);
So as you can see from code above I try to get data on every $i increment and search if id_activity on table aktivnosti = $i
I get just one result so I get just first 'naziv', I need to get all naziv data from table aktivnosti where id_activity = $i and create:
<button>$naz[0]<button>
<button>$naz[1]<button>
<button>$naz[2]<button>
<button>$naz[how many times id_activity = $i]<button>
How I can do that? Some ideas?
sorry for my engish. Thanks
As pointed out in comments above, you are taking a bad approach here. You should be able to get all this data in a single query. You probably also need to take a look at your schema if you want to have the concept of a fixed number of 30 days with each days related to n number of records. I would suggest two tables
day_list
day_id day_name (or any other day-related data fields)
1 ...
2 ...
... ...
30 ...
days_records
record_id day_id other_data
1 1 ...
2 1 ...
3 3 ...
4 5 ...
...
You would then query this like:
SELECT
d.day_id AS day_id
dr.record_id AS record_id
dr.other_date AS other_data
FROM day_list AS d
LEFT JOIN day_records AS dr
ON d.day_id = dr.day_id
Sorry for the change in table names, as don't know what your database schema represents in real-world terms.
You then make a single query like:
$query = <<<EOT
SELECT
d.day_id AS day_id
dr.record_id AS record_id
dr.other_date AS other_data
FROM day_list AS d
LEFT JOIN day_records AS dr
ON d.day_id = dr.day_id
EOT;
$rs1 = $db->execute($query);
if (false === $rs1) {
// something went wrong. perhaps log an error
} else {
while($row = $rs1->fetch(PDO::FETCH_ASSOC)) {
$temp = $row;
// check to see if this date has a record
if (empty($temp['record_id'])) {
// this is a day with no associated record.
// do something
}
// not shown - continue to manipulate your $temp as desired
// then add to output array
$output['data'][] = $temp
}
}
If you need both ID and activity:
$sql = <<<EOD
SELECT
id_activity AS ID,
CONCAT('<button>', naziv, '</button>') AS activity
FROM aktivnosti
WHERE id_activity BETWEEN 1 AND 30
ORDER BY id_activity
EOD;
$data = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$jsonTable = json_encode(compact('data'));
If you only use activity:
$sql = <<<EOD
SELECT CONCAT('<button>', naziv, '</button>')
FROM aktivnosti
WHERE id_activity BETWEEN 1 AND 30
ORDER BY id_activity
EOD;
$data = $db->query($sql)->fetchAll(PDO::FETCH_COLUMN, 0);
$jsonTable = json_encode(compact('data'));
try this...
while($naz=$rs1->fetch(PDO::FETCH_OBJ))
{
echo $naz->column1;
echo $naz->column2;
}
instead of
$naz = $rs1->fetchColumn();
I have one table with some rows and lot of columns (about 50)
- I don't want to list all the column names, co I use a while loop to go through the table and a foreach command to find the column names and values.
Now I would like to add these two rows into one row (where id is 1) and sum the values together...
id | col 1 | col 2 | ...
1 30 21
1 11 16
2 75 0
It should look like this
id | col1 | col2 | ...
1 41 37
2 75 0
This is what I have...
$query = mysql_query("SELECT * FROM `table` WHERE `id`='1'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $val) {
if($key != 'id') {
//the sum code...?
}
}
}
Could you please help me? Thank you a lot...
Based on your code which indicates you're using mysql I'm going to give you a mysql solution (which can easily be ported to most RDBMS). What you're looking for can easily be accomplished with aggregate functions. Follow the link to read about all the aggregate functions mysql has.
SELECT id, SUM(col1), SUM(col2) FROM table GROUP BY id;
just sum the results in mysql.. databases are made to handle things like this so it'll be a faster solution than doing it just in php.
SELECT
id,
SUM(col1),
SUM(col2)
FROM table
GROUP BY id;
Try this: See the Explanation as comments:
<?php
$query = mysql_query("SELECT * FROM `table` WHERE `id`='1'");
//Initially Set all the columns as zero.
$col1 = 0; $col2 = 0;
//Etc.
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $val) {
if($key != 'id') {
$$key += $val;
//Like: $col1 += 30;
}
}
}
//Now All the variables are ready added:
//Like: $col1 = 41;
//Like: $col2 = 37;
//Use them However you like:
//To update:
//1. First Delete both rows:
$query = mysql_query("DELETE FROM `table` WHERE `id`='1'");
//2. Insert
$query = mysql_query("INSERT INTO `table` (`id`,`col1`,`col2`) VALUES ('1','{$col1}','{$col2}') ");
//And so on
?>
I have the following structure:
Table: products
id, name, sort_order
Let's say I only have 5 products, but I want 20.
How would I loop through to get 20 results?
Additionally, I'll need to start at a specific sort_order. So let's say I have
1,2,3,4,5
and I want to get 20 results and start at 3. It should end up as:
3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,etc.
Any ideas? I'm totally lost.. thank you!
$how_many = 20;
$counter = 0;
$rows = array();
$result = mysql_query("Your query");
while($row == mysql_fetch_row($result)) {
$rows[] = $row;
}
$expanded = array();
for($i = 0; $counter < $how_many; $counter++) {
$expanded[] = $rows[$i];
$i++;
if($i == count($rows)) {
$i = 0;
}
}
And now $expanded is filled with those 5 rows for 4 times.
Edit: and don't forget to adjust $i to your start element. For your example that would mean $i = 2 (third element).
create a table named abc and use this procedure to populate the table
CREATE PROCEDURE `populator`(i INT)
BEGIN
DECLARE existing int;
DECLARE counting int;
DECLARE limitation int default i;
SELECT COUNT(*) INTO existing FROM asd;
theLoop: LOOP
SELECT COUNT(*) INTO counting FROM abc;
IF (existing + counting) > i
THEN SET limitation = i - counting;
END IF;
IF counting >= i
THEN LEAVE theLoop;
ELSE
SET #sql = CONCAT("INSERT INTO abc SELECT id from asd LIMIT ", limitation);
PREPARE s1 FROM #sql;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END IF;
END LOOP theLoop;
END
remember to rename the tables. i used asd as source table and abc as destination table. if you do the concatenation thing right you can even write a procedure that works with temporary tables.
You can do this in MySQL by cheating:
SELECT
t1.id
FROM
products t1
CROSS JOIN products t2
LIMIT
2, 20
Like the others, I'm not 100% sure what you want. You want to show the same products over again until 20 times?
$count =0;
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");
$result4= mysql_fetch_array($result3);
print $result4[$count].'<br>';
$count++;
}
mysql_free_result($result1);
mysql_free_result($result3);
Let's have a look at how mysql_fetch_array works - for example if you have table structure like
id | name | surname | role
1 John Smith user
2 Peter Qeep user
3 Mark Ziii admin
When you execute a query SELECT * FROM table and then loop $result = mysql_fetch_array($query), $result will always be an array(4) containing
[0] => id,
[1] => name,
[2] => surname,
[3] => role
Therefore, when you execute the query $result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");, in the first iteration, $count will be 0 which is the key for the result returned by the previous query, however in any further iteration it will increase and that will lead to an undefined key. This means that you have to stop using the variable $count and just use $result2[0] instead.
Also, way better approach to this would be using MySQL JOIN, in your example it would be SELECT w.fsyn FROM sbsw s JOIN wrsyn w ON s.fwid = w.fwid WHERE s.fword = "'.$searchText.'";
Please, use reasonable variable names and indent properly. You're getting one column from each row as you're only printing out once for each iteration over your rows.
Basically: For each row, print the value of a column.
The $count-variable decided which column, but it obviously didn't make sense at it counts the row you're at.
Something like this should do it: (not tested)
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2['fwid']."'");
$result4= mysql_fetch_row($result3);
for($x = 0; $x < count($result4); $x++){
print $result4[$x].'<br>';
}
}
mysql_free_result($result1);
mysql_free_result($result3);
Oh and I changed fetch_array to fetch_row in the inner loop to ease iteration.