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();
Related
How do i encode this in json format? I am receiving the same data in my 1st, 2nd and 3rd if i put 1st, while if i put "2nd"=>$row1, "3rd"=>$row1 the same data as the 1st is being retrieved. If i try to put in 3 it gives me a null. Please someone help, Thanks.
Here is my php
$sql = "select
n_name,
shortcut,
case
when rank = 1 then '1st'
when rank = 2 then '2nd'
when rank = 3 then '3rd'
end as rank
from
team inner join nonsport on team.n_id = nonsport.n_id group by n_name order by n_name asc";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("n_name"=>$row[0], "1st"=>$row[1], "2nd"=>$row[2], "3rd"=>$row[2]));
}
echo json_encode (array("nresults"=>$response));
My expected output is
Example. Shortcut has a, b, c and they have rank a =1 b =2 c =3;
Then 1st = a, 2nd = b, 3rd = c;
What im getting is
1st = a, 2nd = a, 3rd = a
your query is returning 3 attributes for each row "n_name, shortcut, rank" and the rank will be "1st", "2nd", or "3rd", so you will not get the three ranks in a single row. I think you need to check the value of rank before assign it, as follow:
while($row=mysqli_fetch_array($result)){
$array = [];
$array["n_name"] = $row[0];
if($row[1]=='a'){
$array["1st"] = $row[1];
} elseif($row[1]=='b'){
$array["2nd"] = $row[1];
} elseif($row[1]=='c'){
$array["3rd"] = $row[1];
}
array_push($response, $array);
}
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
?>
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
I have a mysql table with the following columns:
ID Units
1 1234,6543,9876
2 1234,6543
3 6543
4 9876
5 0987
I would like to reverse the relationship to get an output like this:
Unit IDs
1234 1,2
6543 1,2,3
9876 1,4
0987 5
I was wondering if this could be done in a query or some php, without chunking through with explodes etc?
Using comma-separated lists in SQL is awkward. This is a denormalized design, and SQL is not well suited to work with data in this format.
I would fetch all the data back into PHP and manipulate it there.
$id_per_unit = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$unit_array = explode(",", $row["Units"]);
foreach ($unit_array as $unit) {
$id_per_unit[$unit][] = $row["Id"];
}
}
Something like this:
$query = "SELECT `Unit`, `IDs` FROM `table` ORDER BY `Unit`";
$data = mysqli_query($con, $query);
$prev_unit = '';
while ($row = mysqli_fetch_array($data)) {
if ($prev_unit != $row['Unit']) {
// echo a new row with the new unit and then ID
} else {
// echo just the ID in the same row, this unit is the same as the last one.
}
$prev_unit = $row['Unit'];
}
With only SQL, you can do something like this :
SELECT unit , GROUP_CONCAT(id)
FROM (
SELECT id,substring_index(Units,',',1) AS unit
FROM Table1
UNION
SELECT id,REPLACE(
REPLACE(SUBSTRING_INDEX(Units,',',2),SUBSTRING_INDEX(Units,',',1),'')
,',','') AS unit
FROM Table1
UNION
SELECT id,REPLACE(
REPLACE(SUBSTRING_INDEX(Units,',',3),SUBSTRING_INDEX(Units,',',2),'')
,',','') AS unit
FROM Table1) AS UNITS
WHERE unit != ''
GROUP BY unit
See SQLFIDDLE
I have an issue with my code. I have 2 tables. First employee_id:
|Employee id|
1
2
3
And the second table called employee_times:
|Employee_id|Hours_dev|hours_pm|
|1|2|3|
|1|3|4|
|2|3|3|
What I am trying to do is to calculate the total time that each employee has worked (hours_dev+hours_pm). For example employee_id 1 has worked 12 hours
So far I have tried to retrieve all the employee_id from the first table and use a for loop to go through the employee_times in an SQL statement (SEE CODE BELOW). However the code does not work as it prints 0 for both employee_id and total_hours.
I am using MYSQL on a localhost server.
$sql = "SELECT employee_id FROM employee";
$result = mysql_query($sql);
while($row = mysql_fetch_array)
{
$employee_id = $row['employee_id'];
}
$employee_id_length = sizeof($employee_id);
for($i = 0; $i < $employee_id_length; $i++)
{
$sql4 = "SELECT employee_id, hours_dev, hours_pm FROM employee_times WHERE employee_id= '$employee_id[$i]'";
$result = mysql_query($sql4);
while($info = mysql_fetch_array($result));
{
$employee_id = $info['employee_id'];
$hours_dev=$info['hours_dev'];
$hours_pm=$info['hours_pm'];
$total_hours = ($total_hours + $hours_dev + $hours_pm );
}
//print "$employee_id worked for $total_hours";
}
Any help is much appreciated.
you can get sum directly
select employee_id, sum(hours_dev)+ sum(hours_pm) as total
from employee_times WHERE employee_id= '1'
group by employee_id
refer this Fiddle Demo
this should get the data you need
SELECT
hours_dev,
hours_pm,
sum(hours_dev) + sum(hours_pm) as total_hours
FROM
employee_times
WHERE
employee_id = 123
GROUP BY
employee_id
Take a look at aggregate functions:
http://www.w3schools.com/sql/sql_functions.asp
http://www.w3schools.com/sql/sql_func_sum.asp
This SQL query should pull the info much quicker than by script;
SELECT Employee_id, SUM(Hours_dev), SUM(Hours_pm), SUM(Hours_dev + Hours_pm)
FROM employee_times
GROUP BY Employee_id