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>";
}
Related
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)) ...
I'm starting to learn bit by bit how to program in PHP. But I have come to a problem I can't fix myself. So I require a bit of help. The problem is, in my function I get information from my database. The variable $DisplayProducts01Title I want to use into my other function that is posted below
Function to get the data:
//GetAllPages
function GetAllPages() {
$GetAllPagesSql = "SELECT ContentPages.ContentPagesID, ContentType.ContentTypeName, ContentInformation.ContentInformationTitle, ContentPages.ContentPagesOrder FROM `ContentPages` INNER JOIN ContentType ON ContentPages.ContentTypeID = ContentType.ContentTypeID INNER JOIN ContentInformation ON ContentPages.ContentInformationID = ContentInformation.ContentInformationID ORDER BY ContentPagesOrder";
$GetAllPagesQuery = mysql_query($GetAllPagesSql);
while (($GetAllPagesRow = \mysql_fetch_assoc($GetAllPagesQuery)) != false) {
if($GetAllPagesRow[ContentTypeName] == 'products01') {
DisplayProducts01DesignFunction();
$DisplayProducts01Title = $GetAllPagesRow[ContentTypeTitle];
return $DisplayProducts01Title;
}
else if ($GetAllPagesRow[ContentTypeName] == 'information01') {
DisplayInformation01DesignFunction();
}
}
}
Function to show the data:
//DisplayProductsDesignFunction
function DisplayProducts01DesignFunction($DisplayProducts01Title) {
echo "<div class='paddingcnt' id='services'>
<div class='row-fluid'>
<div class='span12'>
<div class='pricing'>
<div class='container'>
<div class='row-fluid'>
<h1>" . $DisplayProducts01Title . "</h1>
<div class='row-fluid'>";
DisplayProducts01Function();
echo "</div>
</div>
</div>
</div>
</div>
</div>
</div>";
}
How can I use the variable $DisplayProducts01Title from function GetAllPages() into function DisplayProducts01DesignFunction()?
Thanks in advance
You need to pass it into that function when it is called. See below:
//GetAllPages
function GetAllPages() {
$GetAllPagesSql = "SELECT ContentPages.ContentPagesID, ContentType.ContentTypeName, ContentInformation.ContentInformationTitle, ContentPages.ContentPagesOrder FROM `ContentPages` INNER JOIN ContentType ON ContentPages.ContentTypeID = ContentType.ContentTypeID INNER JOIN ContentInformation ON ContentPages.ContentInformationID = ContentInformation.ContentInformationID ORDER BY ContentPagesOrder";
$GetAllPagesQuery = mysql_query($GetAllPagesSql);
while (($GetAllPagesRow = \mysql_fetch_assoc($GetAllPagesQuery)) != false) {
if($GetAllPagesRow[ContentTypeName] == 'products01') {
// changes start here
$DisplayProducts01Title = $GetAllPagesRow[ContentTypeTitle];
DisplayProducts01DesignFunction($DisplayProducts01Title);
// changes end here
}
else if ($GetAllPagesRow[ContentTypeName] == 'information01') {
DisplayInformation01DesignFunction();
}
}
}
I'm pulling comments from MySQL with PDO with a limit of 2 comments to show, yet the query does not retrieve the comments nor can I var_dump neither print_r since it does print anything. I believe it should be an issue with the query itself, thought it hasn't worked for countless hours so I figured I'd ask more experienced programmers.
There is no data outputted onto the page, I'm unsure whether It's an issue with the second_count variable or the post_iD variable.
1. Am I using the while loop correctly?
2. Better to use while loop or foreach?
3. Does var_dump and print_r function not work due to errors in the
query or in PHP.INI from what it seems?
Here is how I'm pulling the data with PDO.
PUBLIC FUNCTION Comments( $post_iD,$second_count ){
if($second_count){
$sth = $this->db->prepare("
SELECT C.com_id, C.uid_fk, C.comment, C.created, U.username, U.photo
FROM comments C, users U
WHERE U.status = '1'
AND C.uid_fk = U.uiD
AND C.msg_id_fk = :postiD
ORDER BY C.com_id ASC LIMIT :second, 2");
$sth->execute(array(':postiD' => $post_iD, ':second' => $second_count));
while( $row = $sth->fetchAll())
$data[] = $row;
if(!empty($data)){
return $data;
}
}
}
And here is how I'm trying to display the information on my page,
<?php
$commentsarray = $Wall->Comments( $post_iD, 0 );
$x=1;
if($x){
$comment_count = count($commentsarray);
$second_count = $comment_count-2;
if($comment_count>2){
?>
<div class="comment_ui" id="view<?php echo $post_iD; ?>">
View all<?php echo $comment_count; ?> comments
</div>
<?php
$commentsarray = $Wall->Comments( $post_iD, $second_count );
}
}
if( $commentsarray ){
foreach($commentsarray as $data){
$com_id = $data['com_id'];
$comment = tolink(htmlcode($data['comment'] ));
$time = $data['created'];
$mtime = date("g:i", $time);
$username = $data['username'];
$com_uid = $data['uid_fk'];
$photo = $data['photo'];
?>
<div class="stcommentbody" id="stcommentbody<?php echo $com_id; ?>">
<div class="stcommentimg">
<img src="<?php echo $photo;?>" class="small_face">
</div>
<div class="stcommenttext">
<?php if($uiD == $com_uid || $uiD == $post_iD ){ ?>
<a class="stcommentdelete" href="#" id="<?php echo $com_id;?>" title="Delete Comment"></a>
<?php } ?>
<div class="stmessage"><?php echo clear($comment); ?></div>
</div>
<div class="stime"><?php echo $mtime;?> — Like</div>
</div>
<?php
}
}
?>
1.Simply like this:
$data = $sth->fetchAll();
if(!empty($data) AND count($data) > 0){
return $data;
}
You don't need while to work with fetchAll.
2.I'ts better to use Exception in every your query then you can see if there is any error.
e.g
try
{
//your PDO stuffs here
}
catch (PDOException $e)
{
echo $e->getMessage();
}
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>
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.