What's wrong with my Group By clause? - php

Sorry for the stupid question, but I can't figure out why my data is displaying twice.
It's a very simple query. The DB table calendar_px currently has just three rows and four fields, including one for the date, another for the year and another (Brief) that includes some brief content.
So, if you visit the page MySite/Calendar/January_1, you should see all the years and briefs from the DB table that have a matching date (Date2) field (January_1). My practice table has three such rows:
1969 | So and so was born.
1969 | A volcano erupted.
1970 | They released a new song.
My code displays the information perfectly - except that it displays twice. I've grouped it by every field name, with and without the Cal2. extension, and nothing works. It looks like I must have made a really simple mistake, but I don't get it.
Here's my query...
$stm = $pdo->prepare("SELECT Cal2.N, Cal2.Date2, Cal2.Year, Cal2.Brief
FROM calendar_px Cal2
WHERE Cal2.Date2 = :MyURL
GROUP BY Cal2.Brief");
$stm->execute(array(
'MyURL'=>$MyURL
));
break;
}
while ($row = $stm->fetch())
{
$Year = $row['Year'];
$Brief[] = ''.$Year.' – '.$row['Brief'].'';
}
And this is what I have on the display page...
echo join( $Brief, '<br>' );

Try this:
$rows= $stm->fetchAll();
while ($rows as $row)
{
$Year = $row['Year'];
$Brief[] = ''.$Year.' – '.$row['Brief'].'';
}

Yikes, I knew I did something stupid, and I finally figured it out. I somehow included the file with the query twice. I have to remember to use require_once rather than a simple require.

Related

PHP SQL Request: select only the lowest value of time where name = $name and stage = $stage

Hi so I've already got a php script working working for this but it use a massive amount of data for a really easy task so I really would like to improve it.
My problem is the following: I have a SQL database build like this
and I would to do request like this one:
http://myphppage.php?username=Whataname&stage=1
and I would like it to echo the result so that if I read my php page content I can read the following:
21
so basicly all I want is to do a request with the username and the stage as parameters and I would like it to return the lowest value of the column "time" WHERE name=the name parameter entered AND stage = the stage parameter entered
I'm not really good in sql but I'm pretty I can make this kind of sql request in a single line or two instead of this massive script I have right now.
here's the current script I have:
<?php
$q2 = "SELECT username FROM DB WHERE stage='$stage' GROUP BY username ORDER BY time ASC";
$result2 = mysql_query($q2);
$times = array();
$userusernames = array();
$usernames = mysql_fetch_assoc($result2);
while($rows=mysql_fetch_assoc($result2))
{
$temp = $rows['username'];
$q3 = "SELECT time FROM DB WHERE stage='$stage' AND username='$temp' GROUP BY time ORDER BY time ASC";
$result3 = mysql_query($q3);
while($aaa = mysql_fetch_assoc($result3))
{
array_push($times, $aaa['time']);
array_push($userusernames, $rows['username']);
if($rows['username']==$username)
{
echo $aaa['time'];
}
break;
}
}
?>
may someone please help me figuring out how to do this
EDIT: I have been looking around on internet but I can't find what I'm looking for, I'm pretty sure there's the answer somewhere so maybe you can just help me reformulate my question and I could find the answer by myself. I'm pretty stuck due to my lack of english vocabulary...
thx in advance
You can archive the wanted result with only one query:
SELECT username, MIN(time) AS lowertime
FROM test_table
WHERE stage='$stage' AND username='$temp'
GROUP BY username
ORDER BY time

Hoping For Help in Writing This Query in PDO

I'm really new to PHP but I've been learning all I can, but I'm also aware that I have a lot to learn so go easy on me.
I'm currently working on a classifieds script and although the code is severely dated, It was a lot worse before I began cleaning it up and now I'm just trying to get the classifieds stable again, then I plan on going back and updating things to a more modern language (PDO) but for now I have NO IDEA on where to begin (and don't want to be reading for months while getting nowhere as I have been while learning HTML, CSS, PHP and JS)
The code below originally displayed the Title column from the table it was fetching the data from (tt_%s) but I have since modified the form which inserts the data into the DB so now there is no longer a "Title" column and in it's place there is now Year and Model from one table and Manufacturer from another table but this is where I get confused and am asking for help.
Presently this is what I am looking at; (Below the code I'll explain more)
<?php
echo "<div class='mostPopular'>";
echo "Popular<br>Listings";
$node = new sqlNode();
$node->table = "types";
$node->select = "ID";
$node->orderby = "ORDER BY rand()";
if(($typeRS = $mysql->select($node)) === false )
die('Unable to Retrieve Ad Type');
$sql = array();
$typeID = 0;
while( $adType = mysql_fetch_assoc($typeRS) ){
$typeID = sprintf("`tt_%s`", abs(intval($adType['ID'])));
$sql[] = sprintf("SELECT %s.Year, %s.Hits, %s.CategoryID, %s.ID, CONCAT('','%s') AS TypeID FROM %s WHERE (`ExpireDate` > NOW()) ",
$typeID,
$typeID,
$typeID,
$typeID,
intval($adType['ID']),
$typeID);
}
$sqlStr = #implode("union ",$sql);
$sqlStr .= " ORDER BY Hits DESC LIMIT 5";
if(($adRS = $mysql->exSql($sqlStr)) === false)
die('Unable to Retrieve Most Popular Ads');
while( $ad = mysql_fetch_assoc($adRS) ){
echo "<p>";
echo "<a href='detail.php?fatherID=".$ad['CategoryID']."&TypeID=".$ad['TypeID']."&ListingID=".$ad['ID']."'>";
echo $ad['Title'];
echo "</a>";
echo "</p>";
}
echo "</div>";
?>
For starters, I don't know what CONCAT('','%s') is all about, nor do I know what $sqlStr = #implode("union ",$sql); is all about.
In addition to these issues, considering that this code is outdated and I should be switching to PDO, I was hoping someone could show me exactly how to perform these queries with PDO as then I could learn by example and apply the same procedures to other queries throughout the site.
If anyone wouldn't mind conversing with me to the point where I can perform the same outcome with PDO I'd be most appreciative and I thank you all in advance while I eagerly await your replies.
BTW, I ask this after studying every PHP and MySql tutorial I can find for the past several months
Thanks
Although "Please rewrite this code to PDO" being too localized one, the real problem you have require different solution.
First of all, you need to fix your database architecture. It's terrible.
Premature optimization, being the root of all evil, depraved you from the right ways. There is no point in splitting your data into small chunks if you going to union them anyway.
You have to have one table for the ads.
It will make all this code obsolete, leaving only one regular query which can be run in one conventional PDO call.
Next, this code has been written by some sprintf() maniac, who made it overcomplicated out of nowhere. As a matter of fact, not a single sprintf() is really needed here.
$sql = array();
while( $row = mysql_fetch_assoc($typeRS) ){
$typeID = abs($row['ID']);
$sql[] = "SELECT Year, Hits, CategoryID, ID, '$typeID' AS TypeID
FROM tt_$typeID WHERE ExpireDate > NOW()";
}
$sqlStr = implode("union ",$sql)." ORDER BY Hits DESC LIMIT 5"
is enough.
But again, no need for this union query. Everything have to be performed via single ordinary query like this one
SELECT Year, Hits, CategoryID, ID, TypeID FROM ads ORDER BY Hits DESC LIMIT 5
which you no doubt will be able to run using whatever PDO example you have

How could I echo a random database field once a week using php and mySQL?

Google hasn't been much help sadly. I have some pseudo code below to give you an idea of what I'd like to achieve:
if ($time == one week) {
$result = mysql_query("SELECT * FROM table RANDOMLY,$connection");
echo $result[0];
}
I know I should be using mysqli, but I'm augumenting an existing (ageing) system. I'll be utilising mysqli in future, so if you could give me the solution using mysql that would be great!
I don't think it can be done with a single statement.
My best guess would be to use mysql_list_tables, select a random entry from that list and continue from there on.
Perhaps generating a random number between 1 and the value of SELECT Count(ID) from table. Then you have the index of the value you wish to output, you can simply run a SELECT statement for it; and output! :)
if ($time == one week) {
$result = mysql_query("SELECT * FROM table RANDOMLY,$connection");
echo $result[0];
}
Try this:
$weekNumber = date("W");
$result = mysqli_query("SELECT * FROM table RANDOMLY WHERE weeknumber = '\"$weekNumber\"', $connection");
echo $result[0];
}
Of course you’ll need a column in your table called weeknumber with 1 through 52 setup ahead of time.
As others pointed out you shouldn’t use mysql_* anything. I changed it to a mysqli_query.

php for loop query in magento

Hello all i am new but got so many helps from here. Thanks to all the people who helped.
Now i am facing a problem in magento e-commerce for making a loop query of top 10 point holders. Well i have made a separate database which contain the points .
my database is table : magentodatabase_points
Now here is total 3 colums -
1. ID
2. User_id
3. points
well now, here i would like to make a loop of top 10 members contain the highest points i have tried but failed so can anybody help me on that.
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$table = $resource->getTableName('database_points');
$query = 'SELECT user_id FROM ' . $table . ' ORDER BY points DESC LIMIT 10';
$results = $readConnection->fetchAll($query);
well but after that i have tried with php for loop but that is not supporting for magento. So can anybody know what will be the loop code for magento.
Well, one more help would be greatful for me how do i get magento customer names from the using the top results of user_id because i will get only the results not the names.
Anyways that is not that important because i hope i will solve it by my own.
So, please if anyone can help me on the loop query of top 10 point holders.
Thanks in advace
and sorry for my bad english
If your table name and fields exist then you can just add this below your code:
foreach ($results as $result) {
$user_id = $result['user_id'];
echo $user_id; // or do whatever you wanted to with the variable
}
You should consider using Magento's Models to do this instead. There's an excellent tutorial series from Alan Storm on MagentoCommerce's website: http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-5-magento-models-and-orm-basics
For the customer's names you can try this in your loop:
foreach ($results as $result) {
$user_id = $result['user_id'];
$customer = Mage::getModel('customer/customer')->load($user_id);
print_r($customer);
}
May be because your field name has uppercase for u of user_id correctd "User_id" and you are using lowercase in your query.
else your method is fine to work with magento
for gettting customer, if User_id u get from this result is a customer id then $customer_data = Mage::getModel('customer/customer')->load(User_Id); would give u all detail of customer. you can fetch name from this using $customer_data->getName() method

PHP: mysql_fetch_array() in a while-loop takes too long

I am creating an online calendar for a client using PHP/MySQL.
I initiated a <table> and <tr>, and after that have a while loop that creates a new <td> for each day, up to the max number of days in the month.
The line after the <td>, PHP searches a MySQL database for any events that occur on that day by comparing the value of $i (the counter) to the value of the formatted Unix timestamp within that row of the database. In order to increment the internal row counter ONLY when a match is made, I have made another while loop that fetches a new array for the result. It is significantly slowing down loading time.
Here's the code, shortened so you don't have to read the unnecessary stuff:
$qry = "SELECT * FROM events WHERE author=\"$author\"";
$result = mysql_query($qry) or die(mysql_error());
$row = mysql_fetch_array($result);
for ($i = 1; $i <= $max_days; $i++) {
echo "<td class=\"day\">";
$rowunixdate_number = date("j", $row['unixdate']);
if ($rowunixdate_number == $i) {
while ($rowunixdate_number == $i) {
$rowtitle = $row['title'];
echo $rowtitle;
$row = mysql_fetch_array($result);
$rowunixdate_number = date("j", $row['unixdate']);
}
}
echo "</td>";
if (newWeek($day_count)) {
echo "</tr><tr>";
}
$day_count++;
}
The slowness is most likely because you're doing 31 queries, instead of 1 query before you build the HTML table, as Nael El Shawwa pointed out -- if you're trying to get all the upcoming events for a given author for the month, you should select that in a single SQL query, and then iterate over the result set to actually generate the table. E.g.
$sql = "SELECT * FROM events WHERE author = '$author' ORDER BY xdate ASC";
$rsEvents = mysql_query($sql);
echo("<table><tr>");
while ($Event = mysql_fetch_array($rsEvents)) {
echo("<td>[event info in $Event goes here]</td>");
}
echo("</tr></table>");
Furthermore, it's usually a bad idea to intermix SQL queries and HTML generation. Your external data should be gathered in one place, the output data generated in another. My example cuts it close, by having the SQL immediately before the HTML generation, but that's still better than having an HTML block contain SQL queries right in the middle of it.
Have you run that query in a MySQL tool to see how long it takes?
Do you have an index on the author column?
There's nothing wrong with your PHP. I suspect the query is the problem and no index is the cause.
aside from their comments above, also try to optimize your sql query since this is one of the most common source of performance issues.
let say you have a news article table with Title, Date, Blurb, Content fields and you only need to fetch the title and display them as a list on the html page,
to do a "SELECT * FROM TABLE"
means that you are requiring the db server to fetch all the field data when doing the loop (including the Blurb and Content which you are not going to use).
if you optimize that to something like:
"SELECT Title, Date FROM TABLE" would fetch only the necessary data and would be more efficient in terms of server utilization.
i hope this helps you.
Is 'author' an id? or a string? Either way an index would help you.
The query is not slow, its the for loop thats causing the problem. Its not complete; missing the $i loop condition and increment. Or is this a typo?
Why don't you just order the query by the date?
SELECT * FROM events WHERE author=? ORDER BY unixdate ASC
and have a variable to store the current date you are on to have any logic required to group events by date in your table ex. giving all event rows with the same date the same color.
Assuming the date is a unix timestamp that does not account for the event's time then you can do this:
$currentDate = 0;
while(mysql_fetch_array($result)){
if($currentDate == $row['unixdate']){
//code to present an event that is on the same day as the previous event
}else{
//code to present an even on a date that is past the previous event
//you are sorting events by date in the query
}
//update currentDate for next iteration
$currentDate = $row['unixdate'];
}
if unixdate includes the event time, then you need to add some logic to just extract the unix date timestmap excluding the hours and minutes.
Hope that helps

Categories