I currently have a query
$query = "SELECT * FROM routes ORDER
BY id DESC LIMIT 8;";
And that works all wonderfully.
I have table columns
id int(10)
name varchar(45)
base varchar(16)
econ int(6)
location varchar(12)
x int(2)
y int(2)
galaxy int(2)
planet int(2)
comment varchar(100)
ipaddress varchar(45)
and on the page when this segment of php is called i will have
the econ,X,Y,Galaxy,and planet of another entry
then i want to display the entry is the database(like i do at the moment) BUT
i want a new column to be displayed that is not in the DB, this new column is to be the output of a calculation..
the calculation is to be
Sqrt(min. Economy) x ( 1 + Sqrt(Distance)/75 + Sqrt(Players)/10 )
Sqrt(88) x ( 1 + Sqrt(23)/75 + Sqrt(23)/10 ) = 15 cred./h
players is another variable that is already available in my page
Distance is a function of the 2 galaxys unless there the same when its a function of the 2 x's and y's unless there the same and then its a function of the 2 planet integers
here is the page i talk of..i will add a new button to compare.. thats the new function that i want to compare the given value with existing values.
http://www.teamdelta.byethost12.com/trade/postroute2.php
You can just calculate in your query like this:
$query = "SELECT (Sqrt(min. Economy) x ( 1 + Sqrt(Distance)/75 + Sqrt(Players)/10 ) Sqrt(88) x ( 1 + Sqrt(23)/75 + Sqrt(23)/10 ) = 15 cred./h) as `Distance`, * FROM routes ORDER BY id DESC LIMIT 8;";
Use as for naming your calculation so its become a column and use * to get the other fields.
After the query you store the results into an array. You could parse the array adding an item containing the calculation that you wrote.
If you want more details you should past here the array
--
dam
Related
I have articles and each of them has views. And in sidebar i display the most visited articles. All is working, but with order is problem. For example i have 4 articles. 1 article has 10 views, 2 - 7 views, 3 - 6 views, 4 - 3 views. And order is
1) 1 article - 10
2) 2 article - 7
3) 3 article - 6
4) 4 article - 3
So we can see that all is ok. But when i add one more artilce and it has 1 views order change and 5th artilce goes to top but why. It has lower views then another articles? And when 5th article get 10 views, all is ok and order restored. But why just when order resores when last artilce has more then 10 views?
<?php
$dbname="php";
$dbhost="localhost";
$dbusername="root";
$dbuserpassword="";
$optins= array(PDO::MYSQL_ATTR_INIT_COMMAND=>'set NAMES utf8');
try{
$db= new PDO("mysql:host={$dbhost};dbname={$dbname};chartset=utf8",
$dbusername,$dbuserpassword,$optins);
} catch (PDOException $ex) {
die("Fail to connect".$ex->getMessage());
}
// all post
$sql = "select * from tbl_blog order by page_view desc limit 5";
$data=$db->prepare($sql);
$data->execute();
$allpost=$data->fetchAll();
// Single Post
CREATE TABLE:
CREATE TABLE tbl_blog (
id int(11) NOT NULL,
blog_title text NOT NULL,
description text NOT NULL,
content text NOT NULL,
page_view varchar(10) NOT NULL,
category text NOT NULL,
img varchar(225) NOT NULL,
sub_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB DEFAULT CHARSET = utf8
For me, it's seems that the alphabetic order take control of the page_view attribute.
If your page_view attribute is define as varchar, it will be ordered like a character, for exemple:
"3"
"2"
"12"
"11"
"10"
"1".
Check to put the page_view attribute as integer, to have
1
2
3
10
11
12
Hope this help
The problem is the datatype of page_view is VARCHAR(10), so it gets sorted as strings, not as numbers.
Change the data type to a numeric type (e.g. INTEGER) and it'll sort correctly.
Hi i need 5 rows count always in Mysql select query
I My current output is
my query
----------------------
$query = mysql_query("select * from table_name where MOBILE='$mobile_no' order by ID LIMIT 5 ");
----------------------
Result
----------------------
ARUN - 987654321
VINO - 987654321
RAJA - 987654321
-------------------
But I need like this (Need to return empty rows)
----------------------
ARUN - 987654321
VINO - 987654321
RAJA - 987654321
0 - 0
0 - 0
-------------------
So that I can create html table row (always 5 rows) text box with empty value inside the while loop ----- while($row=mysql_fetch_array($query))
You can use a loop in php and a counter in the loop. If the count is less then 5, then you fill the text box with nothing. It will give you something like that
$count = 0;
while($row=mysql_fetch_array($query)) {
// Fill your text box
$count+=1;
}
for($i=count; $i <= 5; $i++) {
// Fill your text box with empty string or whatever.
}
Since you requested a sql solution here it is: (but I do not recommend using it)
SELECT *
FROM (SELECT id, column1
FROM table_name
WHERE mobile = '$mobile_no'
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL)
AS tab
order by tab.ID LIMIT 5
but you need to explicitly select all the columns from your table and in the select statements add as many NULL columns as you selected in your main statement. I didn't test it since I don't know your columns
simply add 2 more textboxes in html page. and not send any value or send null values in your database
I am definitely stumped on how to arrange a result set.
I have a table which currently contains strictly dates.
DATES
ID Dates
1 2015-05-26
2 2015-05-27
3 2015-05-28
4 2015-05-29
5 2015-05-30
each of those dates are also the name of the table for that day which keeps track which user/agent was present for training.
2015-05-26
ID Attendance
101 Present
201 N/A
301 Present
401 Present
501 Present
The end goal for this is to create the following table:
Now here is what I have accomplished for the table header.
$data_date = true;
$list = "SELECT * FROM list ORDER BY id DESC LIMIT 5";
$result = mysql_query($list);
while ($row = mysql_fetch_assoc($latest)){
$dates[] = $row['date'];
}
foreach($dates as $x){
$data_date .= "<th>$x</th>";
}
By simply echoing out the $data_date I am able to display the headers like the following.
<table>
<tr>
<th>AGT</th>
<?php echo $data_date; ?>
</tr>
<tr>
</tr>
</table>
So far so good. The final step of taking the array and creating new row for each and querying each day from the dates array has me at a loss.
I've been trying for over an hour and cant seem to wrap my head around the array needed to query a new row for each agent.
Any pointers or help would definitely be appreciated.
perhaps this is a start. date-math routines can grab 5 day attendance results
consider the following
create table agent
(
agentid int NOT NULL PRIMARY KEY, -- use AUTO_INCREMENT, whatever
agentname varchar(60)
);
insert agent (agentid,agentname) values (109,'Guy Smiley');
insert agent (agentid,agentname) values (110,'Susie Chapstick');
-- select * from agent
create table class_session
( -- a session is say Monday to Friday, captures a start date
sessionid int not null PRIMARY KEY, -- the week session #
startdate datetime not null,
location varchar(40) -- etc etc
);
insert class_session (sessionid,startdate,location) values (1001,'10/1/2014','Ritz London');
create table session_signup
( -- the list of agents who should be present
sessionid int not null, -- the week session #
agentid int not null
);
create table agent_present
(
sessionid int not null, -- the week session #
agentid int NOT NULL,
thedate datetime not null,
thestatus varchar(40) -- present, present but sleeping, etc
);
position | Average | gpmp
1 70.60 2.0
2 60.20 2.3
3 59.80 4.8
4 59.80 4.8
5 45.70 5.6
Hie All,
As above table, I need to arrange the position according to the lowest gpmp and the highest average. But when the both average and gmp are the same, I will need to have the position to be the same.
For example, position 3 and 4 have the same average and gpmp. How do I generate the mysql query or using php function so that after they detect the same average and gpmp and change the position 4 to 3.
Which mean after the function is generated it will become like the table below.
position | Average | gpmp
1 70.60 2.0
2 60.20 2.3
3 59.80 4.8
3 59.80 4.8
5 45.70 5.6
Here's a simple way to update the table as you described in your post - taking the sequential positions and updating them accordingly. It doesn't calculate the positions or anything, just uses the data already there:
UPDATE `table` t SET position = (
SELECT MIN(position) FROM (SELECT * FROM `table`) t2 WHERE t.Average = t2.Average AND t.gpmp = t2.gpmp
)
I'd give something like the following a try, through it does assume a primary key is on this table. Without a primary key you're going to have issues updating specific rows easily / you'll have a lot of duplicates.
So for this example I'll assume the table is as follows
someTable (
pkID (Primary Key),
position,
Average,
gpm
)
So the following INSERT would do the job I expect
INSERT INTO someTable (
pkID,
position
)
SELECT
someTable.pkID,
calcTable.position
FROM someTable
INNER JOIN (
SELECT
MIN(c.position) AS position,
c.Average,
c.gpm
FROM (
// Calculate the position for each Average/gpm combination
SELECT
#p = #p + 1 AS position,
someTable.Average,
someTable.gpm
FROM (
SELECT #p:=0
) v,someTable
ORDER BY
someTable.Average DESC,
someTable.gpmp ASC
) c
// Now regroup to get 1 position for each combination (the lowest position)
GROUP BY c.Average,c.gpm
) AS calcTable
// And then join this calculated table back onto the original
ON (calcTable.Average,calcTable.gpm) = (someTable.Average,someTable.gpm)
// And rely on the PK IDs clashing to allow update
ON DUPLICATE KEY UPDATE position = VALUES(position)
(pseudo code)
select * from table
get output into php var
foreach (php row of data)
is row equal to previous row?
yes - don't increment row counter, increment duplicate counter
no - increment row counter with # of duplicates and reset duplicate counter
save current row as 'previous row'
next
you can try something like this in php:
$d= mysql_query('select distinct gpmp from tablename order by gpmp');
pos= 1;
while($r= mysql_fetch_array($d)){
mysql_query('update tablename set position='.$pos.' where gpmp='.$r['gpmp']);
$pos++;
}
You only need to "expand" the idea to take averange in account too.
I'm trying to change my rating system which only used one table before but now I'm changing it to use multiple tables and I really dont no how to
update or insert a new rating into the database and was wondering how to do this using my MySQL tables structure?
Also how do I do this by adapting the new code to my current PHP code which I want to change which is listed below.
First let me explain what my tables do they hold the information when students rate there own teachers I listed what the tables will hold in the
examples below to give you a better understanding of what I'm trying to do. Students are only allowed to rate there teachers once.
I provided the two MySQL tables that should be updated which are listed below.
My MySQL tables
CREATE TABLE teachers_grades (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
grade_id INT UNSIGNED NOT NULL,
teachers_id INT UNSIGNED NOT NULL,
student_id INT UNSIGNED NOT NULL,
date_created DATETIME NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE grades (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
letter_grade VARCHAR(2) NOT NULL,
grade_points FLOAT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (id)
);
What the database will hold.
teachers_grades
id grade_id teachers_id student_id date_created
1 3 2 32 2010-01-23 04:24:51
2 1 32 3 2010-01-23 12:13:58
3 2 32 103 2010-01-23 12:24:45
grades
id letter_grade points
1 A+ 10
2 D 3
3 B 5
Here is the old PHP code.
// function to insert rating
function rate(){
$text = strip_tags($_GET['rating']);
$update = "update vote set counter = counter + 1, value = value + ".$_GET['rating']."";
$result = mysql_query($update);
if(mysql_affected_rows() == 0){
$insert = "insert into vote (counter,value) values ('1','".$_GET['rating']."')";
$result = mysql_query($insert);
}
}
Old table.
CREATE TABLE vote (
`counter` int(8) NOT NULL default '0',
`value` int(8) NOT NULL default '0'
);
first , do mysql_escape_string to the parametrs when inserting like :
mysql_real_escape_string($_GET['rating']);
second
you need to get all parameters (from GET or POST) and insert it to the db ,
the teacher_id ....
now i only see the rating.
Your old table was bit confusing as it seems like it only rates 1 teacher or teachers as a whole.
Now it seems like your new design process requires you to:
- store rating and averages of teachers
- track historical ratings from students
rating table should look something like
Table: rating
rating_id student_id teacher_id grade_id date_created
1 101 21 1 2010-01-23 04:24:51
2 102 21 1 2010-01-23 04:26:51
3 102 22 2 2010-01-23 04:28:51
4 103 24 1 2010-01-23 04:44:51
Your code usage:
$rating_value = $_GET['rating']; // Remember to sanitize your inputs
$student_id = $_GET['student_id'];
$teacher_id = $_GET['teacher_id'];
rate_a_teacher($teacher_id, $student_id, $rating_value);
Your method:
function rate_a_teacher($teacher_id, $student_id, $rating_value)
{
// Find the corrosponding to specified rating value
$grade_id = find_grade_id($rating_value); //TODO
$sql = "
INSERT INTO rating
('student_id', 'teacher_id', 'grade_id', 'date_created')
VALUE
($student_id, $teacher_id, $grade_id, NOW);
";
mysql_query($sql);
}
I skipped implementation for find_grade_id() for you to fill it in yourself.
The purpose of splitting your calcualted values to individual records is so that you can start do interesting reports,
like such:
Find average rating value of each teacher for the past 3 months:
SELECT teacher_id, (SUM(points)/COUNT(rating_id)) AS average_score
FROM rating
LEFT JOIN grades ON grades.id = rating.grade_id
WHERE date_created > SUBDATE(NOW(), INTERVAL 3 MONTH)
GROUP BY teacher_id