Why is my if statement skipping my else statement? - php

I have a piece of code, where every 20 mins, a system task runs a SQL query, adding to one of my database tables (tickets).
I have if if statement thats supposed to find than number (tickets) and use it to allow someone to "buy" items from my store.
It allows the user to buy more items, than they have tickets for (bringing their balance in to the negatives) like its just completely skipping my else statement. Is there something im doing wrong?
also thought i would add, the "tickets" column is INT and not like, VARCHAR or anything
the thing is also, it worked perfectly a few hours ago, so im not sure if i added something by accident, but now its not working
Be watching, the problem here is "if ($rewards > 4)"
http://prntscr.com/g79q3p
<div class="box">
<div class="contentHeader headerGreen">
<div class="inside">
5 Tickets
</div>
</div>
<ul>
<img src="/swf/c_images/album1584/2015HA.gif" align="right">
<li>25k Credits</li>
<li>25k Pixels</li>
<li>5 Diamonds
</ul>
<?php
if(isset($_POST['buy1'])) {
$getRewards = mysql_query("SELECT tickets FROM users WHERE id = '" . $_SESSION['user']['id'] . "'");
while($rewards = mysql_fetch_assoc($getRewards)) {
if($rewards > 4) {
mysql_query("UPDATE users SET tickets = tickets-5 WHERE id = '" . $_SESSION['user']['id'] . "'") or die(mysql_error());
mysql_query("UPDATE users SET credits = credits+25000 WHERE id = '" . $_SESSION['user']['id'] . "'");
mysql_query("UPDATE users SET activity_points = activity_points+25000 WHERE id = '" . $_SESSION['user']['id'] . "'");
mysql_query("UPDATE users SET vip_points = vip_points+5 WHERE id = '" . $_SESSION['user']['id'] . "'");
echo '
<div class="alert alert-sucess">
<strong>Well Done!</strong> Your items have been added.
</div>';
}
else if($rewards < 5) {
echo '
<div class="alert alert-error">
<strong>Error:</strong> You Do NOT Have Enough Tickets To Buy This
</div>';
}
/*else {
echo '
<div class="alert alert-error">
<strong>Error:</strong> You Do NOT Have Enough Tickets To Buy This
</div>';
}*/
}
}
?>
<form method='post'>
<input type="submit" value="Buy" name="buy1" style="width: 138px;cursor: pointer;" />
</form>
</div>

Please see how mysql_fetch_assocs works.
It returns an array. Does not matter how many fields you specify in sql - it is always an array.
Also do print_r and echo of your variables to see what is inside when it does not work.
if ($rewards["tickets"] > 4)
{
}
else if ($rewards["tickets"] < ....

Related

mysqli_num_rows generates unlimited amount of data

so, I'll try to explain it as good as I can with my knowledge in english.
I am trying to count data from my database, basically - how many fields I have with the same ID. here's image from database.
image from database
for example, in posts i have review system and it works, i have this PHP code to count how many same fields i have with review and id.
Here's the code:
<?php
$revposid = $res['content_id'];
$pos="SELECT review FROM comments WHERE review='positive' and postid=$revposid";
$neg="SELECT review FROM comments WHERE review='negative' and postid=$revposid";
$neu="SELECT review FROM comments WHERE review='neutral' and postid=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neg)){$rowcountneg=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neu)){$rowcountneu=mysqli_num_rows($result);}
?>
<div class="reviews" id="reviews">
<span class="good"><b class="fa fa-thumbs-up"></b><?php echo $rowcountpos ?></span>
<span class="neutral"><b class="icon-thumbs-up"></b><?php echo $rowcountneu ?></span>
<span class="bad"><b class="fa fa-thumbs-down"></b><?php echo $rowcountneg ?></span>
</div>
and when I try to use the same code
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
in my other script I have like system, it should show all my likes and under likes total likes of the post but when I use it it shows unlimited amount of data, i have no idea why. Here's the full code, I would appreciate some help or explanation.
<?php $ususername = $_GET['user_username'];$sql = "SELECT * FROM user_details WHERE user_username='$ususername'";$usresult = mysqli_query($_db,$sql);?>
<?php if( ! mysqli_num_rows($usresult) ) {
echo " Ooops? <br> <br>User <b>".$_GET["user_username"]."</b> doesn't exist.";
} else {
while($usrow = mysqli_fetch_array($usresult,MYSQLI_BOTH)) {?>
<?php
$current_user = $usrow['user_id'];
if ($_db->connect_error) {
die("Connection failed: " . $_db->connect_error);
}
$sql = "SELECT * FROM user_content_like WHERE user_id=$current_user ORDER BY date_added DESC;";
$result = $_db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$content_id = $row['content_id'];
$sql1 = "SELECT * FROM content WHERE content_id=$content_id";
$result1 = $_db->query($sql1);
if ($_SESSION['user_id'] == $usrow['user_id']) {$output = '
<button type="button" class="unlike_button" onclick="unlike(this);" name="like_button" data-content_id="'.$row["content_id"].'" ><i class="fa fa-minus"></i></button>
';} else {
$output = '';
}
while($cont = $result1->fetch_assoc()) {
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
echo '
<div class="community-feed-thread">
<div class="community-icon-thread"></div>
<div class="community-comments-thread">'.$output.'</div>
<a href="'.$cont["content_id"].'" class="community-title-thread"><h3>'.$cont["title"].'</h3>
<span class="likes-desc"> Total likes: '.$rowcountpos.'</span>
</a>
</div>
';
}
}}
else {
echo " hmmmmmmmmmmmm.<Br><br>". $usrow["user_username"]." doesn't like anything. ";
}
$_db->close();
?>
<?php }}?>
this is how i want it to look
This is how it looks
Your re-using the same variable for different result sets in the code...
$result = $_db->query($sql);
and
if ($result=mysqli_query($_db,$pos))
You will need to ensure you only use the variable name once or it may have side effects in other loops.

Prepared statements: while loop inside while loop. How to display ordered files in groups?

This is the code of a website of a non-profit organization that sponsors children in a situation of need; The sponsor can login to his/her user account and every three months see a series of files of his godchild (photos, letters, etc.) that can download.
This code should select the available files registered in a table named 'files' and show the result sorted by its corresponding period, are four periods of three months.
Example:
First quarter of 2016
Archive A1 ::: Archive B1 ::: Archive C1
Second quarter of 2016
Archive A2 ::: Archive B2 ::: Archive C2
Etc.
The problem so far has been that the page shows either the ordered periods if i remove the '$file statement' from 'while ( $updates -> fetch())', or shows all the files of all periods together with the '$file statement' whitout the '$updates statement'.
Can somebody help me?
<?php
...
// This relate the file with its user.
$FileCode = $_SESSION["Card"];
echo '
<div class="contentLogIn">
<div class="ctlg-ins">
<p class="startText">My files</p>
</div>
';
// I use SELECT DISTINCT because in the table 'files' multiple values can have the same period but i only want to know if the period have values not how much.
$updates = $db->prepare("SELECT DISTINCT Trimester, Quarter, Year FROM files WHERE FileCode=? ORDER BY Year DESC, Quarter DESC, Trimester DESC");
if ($updates === FALSE) {trigger_error($db->mysqli->error, E_USER_ERROR);}
$updates->bind_param("s", $FileCode);
$updates->execute();
$updates->bind_result( $Trimester, $Quarter, $Year );
while ( $updates->fetch() ) {
// For every single period shows its title.
if ( isset($Year, $Quarter) ) {
$FilesDate = $Trimester . " quarter of " . $Year; // Output example: *First quarter of 2016*
} else {
$FilesDate = "There's no available files.";
}
echo '
<div class="W100">
<p class="startTextDesc">' . $FilesDate . '</p>
</div>
<div class="A12">
';
$files = $db->prepare("SELECT Type, Class, SRC FROM files WHERE FileCode=? AND Quarter=? AND Year=?");
if ($files === FALSE) { trigger_error($db->mysqli->error, E_USER_ERROR); }
$files->bind_param("sss", $FileCode, $Quarter, $Year);
$files->execute();
$files->bind_result($Type, $Class, $SRC);
while ( $files->fetch() ) {
// This is the file that it is supposed to be displayed under its period title - like the example i post before.
echo '
<div class="FileCont CustomPointer">
<form method="POST" action="/php/File.Download.php">
<input type="hidden" name="fileButton" id="fileButton" value="' . $SRC . '">
<button type="submit" class="buttonFile-download">
<div class="CustomPointer">
<p style="...">' . $Type . '</p>
</div>
</button>
</form>
</div>
';
}
$files->free_result();
echo '
</div>
';
}
$updates->free_result();
echo '
</div>
';
...
?>
Something like this should work; you use a variable ($CurrentFilesDate) to keep track of the period, and when you see it changes, you put a new header in.
$CurrentFilesDate = "";
$updates = $db->prepare("SELECT Trimester, Quarter, Year, Type, Class, SRC FROM files WHERE FileCode=? ORDER BY Year DESC, Quarter DESC, Trimester DESC");
if ($updates === FALSE) {
trigger_error($db->mysqli->error, E_USER_ERROR);
}
$updates->bind_param("s", $FileCode);
$updates->execute();
$updates->bind_result( $Trimester, $Quarter, $Year, $Type, $Class, $SRC );
while ( $updates->fetch() ) {
$FilesDate = $Trimester . " quarter of " . $Year;
if ($FilesDate != $CurrentFilesDate) {
if (!empty($CurrentFilesDate)) {
echo '</div>';
}
echo '
<div class="W100">
<p class="startTextDesc">' . $FilesDate . '</p>
</div>
<div class="A12">
';
$CurrentFilesDate = $FilesDate;
}
echo '
<div class="FileCont CustomPointer">
<form method="POST" action="/php/File.Download.php">
<input type="hidden" name="fileButton" id="fileButton" value="' . $SRC . '">
<button type="submit" class="buttonFile-download">
<div class="CustomPointer">
<p style="...">' . $Type . '</p>
</div>
</button>
</form>
</div>
';
}
echo '</div>';
This code is very ugly though, you should be separating your PHP and HTML. I recommend using the DB loop to build an array in the structure you need, and then loop through it in an HTML template that contains only simple echo statements.

How to change the "while" loop to retrieve only 3 top records from MySQL database

I set up the query to SELECT * FROM,
Then I used the while loop to print out all retrieved records and it all works fine.
But what I need is to print out only the TOP 3 of those records, is there any way to change that while loop to make it work this way.
Any help on this will be much appreciated, thx
while($row = $alerts_query->fetch_object()){
echo "<div class='panel'>
<div class='panel-heading'>
<h3 class='panel-title'>" . $row->ticket_title . " <a href='clientpanel.php?tab=dashboard=" . $row->ticketId . "' aria-hidden='true' type='button' class='close pull-right'>x</a></h3>
</div>
<div class='panel-body'>" . $row->ticket_description . "
<br />
<br />
<span style='color: #999'>Reported: " . $row->ticket_date . "</span>
</div>
</div>";
}
Do not limit in the while loop (though, it's possible). Change your SQL instead:
SELECT * FROM yourtable
Append:
SELECT * FROM yourtable LIMIT 3
If for some reason you should do it in PHP (not advised in this situation):
$i = 0;
while($row = $alerts_query->fetch_object() and $i<3) {
$i++;
// ...
}
Use:
SELECT * FROM [table] LIMIT 3
Use
SELECT * FROM table LIMIT x ORDER BY ASC
where x in your case is 3
It can achieved in many ways, using LIMIT clause is one of the approach. But following is according your scenario
$i = 1;
while ($row = $alerts_query->fetch_object()) {
if ($i > 3)
break;
echo "<div class='panel'>
<div class='panel-heading'>
<h3 class='panel-title'>" . $row->ticket_title . " <a href='clientpanel.php?tab=dashboard=" . $row->ticketId . "' aria-hidden='true' type='button' class='close pull-right'>x</a></h3>
</div>
<div class='panel-body'>" . $row->ticket_description . "
<br />
<br />
<span style='color: #999'>Reported: " . $row->ticket_date . "</span>
</div>
</div>";
$i++;
}
Try this
SELECT * FROM table LIMIT 0,3

PHP mysql_num_rows die error

I want to create one page, where users add their informations..
I allready have that page created, but my real problem its down code..
I have some kind of problem, with that part of code:
<?php
//Connect to DB
$db = mysql_connect("localhost","USER","PASS") or die("Database Error");
mysql_select_db("DB",$db);
//Get ID from request
$idstire = isset($_GET['idstire']) ? (int)$_GET['idstire'] : 0;
//Check id is valid
if($idstire > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM stiri2 WHERE idstire = " . $idstire);
if($resource === false)
{
die("Eroare la conectarea cu baza de date");
}
if(mysql_num_rows($resource) == 0)
{
die("Se pare ca stirea nu mai exista, sau a fost stearsa. <a href='http://www.wanted-web.ro'>ACASA</a>");
}
$user = mysql_fetch_assoc($resource);
echo "
<div class='main-article-content'>
<h2 class='article-title'>asd</h2>
<div class='article-photo'>
<img src='" . $user['poza'] . "' class='setborder' alt='' />
</div>
<div class='article-controls'>
<div class='date'>
<div class='calendar-date'>" . $user['data'] . "</div>
</div>
<div class='right-side'>
<div class='colored'>
<a href='' class='icon-link'><span class='icon-text'></span>Printeaza articol</a>
<a href='#' class='icon-link'><span class='icon-text'></span>Trimite prietenilor</a>
</div>
<div>
<a href='#' class='icon-link'><span class='icon-text'></span>de Cristian Cosmin D.</a>
<a href='#' class='icon-link'><span class='icon-text'></span>39 comentarii</a>
</div>
</div>
<div class='clear-float'></div>
</div>
<div class='shortcode-content'>
<p>" . $user['nume'] . " , " . $user['prenume'] . " , " . $user['varsta'] . " , " . $user['localitatea'] . "</p>
</div>
</div>
";
}
$query = "UPDATE stiri2 SET accesari = accesari + 1 WHERE idstire=\"" . $idstire . "\"";
$result = mysql_query($query) OR die(mysql_error());
?>
It's show me error from here:
if(mysql_num_rows($resource) == 0)
{
die("Se pare ca stirea nu mai exista, sau a fost stearsa. <a href='http://www.wanted-web.ro'>ACASA</a>");
}
I really dont understand why!?
Can someone explain me?
Thank you!
mysql_query should have the second parameter as the connection which is in your case $db
$resource = mysql_query("SELECT * FROM stiri2 WHERE idstire = " . $idstire,$db);
if this also not works then use mysql_error to know the exact error
$row=mysql_num_rows($resource);
if($row)
{
}
else
{
mysql_error();
}
this will show you if there is problwm in mysql_num_rows
Well the problem is, that your SQL Statement does not have any results.
Please check if your database contains some rows for this idstire.
If $_GET['idstire'] is not set, you are setting $idstire to 0. Is there any entry in the table for idstire=0?
You can print your php query with $idstire replaced with its value. Take that query and execute in phpmyadmin to see the error. Also verify that row exists for the value of $idstire being used in the query.

PHP Gallery Problem

Ok, I have a gallery that's being populated by a database but for some reason it's not pulling entries from beyond May 31st 2011. I've scoured the code and can't find any date limitations so I'm at a loss as to why it's not pulling in any recent entries.
I've also looked through the database table and don't see any irregularities between pre May31st and more current entries.
<?php
//GALLERY PAGE
$user="USER";
$password = "PASSWORD";
$database = "GALLERY";
$hostname_portfolio ="localhost:3306";
//gets the page number from the URL
if($_GET["pageNum"]==''){
$listedNum=0;
//gets the page limit from the URL
$limit=5;
}
else{
$listedNum=$_GET["pageNum"];
//gets the page limit from the URL
$limit=$_GET["limit"];
}
//creates the list of projects and puts them into an array
$project= array();
$con = mysql_connect($hostname_portfolio,$user,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$dbcon = mysql_select_db("GALLERY", $con);
if (!$dbcon)
{
die('Could not connect: ' . mysql_error());
}
if ($dbcon)
{
}
mysql_select_db($database, $con);
$result = mysql_query("SELECT * FROM Persons ORDER BY date_uploaded DESC");
echo"<div class='clear' style='clear:both;'></div>";
$j=0;
do{
if($row['approved']=="true"){
$project[$j] =
"<div class='project-list'>
<div class='user-project'>
<div class='container'>
<div class='before-box' >
<p class='picture_state'>Before</p>
<a href='http://THEURL.com/". $row['image_path']."'>
<img src= '". $row['image_path']. "' width='400px' height='300px'/></a>
<br />
</div>
<div class='after-box'>
<p class='picture_state'>After</p>
<a href='". $row['picture_state']."'>
<img src= '". $row['picture_state']. "' width='400px' height='300px' /></a>
<br />
</div>
<div class='sidebox'>
<div class='inner-sidebox'>
<p class='date-project'>
Submitted by " . $row['FirstName'] . " " . $row['LastName']. " on " .$row['date_uploaded']. "</p>
<p> " .$row['decription']. "</p>";
if($row['ATTR1'] || $row['ATTR2']){
$project[$j] .= "<p>Used ";
if ($row['ATTR1']){
$project[$j] .= "PRODUCT2™";
if ($row['color1']){
$project[$j] .= " in " . $row['color1'];
}
if ($row['ATTR2']){
$project[$j] .= " and ";
}
}
if($row['ATTR2']){
$project[$j] .= "PRODUCT<sup>®</sup>";
if ($row['color2']){
$project[$j] .= " in " . $row['color2'];
}
}
$project[$j] .= "</p>";
}
$project[$j] .= "
</div>
</div>
</div>
<div class='clear' style='clear:both;'>
</div>
</div>
<div class='clear' style='clear:both;'>
</div>
</div>
<div class='clear' style='clear:both;'>
</div>";
$j++;
}
}
while($row = mysql_fetch_array($result));
$max=sizeof($project);
for($i=$listedNum;$i<$limit;$i++){
echo $project[$i];
}
$max=sizeof($project) - 1;
echo "<div class='bottom' style='width:170px;margin:0px auto;'>";
if($listedNum > 0){
$prevPageNum=$listedNum - 5;
$lastPage= $limit - 5;
echo "<a href='http://THEURL.com/gallery.php? pageNum=".$prevPageNum."&limit=".$lastPage."'>< Last Page </a>";
}
else{
$prevPageNum=$listedNum;
$lastPage= $limit;
}
echo" ";
if($limit <= $max){
$newPageNum=$listedNum + 5;
$nextPage= $limit + 5;
echo "<a href='http://THEURL.com/gallery.php?pageNum=".$newPageNum."&limit=".$nextPage."'> Next Page ></a>";
}
else{
$newPageNum=$listedNum;
$nextPage= $limit;
}
echo "</div>";
mysql_close($con);
?>
Im going to guess that its one of the following:
Youre server is only allowing you to pull 'x' amount of rows within each query (and that 'x' is dont at may 31st')
or theres something different with the files after may 31st. compared to the ones earlier
There's nothing in the code. It might be the way your database is configured where it only lets a certain number of results be returned and that happens to coincide with the date.
Check data in table. May be, after may 31st it was not "approved" ("approved" field was not set to something that casts to boolean TRUE)
Judging from your code - either date_uploaded is null in the records after May 31 or something else is wrong in your DB. Approved not equaling true on the offending records, for example.
Failing that, maybe it has something to do with this limitation. Try passing in a number higher than 5 and see if you get more records showing.
//gets the page number from the URL
if($_GET["pageNum"]==''){
$listedNum=0;
//gets the page limit from the URL
$limit=5;
}
else{
$listedNum=$_GET["pageNum"];
//gets the page limit from the URL
$limit=$_GET["limit"];
}

Categories