How to select an id bigger then - php

I'm working on a news system for a website. I used the news system from this tutorial: http://pixelcode.co.uk/tutorials/php/mysql-news-system/
So to display the news I use this line of code:
if(!$_GET['id'])
{
$query = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($output = mysql_fetch_assoc($query))
{
echo '<div id="nieuws">';
echo '<a href="?id='.$output['id'].'" id="link">';
echo '<h1>'.$output['title'].'</h1>';
echo '<span id="date">'.date('d-m-y', $output['date']).'</span><br / >';
echo $output['shortnews'].'<br / >';
echo '</a>';
echo '</div>';
}
}
else
{
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM news WHERE id='$id'");
$output = mysql_fetch_assoc($query);
?>
<form method="post" action="?id=<? echo $output['id']; ?>">
<h1><? echo $output['title']; ?></h1>
<? echo '<span id="date">'.date('d-m-y', $output['date']).'</span><br / >' ?>
<? echo $output['news']; ?>
</form>
<?php } ?>
I can do: if(!$_GET['id'] = 6) but I can't do this: if(!$_GET['id'] > 6). What's the problem? Or is there another code for bigger then an id?
Thanks for replying, MARCH

Operator precedence: ! binds tighter than ==, so you're effectively doing
(not($_GET) == 6)
That's why there's != for inequality tests.
If you'd used proper bracketing, e.g
(!($_GET['id'] == 6))
then you'd be doing
not(id == 6)
and get your expected results, because that's logically/functionally equivalent to id != 6
And note that you're vulnerable to sql injection attacks and are using an obsolete/deprecated DB interface.

Use isset():
if (isset($_GET['id'])) ...
Or, what I like to do:
// Get all possible arguments:
$id = #$_GET['id']; // The # prevents an error message
$foo = #$_GET['foo']; // foo means ... (explain the args)
...
// Later, as needed:
if (isset($id)) ...

Related

MySQL GROUP by or using PHP?

I have an issue that seems to be quiet easy but I just would like to ask how you would solve it:
In a MySQL-table there is the following structure:
provider artist
a 1
a 2
a 3
b 4
Now it is necessary to echo a list in HTML like:
provider a
1
2
3
provider b
4
I stuck at the point where I would like to group the results and echo them out with for-each and while loop.
The main idea is quiet simple like:
<?php $query = mysqli->query("SELECT * FROM `table` GROUP by provider");
foreach GROUP {?>
echo some styling HTML-code for each group of headline;
<?php while ($data= $query->fetch_assoc()){?>
echo some styling HTML-code for each list-item;
<?php};?>
Thanks in advance.
UPDATE:
Thanks for answering.
The solution fro RiggsFolly seems to work fine. There is just a small problem with the HTML. There is a surrounding div-tag that wont be closed when adding the HTML code in that line:
echo 'provider '. $data->provider;
The problem is that the while loop needs to be in the div. The closing div-tag is missing for every
if ( $current_provider != $data->provider ) {
Here is the original HTML-code:
<?php
$service = $db->query("SELECT * FROM `system` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $service->fetch_object()) {
if ( $current_provider != $data->provider ) {// new provider?>
<div class="service">
<p class="lower">
<?php echo $data->provider;?>
</p>
<?php
$current_provider = $data->provider;
}?>
<a href='?artist=<?php echo $data->artist;?>'><?php echo "/".$data->artist;?</a><br/>
<?php };?>
</div><!--service -->
The list-items will be shown nicely. But when looking into the Source code you can see that the closing div-tag is missing. Thanks
Kind regards.
It would seem simpler to not use a GROUP BY especially as it will not provide you with the data that you want. So instead just select them all and sort them by provider and maybe artist as a sub sort like so
<?php
$result = $mysqli->query("SELECT * FROM `table` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $result->fetch_object()){
if ( $current_provider != $data->provider ) {
// new provider
echo 'provider '. $data->provider;
$current_provider = $data->provider;
}
echo $data->artist;
}
?>
AFTER UPDATE:
<?php
$service = $db->query("SELECT * FROM `system` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $service->fetch_object()) {
if ( $current_provider != $data->provider ) {
if ( $current_provider !== NULL ) {
echo '</div>';
}
echo '<div class="service">';
echo '<p class="lower">' . $data->provider . '</p>';
$current_provider = $data->provider;
}
echo '<a href="?artist=' . $data->artist '">' .
$data->artist . '</a><br/>';
}
echo '</div>';
How about that.
<?php $query = mysqli->query("SELECT * FROM `table`");
$current_group = array();
while ($data= $query->fetch_assoc()){
if(in_array($data['provider'],$current_group)){
echo "<h1>New Group" . $data['provider'] ."</h1>";
$current_group[] = $data['provider']
}
echo $data['artist'] . "<br/>";
}

if mysql result does not exist echo?

Hi ive got a basic likes system on my site. Basically once the user clicks like, this sets user_id-has_liked to 1 from 0.
if their user_id_has_liked is set to 0 it displays the like link, if its set to 1 it displays unlike. however i want to add another condition that says if result is not in mysql then echo out the like link.
can someone show me where and what i would add to make this happen please.
<div class="profile_likes">
<?php
$user_like_set = user_like_status();
while ($like = mysql_fetch_array($user_like_set))
if ($like['user_id_has_liked'] == '0') { ?>
Like | <?
$count_likes_set = count_likes();
while ($likes = mysql_fetch_array($count_likes_set)) {
echo "". $likes['likes'] ." People Like ".$profile[2]."";
//$check_new_duos_set = check_new_escort_duos(); while ($newd = mysql_fetch_array($check_new_duos_set)) {
?>
<? } }?>
<?php
$user_like_set = user_like_status();
while ($like = mysql_fetch_array($user_like_set))
if ($like['user_id_has_liked'] == '1') { ?>
Unlike | <?
$count_likes_set = count_likes();
while ($likes = mysql_fetch_array($count_likes_set)) {
echo "". $likes['likes'] ." People Like ".$profile[2]."";
//$check_new_duos_set = check_new_escort_duos(); while ($newd = mysql_fetch_array($check_new_duos_set)) {
?>
<? } }?>
</div>
You should give a try to mysql_num_rows. It will give you number of rows present in the record set.
Besides that, a word of caution, the APIs you are using are deprecated. Look for suggested alternative on mysql site.
Try to strive for consistency in your usage of the echo/print functions and emulating them by terminating the php tag, your code will become much clearer.
<?php
function printLikeLink($likeLink){
echo "<a href='{$likeLink}'>Like this profile</a>";
}
$user_like_set = user_like_status();
if ($like = mysql_fetch_array($user_like_set)){
if ($like['user_id_has_liked'] == '1') {
echo "Unlike|";
$count_likes_set = count_likes();
while ($likes = mysql_fetch_array($count_likes_set)) {
echo "". $likes['likes'] ." People Like ".$profile[2]."";
//$check_new_duos_set = check_new_escort_duos(); while ($newd = mysql_fetch_array($check_new_duos_set)) {
}
}else printLikeLink("like_profile.php?to={$profile_id}");
}else printLikeLink("like_profile.php?to={$profile_id}"); // Edit this link.
?>
try this i just made one change that your user_like_status(); should return true or false
<div class="profile_likes">
<?php
$user_like_set = user_like_status();//should return true or false
if ($user_like_set == false){
$what = "Like";
}else{
$what = "Unlike";
}?>
<?php echo $what ;?> |
<?php
$count_likes_set = count_likes();
while ($likes = mysql_fetch_array($count_likes_set)) {
echo "". $likes['likes'] ." People Like ".$profile[2]."";
}
?>
</div>

A variable won't display

I have code that runs a query on the database and returns some data and displays it.
All very simple. I've tested the query and it work's perfectly.
So somewhere between the query being executed and me displaying the data, it's not working.
$q = "SELECT u.username, r.position, r.score, r.winner, t.team FROM ".TBL_FOOT_TOUR_ROUNDS." r
LEFT JOIN ".TBL_USERS." u ON u.id = r.winner
LEFT JOIN ".TBL_FOOT_TOUR_PLAYERS." pl ON pl.userid = r.winner
LEFT JOIN ".TBL_FOOT_TEAMS." t ON t.id = pl.team
WHERE r.tourid = '$tour_id' && r.round = '$i' ORDER BY r.position";
$result = $database->query($q);
?>
<div class="vertical-holder">
<div class="vertical-header"><p><?php echo $roundName[$i]; ?></p></div>
<?php
while($row=mysql_fetch_assoc($result)){
extract($row);
if($k&1){
?>
<div class="horizontal-holder<?php echo $j; ?>">
<div class="white-holder">
<div class="player-holder">
<?php
if($winner == 0){
echo "<p>TBC</p>";
}
else{
echo "<p><a href='/profile.php?id=$winner'>$username</a><br />$team</p>";
}
?>
</div>
<div class="score-holder">
<?php
if($score == NULL){
echo "<p>-</p>";
}
else{
echo "<p>$score</p>";
}
?>
</div>
</div>
<?php
}
That's the snippet of code that's (what I believe to be) relevant.
The score is showing as '-' all the time even when a score is present.
The rest of the returned data shows no problem.
Can anyone see why the score variable isn't showing?
Thanks
<?php
if($score == NULL){
echo "<p>-</p>";
} else {
echo "<p>$score</p>";
}
?>
you got it wrong. if the value in the database is null, $score will not be null, it will be the string "null". so try
<?php
if(strtoupper($score) === "NULL"){
echo "<p>-</p>";
} else {
echo "<p>$score</p>";
}
?>
:)
alternatively you can create some utility function that changes a variable:
function nullify(&$data) {
if(strtoupper($data) === "NULL") {
$data = NULL;
}
}
and then call it like this:
nullify($score);
if $score should be set to null, it will be null after the call. then you can keep your logic the way it is ^^
Not sure what $score contains, but it seems to me that you could write your test like:
if($score < -1){ // or $score <= -1
echo "<p>-</p>";
}
else{
echo "<p>$score</p>";
}

Reduce number of MySQL Queries and Output Data in Correct Order

My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.

php and mysql not showing data, not entering foreach loop

I am having trouble with modifying a php application to have pagination. My error seems to be with my logic, and I am not clear exactly what I am doing incorrectly. I have had before, but am not currently getting errors that mysql_num_rows() not valid result resource
and that invalid arguments were supplied to foreach. I think there is a problem in my logic which is stopping the results from mysql from being returned.
All my "test" echos are output except testing while loop. A page is generated with the name of the query and the word auctions, and first and previous links, but not the next and last links. I would be grateful if a more efficient way of generating links for the rows in my table could be pointed out, instead of making a link per cell. Is it possible to have a continuous link for several items?
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$query ='';
if (isset($_GET["query"])) {
$query = $_GET["query"];
}
if (isset($_GET["pg"]))
{
$pg = $_GET["pg"];
}
else $pg = 1;
$con = mysql_connect("localhost","user","password");
echo "test connection<p>";
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("database",$con);
if($cmd=="GetRecordSet"){
echo "test in loop<p>";
$table = 'SaleS';
$page_rows = 10;
$max = 'limit ' .($pg - 1) * $page_rows .',' .$page_rows;
$rows = getRowsByProductSearch($query, $table, $max);
echo "test after query<p>";
$numRows = mysql_num_rows($rows);
$last = ceil($rows/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
echo 'html stuff <p>';
foreach ($rows as $row) {
echo "test foreach <p>";
$pk = $row['Product_NO'];
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>'.$row['Product_NAME'].'</td>' . "\n";
echo '</tr>' . "\n";
}
if ($pg == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pg=1'> <<-First</a> ";
echo " ";
$previous = $pg-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$previous'> <-Previous</a> ";
}
echo "---------------------------";
if ($pg == $last) {
} else {
$next = $pg+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$last'>Last ->></a> ";
}
echo "</table>\n";
}
echo "</div>";
function getRowsByProductSearch($searchString, $table, $max) {
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT Product_NO, USERNAME, ACCESSSTARTS, Product_NAME, date_format(mycolumn, '%d %m %Y') as shortDate FROM {$table} WHERE upper(Product_NAME) LIKE '%" . $searchString . "%'" . $max);
if($result === false) {
echo mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
echo "test while <p>";
$rows[] = $row;
}
return $rows;
mysql_free_result($result);
}
edit: I have printed out the mysql error of which there was none. However 8 "test whiles" are printed out, from a database with over 100 records. The foreach loop is never entereded, and I am unsure why.
The problem (or at least one of them) is in the code that reads:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = mysql_num_rows($rows);
The $numRows variable is not a MySQL resultset, it is just a normal array returned by getRowsByProductSearch.
Change the code to read:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = count($rows);
Then it should at least find some results for you.
Good luck, James
Hi there,
The next problem is with the line that reads:
$last = ceil($rows/$page_rows);
It should be changed to read:
$last = ceil($numRows / $page_rows);
Would recommend adding the following lines to the start of you script at least while debugging:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
As that would have thrown up a fatal error and saved you a whole lot of time.
if (!(isset($pg))) {
$pg = 1;
}
How is $pg going to get set? You don't appear to be reading it from $_GET. If you're relying on register_globals: don't do that! Try to read it from $_GET and parse it to a positive integer, falling back to '1' if that fails.
<a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a>
You appear to be losing the other parameters your page needs, 'query' and 'cmd'.
In general I'm finding it very difficult to read your code, especially the indentation-free use of echo(). Also you have untold HTML/script-injection vulnerabilities every time you "...$template..." or .concatenate a string into HTML without htmlspecialchars()ing it.
PHP is a templating language: use it, don't fight it! For example:
<?php
// Define this to allow us to output HTML-escaped strings painlessly
//
function h($s) {
echo(htmlspecialchars($s), ENT_QUOTES);
}
// Get path to self with parameters other than page number
//
$myurl= $_SERVER['PHP_SELF'].'?cmd='.urlencode($cmd).'&query='.urlencode($query);
?>
<div id="tableheader" class="tableheader">
<h1><?php h($query) ?> Sales</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border="0" width="100%"> <!-- width, border, cell width maybe better done in CSS -->
<tr>
<td width="15%">Seller ID</td>
<td width="10%">Start Date</td>
<td width="75%">Description</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr id="row-<?php h($row['Product_NO']) ?>" onclick="updateByPk('Layer2', this.id.split('-')[1]);">
<td><?php h($row['USERNAME']); ?></td>
<td><?php h($row['shortDate']); ?></td>
<td><?php h($row['Product_NAME']); ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="pagercontrols">
<?php if ($pg>1) ?>
<<- First
<?php } ?>
<?php if ($pg>2) ?>
<-- Previous
<?php } ?>
<?php if ($pg<$last-1) ?>
Next -->
<?php } ?>
<?php if ($pg<$last) ?>
Last ->>
<?php } ?>
</div>
Is it possible to have a continuous link for several items?
Across cells, no. But you're not really using a link anyway - those '#' anchors don't go anywhere. The example above puts the onclick on the table row instead. What exactly is more appropriate for accessibility depends on what exactly your application is trying to do.
(Above also assumes that the PK is actually numeric, as other characters may not be valid to put in an 'id'. You might also want to consider remove the inline "onclick" and moving the code to a script below - see "unobtrusive scripting".)
This is wrong:
if($cmd=="GetRecordSet")
echo "test in loop\n"; {
It should be:
if($cmd=="GetRecordSet") {
echo "test in loop\n";
In your getRowsByProductSearch function, you return the result of mysql_error if it occurs. In order to debug the code, maybe you can print it instead, so you can easily see what the problem is.

Categories