How to properly count a query in pdo - php

I am trying to dynamically load more posts into my system
This is my code...
$stmt = "
SELECT * FROM `acmPosting`
WHERE (`sender`='$thisID' AND `postType`='a')
OR (`recip`='$thisID' AND `sender`='$userID' AND `postType`='a')
OR (`sender` IN ($friendsArray) AND `recip`='$thisID' AND `postType`='a')
ORDER BY `timeSent` DESC LIMIT $startlimit,10";
if($stmtCount = $conn->query($stmt)){
if($stmtCount->fetchColumn() > 0){
$result = acmPosts($conn, $site, $userID, $stmt);
$jsonArray['a'] = $result;
$jsonArray['b'] = 'go';
}else{
$jsonArray['a'] = '<div class="thisOutput" style="padding:12px;">There are no more posts</div>';
$jsonArray['b'] = 'stop';
}
}
Everything works fine until it gets to the last set of posts AKA if the LIMIT is 100,10 but there are 105 posts in the call it won't call any to the fetchColumn().
I hope this question makes sense. Thanks in advance for any help you can give.
EDIT
How can I determine when I have reached the LIMIT and act accordingly

Your description is not very precise but maybe this is what you are looking for:
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

Related

send php text output to client browser and run rest in server side

I have a straight forward php script thats performs one mysql query. Based on this i then run about 10 more mysql queries. I then return the result via echo to the client.
But to save time for the client I can echo the result out THEN run the remaining 10 mysql queries server side so the client gets a quicker response.
can this be done? or does the client have to wait for the entire php script to executed server side before getting a text response?
Heres my code:
$dbc = mysql_connect("$db_host","$db_username","$db_pass");
if (!$dbc) { die('SERVER ERROR PLEASE CONTACT US FOR MORE INFORMATION!'); }
mysql_select_db("$db_name", $dbc);
$sql = "SELECT * FROM `ads` WHERE (`status` LIKE 'active%' OR `status` LIKE 'featured%') ORDER BY `clicks` DESC LIMIT 10;";
$result = mysql_query($sql,$dbc);
$totalads=mysql_num_rows($result);
$str="";
while ($row = mysql_fetch_assoc($result))
{
$str .= $row["banner"] . "][". $row["link"] . "<BR>";
//the code below is used to update stats but can be run after output to client
$views=$row["views"]; $targetviews=$row["targetviews"];
if (intval($views)+1 >= intval($targetviews))
{
$sql1 = "UPDATE `ads` SET `views` = `views` + 1 , `status` = 'expired' WHERE `ID`=".$row["id"].";";
}
else
{
$sql1 = "UPDATE `ads` SET `views` = `views` + 1 WHERE `ID`=".$row["id"].";";
}
$result2 = mysql_query($sql1,$dbc);
mysql_free_result($result2);
}
$str=rtrim($str,"<BR>");
mysql_free_result($result);
mysql_close($dbc);
die ($str);
What you want is completely possible with the use of ob_start(); Take a look here... http://www.php.net/ob_start and that will give you an idea. I don't know what your code looks like but as an example you could do something like this...
<?php
ob_start();
$query = "SELECT * FROM users";
$results = DB::get()->query($sql);
echo "<pre>";
print_r($results);
echo "</pre>";
$content = ob_get_content();
#ob_end_clean();
echo $contents;
//continue processing
obviously you need to tailor that for your specific script but that is an idea to get you where you need to go
~~~~~~~~~EDIT~~~~~~~~~~~~~
OK so using your code and comments here you go.
First, yes you can do more than one while loop with the results, though you shouldn't as that is bad coding practices.
That being said here is what I would do...
ob_start();
$level = ob_get_level();
$dbc = mysql_connect("$db_host","$db_username","$db_pass");
if (!$dbc) {
die('SERVER ERROR PLEASE CONTACT US FOR MORE INFORMATION!');
}
mysql_select_db("$db_name", $dbc);
$sql = "SELECT * FROM `ads`
WHERE (`status` LIKE 'active%' OR `status` LIKE 'featured%')
ORDER BY `clicks` DESC LIMIT 10;";
$result = mysql_query($sql,$dbc);
$totalads=mysql_num_rows($result);
$str="";
while ($row = mysql_fetch_assoc($result)) {
$str .= $row["banner"] . "][". $row["link"] . "<br />";
$views[] = $row['views'];
$target_views[] = $row['targetviews'];
$ids[] = $row['id'];
}
echo $str;
$content = ob_get_contents();
if(ob_get_level() > $level + 1) {
ob_end_flush();
}
echo $content;
#ob_end_clean();
for($i = 0, $len = count($views); $i < $len; $i++) {
if((intval($views[$i] + 1) >= intval($target_views[$i]) {
$sql = "UPDATE `ads`
SET `views` = `views` + 1 ,
`status` = 'expired'
WHERE `ID`=".$ids[$i].";";
} else {
$sql = "UPDATE `ads`
SET `views` = `views` + 1
WHERE `ID`=".$ids[$i].";";
}
$result = mysql_query($sql);
mysql_free_result($result);
}
//I don't know what this stuff here is for except for the close line, but it's her if you want it
$str=rtrim($str,"<BR>");
mysql_free_result($result);
mysql_close($dbc);
die ($str);
?>
You no longer need the die statement there, but I left it incase you wanted it for something else. That should do what you need, check my stuff for typos though I just kinda pushed it out real quick for ya. please don't forget to mark that little check box for the right answer if it works, or leads you to the solution. Thanks man
You can as example run the first query.
Then return data to client.
From client run the 2°nd ajax call that will call a php page with the second script, etc....
Maybe the 2°nd ajax can call a php page that will launch the other 9 queries and then finally get the last reply needed.
generate output string
flush it
and do less of code
http://www.php.net/manual/en/function.flush.php
I'm guessing that you're creating a website. So, you can run the 10 others queries in a AJAX call, launch at the loading of the page.
Your architecture will be:
main.php which run 1 query and return the HTML page with data of the query ;
long_query.php which run the other queries in background ;
page.html which present first query results and with some javascript called the long_query.php script to get the result of other queries.
You need for this to write some javascript which will run an AJAX call, get the data and modify the current HTML page to add the data returned. If you're already using jQuery on your project, you can use jQuery.ajax() function.

creating a top list in PHP

So my brain is having trouble functionning this morning and I can't figure out how to create a Top list.
I have my query like so
$moyennepisode = $conn->prepare('SELECT * FROM show_moyenne, shows WHERE shows.id = show_moyenne.show_id ORDER BY moyenne DESC LIMIT 100');
$moyennepisode->execute();
while ($show = $moyennepisode->fetch()) {
somecode }
Which is all fine but I simply want to output the position so I tried a for loop but I can't seem to figure out where to place it. I tried an associate array but I failed at that, too.
Can anyone recommend how to do that ? And if there might be a way to do have the position from mmysql instead of php ?
Any help appreciated. Thanks!
$position = 1;
while ($show = $moyennepisode->fetch()) {
Output $position;
$position++;
somecode;
}

Redbean ORDER BY

Quick Question!
In redbean, seeing as you can order content like this with the findAll:
$all = R::findAll('needle',' ORDER BY title LIMIT 2 ');
It is possible to order a load function? I have tried but it doesn't work and the previous one does. This is what I tried:
$vals['events'][] = R::load('events', $eventid, ' ORDER BY title LIMIT 2 ');
Thanks!
If you are going to update the events then loading the event is perfectly fine, if you just want to get the event information i would say use find which is better.
<?php
$events = R::findAll('needle');
foreach($events as $e_info){
$eventid = $e_info->id;
$event_info = R::findOne('event_info', ' id = ?' , array($eventid));
//Do whatever you want with the data.
//You can also update it like
// $event_info->updated_at = R::isoDateTime();
//R::store($event_info);
}
?>
I hope this helps.

PHP link only passing part of a mysql result

OK i have a php link which is made up of several variables
<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>
The whole code is really long as it has a lot of pagination, so i will just include the basic query and the loop part.
$query1 = "SELECT Distinct model_type from $tableName where manufacturer='$manufacturer' AND fuel='$fuel_type' LIMIT $start, $limit";
$result = mysql_query($query1);
And then the bottom part where i get and show the results.
$count = 0;
$max = 2;
while($row = mysql_fetch_array($result))
{
$model_type = $row['model_type'];
$count++;
echo '<td class="manu"><div align="center">'.'<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>'.'</div></td>';
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo '</tr><tr>';
}
}
now this works fine except when i take the mode type variable from the database it shows as 1 series, however when it is passed in this link it only gets the 1 and doesn't pick up the series.
Thanks
try to pass it like:
'.urlencode($model_type).'
Try To access it on next page with urldecode($_REQUEST['$model_type'])
I am not shure but you probably have a missing encoding Problem.
try this:
'.$model_type.'
Its url_encoding the values so your url doesnt get broken by ',",spaces and so on.
additional Hint:
Enclose your URL with " or ' so you do not get problems at the end.

PHP List Menu Boxes - Best way to do the cycle?

This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>

Categories