Im having problems with a method in a class file:
public static function getPageLeft($pid)
{
self::_dbConnect();
echo "now " .$pid;
$pid--;
echo " after ". $pid;
$data = mysql_query("SELECT id FROM evening_pages WHERE id='".$pid."'") or die(mysql_error());
$rows = mysql_num_rows($data);
if($rows == 1){
echo " in ";
return $data;
}elseif($pid != self::getMinPage()){
self::getPageLeft($pid);
echo " Current: " . $pid . " min: " .self::getMinPage();
}
}
I have the echos in there for debug only, and im getting:
now 22 after 21now 21 after 20 Current: 21 min: 1
This code is to find the next page left in a database driven CMS in case the client deletes a row from the database, it finds the next lower value.
So page id is 22 that your on, looks for id 21 in database, if its not there it should return 0 for the rows and move on and try again but on id 20, but there IS an entry for id = 20.
Anyone spot any issues with the code?
Also getting this error when it tries to find a page which doesnt exist before the current page, eg on page 22 but there is no ID for 21:
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/prelas/public_html/index.php on line 37
the code there is (line 37 is while):
$getPageLeft = sql::getPageLeft($pid);
while($row = mysql_fetch_array($getPageLeft)){
$pageleft = $row['id'];
}
Many thanks.
Just a quick edit: " in " never gets echoed, but yet when there is no deleted pages the navigation works fine.
Further edit: The code which makes use of the code (by like 37):
$navigation = '<div id="direction">
<span class="inNav"> << < </span><span class="black">•</span><span class="inNav"> > >></span>
</div>'
So you can see it uses $pageleft in there however when its dealing with blank pages the value is nothing (empty).
why don’t you write the SQL statement to get the next lower ID? For example:
SELECT `id`
FROM `evening_pages`
WHERE `id` < ?
ORDER BY `id` DESC
LIMIT 1
Or:
SELECT MAX(`id`)
FROM `evening_pages`
WHERE `id` < ?
That way, you only have to check if something has been returned by the query. Less code, less overhead for database requests.
The mysql extension is being phased out. Learn about using mysqli or PDO, and read up on the dangers of SQL injection.
Related
I am working on a ' Show Online user' script where the script show everybody who is online.
Now i want to remve the entry which matches the session user name i.e "if (Online user = Session User name ) then do not display it , just like on facebook.com chat where your friends id is shown and not your own Id
my code is as follows :
<?php
mysql_connect("localhost","root","12345");
mysql_select_db("accounts");
$user = $_SESSION['user_name'];
$result = mysql_query("SELECT * FROM online * WHERE ($chat<>$user)");
while($row=mysql_fetch_array($result)) {
$chat=$row["emp_name"];
$chlk = ("<a href=javascript:void(0) onclick=javascript:chatWith('$chat')>$chat</a>");
$chs = ("<a>$chat</a>");
if ($chat <> $user) {
echo $chlk;
}
else {
echo $chs;
}
echo $chlk;
}
?>
I am getting the following error :
Notice: Undefined variable: chat in localhost/accounts/removeuser.php on line 7
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given localhost/accounts/removeuser.php on line 9
Any help is highly appreciated.
Correction in query.
"SELECT * FROM online WHERE ($chat<>$user)"
OR
Replace $chat in query with your table field name.
there is extra * before WHERE that is invalid.
and $chat is not defined in query.
<> is not PHP as far as I know. You need to use !==.
(and probably read up on some PHP basics...)
So I'm having a very strange issue and am not quite sure what to think about it...
I have a standard database query doing a select on a table. It returns a resource, num_rows = 101, and it will fetch rows up to row 42 at which point it simply stops all script execution, no errors, not timing out (takes less than a sec to get the 42 rows) ... I can't provide a link but here's the code in question...
$select2 = "SELECT * FROM `$dbname`.`$file" . "_settings` WHERE `weight` <> 0 ORDER BY `count` ASC";
$result = mysql_query($select2);
$lpcnt = 0;
$numrows = mysql_num_rows($result);
while ($display = mysql_fetch_array($result, MYSQL_ASSOC)){
/* This will print out 42 times */
echo '<pre>In The LOOP, row('.$lpcnt.'):<br>NumRows: '.$numrows.'<br>';
print_r($display);
echo '</pre><br/>';
$domRows[] = $display;
$aTotal[] = $display['count'];
$aTotWeight[] = $display['weight'];
//debug vars
$d['url'] = $display['url'];
$d['total'] = $total;
$d['count'] = $display['count'];
$d['weight'] = $display['weight'];
$dbug['domRows'][] = $d;
$lpcnt++;
}
/* Never Reaches this */
echo '<pre>';die(print_r('Loop Finished'));
At a loss as to what's causing the failure midway through the results loop...
also..I know, I know...myql_ is depreciated, but's that's what I have to work with!
Thanks in advance for any light anyone can shed...this is really hurting the site!
EDIT: also this doesn't break all the time, so far it seems to be related somehow to the number of results...for example, if I run through a result set that has 39 rows, it will proccess all of them...and it's consitently failing at 42 rows... on my tables that have 100+ records
EDIT FINAL: Ok figured it out! Turns out we had our memory limit to low, so it was trying to allocate an illegal amount of memory! So we upped it and now it works! Also I had my error reporting in a spot where it was being conditionally turned back off by other code...that's why I wasn't seeing errors! Duh... anyway, thanks for the stabs, to those that responded Merry x-mas and all that jazz...
I'm running a query to get the total sum of some hours from a database table to show in a PDF file but for some strange reason it won't echo 0 (zero).
$query = mysql_query("SELECT id, SUM(hours_night), SUM(hours_days) FROM table WHERE invoiceID='".mysql_real_escape_string($invoiceID)."'") or die(mysql_error());
$result = mysql_num_rows($query);
$totalhours_night = 0;
while ($fetch = mysql_fetch_assoc($query)) {
$totalhours_night += $fetch['SUM(hours_night)'];
}
$html_output = "Some html and tables markup... " . $totalhours_night . "";
The output of the html works fine, thats not the problem.. but the problem is it won't output 0 (zero) for some reason. If the hour result is actualy something like 1 or 5 or whatever it outputs the totalhours fine, but i need it to output 0 if there are no hours.
Because it looks strange to ouput nothing if there are no hours, i need to display a 0 zero since this looks more good.
BTW, if i for example put number_format($totalhours_night, 2); it does display 0.00, but i need it to be just 0.
Three things:
Your SQL query is wrong, you can't display id and SUM(..) unless you use GROUP BY id (Which kid of loses the idea if id is unique)
If you use SUM(..) give it an alias like SUM(..) AS alias1, and later in the PHP refer to alias1.
If this is not the reason, try var_dump($fetch['alias1']); and look at what you really get back. (And post your findings here so we can give you further help)
Treat integer as string like this-
echo (string)$totalhours_night;
As i am trying to increment the counter to plus 1 every time when the user clicks on the image. I have written the following code but it says some error "Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\tkboom\includes\core.php on line 72". Can anyone look into this where i made a mistake..
Actually i have created 2 php files one for incrementing the counter and one for displaying the counter. In core.php file i have written the function and for displaying the count i have created a file called view.php
core.php
function GenerateCount($id, $playCount) {
global $setting;
$counter_query = "SELECT hits FROM ava_games WHERE id=".$_GET['id']."";
$counter_res = mysql_query($counter_query);
while($counter_row = mysql_fetch_array($counter_res)){
$counter = $counter_row['hits'] + 1;
$update_counter_query = "UPDATE ava_games SET hits=".$counter." WHERE id=".$_GET['id']."";
$playCount = mysql_query($update_counter_query);
$playCount = $row['hits'];
}
return $playCount;
// Get count END
}
view.php
<?php
$sql = mysql_query("SELECT * FROM ava_games WHERE published=1 ORDER BY id desc LIMIT 30");
while($row = mysql_fetch_array($sql)) {
$url = GameUrl($row['id'], $row['seo_url'], $row['category_id']);
$name = shortenStr($row['name'], $template['module_max_chars']);
$playRt = GenerateRating($row['rating'], $row['homepage']);
$playCt = GenerateCount($row['id'], $row['hits']);
if ($setting['module_thumbs'] == 1) {
$image_url = GameImageUrl($row['image'], $row['import'], $row['url']);
$image = '<div class="homepage_game"><div class="home_game_image"><img src="'.$image_url.'" width= 180 height= 135/></div><div class="home_game_info"><div class="home_game_head">'.$name.'</div></div><div class="home_game_options"><img class="home_game_options_icon" src="'.$setting['site_url'].'/templates/hightek/images/joystick-icon.png" /> '.$playRt.' <b>|</b> '.$playCt.' plays </div></div>';
echo $image;
}
}
?>
That most likely means that there's an error in the sql statement. You can get more information about the error via mysql_error().
In its simplest form:
$counter_res = mysql_query($counter_query) or die(mysql_error());
(edit: ...simplest form, but with this approach you don't give the application a chance to react to the problem, "die" as in "dead". And mysql_error() can leak too much information to a user of your webservice/website, see https://www.owasp.org/index.php/Top_10_2007-Information_Leakage_and_Improper_Error_Handling)
Your code is also prone to
sql injections, because the $_GET parameter is put into the statement without sanitizing it first
race conditions because you have a compound operation consisting of one SELECT and one UPDATE without any locking mechanism.
This is because you get the error in your SQL query.
I'd change it a little bit:
$counter_query = 'SELECT hits FROM ava_games WHERE id = ' . (int)$_GET['id'];
to make sure you always compare id against integer value.
After all, this query does not look good. First point: why are you using two queries to increment a value? UPDATE ava_games SET hits=hits+1 WHERE id=".$_GET['id'].""should do this in one step. Second point: have you heard about SQL injections? Escape or cast $_GET['id'] to avoid surprises ;)
Convert the value in int first like that:
function GenerateCount($playCount) {
global $setting;
$counter_query = "SELECT hits FROM ava_games WHERE id=".$_GET['id']."";
$counter_res = mysql_query($counter_query);
while($counter_row = mysql_fetch_array($counter_res)){
$counter = intval($counter_row['hits']) + 1;
$update_counter_query = "UPDATE ava_games SET hits=".$counter." WHERE id=".$_GET['id']."";
$playCount = mysql_query($update_counter_query);
$playCount = $row['hits'];
}
return $playCount;
// Get count END
}
and check link:
Convert into int
If mysql_query returns a Boolean, your query failed.
Presuming id is the primary key, you can use the following function to update on a database level which will prevent race conditions:
function GenerateCount($playCount) {
global $setting;
$update_counter_query = "UPDATE ava_games SET hits=hits + 1 WHERE id=".intval($_GET['id'])."";
mysql_query($update_counter_query) or die(mysql_error());
$counter_query = "SELECT hits FROM ava_games WHERE id=".intval($_GET['id'])." LIMIT 1";
list($playCount) = mysql_fetch_row(mysql_query($counter_query));
return $playCount;
// Get count END
}
also note the intval() around the $_GET variable to prevent SQL injection
Can anybody tell me what's wrong with the following code ---
for($i=0; $i<count($strnamearray); $i++){
echo $strnamearray[$i]."<br />";
$cordcquery = "SELECT `lat` , `lng` FROM `traffic` WHERE `strname` = '{$strnamearray[$i]}' LIMIT 0 , 30;";
$cordresult = mysql_query($cordcquery);
if (!$cordresult)
{
die('Invalid strncquery: ' . mysql_error());
}
while($cordrow = #mysql_fetch_assoc($cordresult)){
echo $cordrow['lng'].",".$cordrow['lat'];
echo "<br />";
}
}
Here $strnamearray[$i] is an array which contains some name. there is no error showed after executing this php code. But the problem is i am not getting my desired output...
This is a shot in the dark here with out some more information but two things.
echo $cordcquery just to make sure the sql looks right and you can execute it directly in MYSQL. From what I can tell it should but without knowing whats in the variables I'm not sure.
Instead of LIMIT 0, 30 use just LIMIT 30. Should be the same thing but I have seen some funkiness depending on what versions of php and mysql you are using with passing LIMIT offset, row count. From what I can remember it would take the offset and not parse the row count and therefore would not return any information.
Let me know if this helps.