MYSQLI Prepared Statement White Page - php

I am trying to convert some PHP code for notifications into a more suitable Prepared statement. No matter what I try, it breaks my page. Is any body out there able to tell me where the error lies?
EDIT The page is not completely blank. The page breaks after this code.
$acctNotsQry = $redoDB->prepare('SELECT message, nDate FROM notifications WHERE uID = ? AND nSeen = "0" ORDER BY nDate DESC');
$acctNotsQry->bind_param('i', intval($memID));
$acctNotsQry->execute();
$acctNotsQry->store_result();
$acctNotsQry->bind_result($notMessage, $notnDate);
if($acctNotsQry->num_rows == 0){
echo '<li><div class="nilNots">NO NOTIFICATIONS</div></li>';
} else {
while($acctNotsQry->fetch()) {
?>
<li><i class="fa fa-bell"></i> <?php echo htmlspecialchars_decode(stripslashes($notMessage)); ?>
<p><?php echo date('d M Y - h:ia', strtotime($notnDate)); ?></p></li>
<?php
}
}
$acctNotsQry->close();
SECOND EDIT: The following code DOES work, the above does not. It might help with a solution:
$acctNotsQry = 'SELECT * FROM notifications WHERE uID = "'.$memID.'" AND nSeen = "0" ORDER BY nDate DESC';
$acctNotsRes = $redoDB->query($acctNotsQry);
$acctNotsNum = $acctNotsRes->num_rows;
if($acctNotsNum == 0){
echo '<li><div class="nilNots">NO NOTIFICATIONS</div></li>';
} else {
while($acctNotsRow = $acctNotsRes->fetch_assoc()){
$notMsg = $acctNotsRow['message'];
?>
<li><i class="fa fa-bell"></i> <?php echo htmlspecialchars_decode(stripslashes($notMsg)); ?>
<p><?php echo date('d M Y - h:ia', strtotime($acctNotsRow['nDate'])); ?></p></li>
<?php
}
}
I have tried searching for a solution to no avail.
Many thanks in advance.

Change
$acctNotsQry->bind_param('i', intval($memID));
to
$acctNotsQry->bind_param('i', $memID);
The 2nd and following arguments to bind_param are reference parameters, so you have to use variables there, not expressions. You don't need to call intval() yourself, the i type in the first argument tells mysqli to convert it to an integer when sending it to MySQL.

Related

echo inside if else in php

I want to use echo inside if...else so i can print "-" if the data doesn't exist in the database, and if the data exist in database, print the data. Until now, my "-" doesn't shows up if the data doesn't exist in database.
This is for printing on localhost .php
<?php
$kata='';
$no=1;
$data = mysqli_query($koneksi,"SELECT msdosen.`IDDOSEN`, `POSITION`,
`COMPANY`, `START`, `END`
FROM trprofessionalhis
INNER JOIN msdosen ON msdosen.IDDOSEN = trprofessionalhis.IDDOSEN
WHERE trprofessionalhis.IDDOSEN ='$id'
ORDER BY trprofessionalhis.`START` DESC");
while($d = mysqli_fetch_array($data)){
?>
<br><?php echo $d['POSITION'];?><br><?php echo $d['COMPANY'];?>
<br><?php echo $d['START'];?>-<?php echo $d['END']?><br>
<?php
if (empty($d['POSITION'])){
echo '-';
}
else{
echo '';
}
}
?>
I expect the output prints "-" if the data doesn't exist in database.
You can use ternary operator. Here is example:
echo empty($d['POSITION']) ? $d['POSITION'] : '-';
If you are using PHP 7+ version, there is more short way:
echo $d['POSITION'] ?? '-';
More examples about ternary operator.
If your SQL query returns no result, $d will return NULL and the while-loop will end before it starts. Therefore none of the echo statements in the loop will be run.
Given the screenshot in this comment, I think this is the case. That is why your if-then never ran in the case intended and shows nothing:
As #catcon mentioned in comment, you can use mysqli_num_row to check if there is any result at all. That way you may still show something when there is no result:
<?php
$kata='';
$no=1;
$data = mysqli_query($koneksi,"SELECT msdosen.`IDDOSEN`, `POSITION`,
`COMPANY`, `START`, `END`
FROM trprofessionalhis
INNER JOIN msdosen ON msdosen.IDDOSEN = trprofessionalhis.IDDOSEN
WHERE trprofessionalhis.IDDOSEN ='$id'
ORDER BY trprofessionalhis.`START` DESC");
// add this to print "-" if the query returns no result
if (mysqli_num_row($data) <= 0) {
echo '<br> -';
}
?>
<?php while($d = mysqli_fetch_array($data)) { ?>
<br><?php echo $d['POSITION'];?><br><?php echo $d['COMPANY'];?>
<br><?php echo $d['START'];?>-<?php echo $d['END']?>
<?php } ?>

If field == null display else don't

My recordset is:
mysqli_select_db($KCC, $database_KCC);
$query_rsOtherServices = "SELECT pagecontent.mainMenuID, mainmenu.mainMenuLabel, pagecontent.subMenuID, submenu.subMenuLabel, pagecontent.contentID, pagecontent.contentTitle FROM submenu RIGHT JOIN (mainmenu RIGHT JOIN pagecontent ON mainmenu.mainMenuID = pagecontent.mainMenuID) ON submenu.subMenuID = pagecontent.subMenuID WHERE pagecontent.mainMenuID = 1 AND pagecontent.subMenuID IS NULL";
$rsOtherServices = mysqli_query($KCC, $query_rsOtherServices) or die(mysqli_error());
$row_rsOtherServices = mysqli_fetch_assoc($rsOtherServices);
$totalRows_rsOtherServices = mysqli_num_rows($rsOtherServices);
and the code I'm using to display the record is:
<?php do { ?>
<li><h4><?php echo $row_rsOtherServices['contentTitle']; ?></h4></li>
<?php } while ($row_rsOtherServices = mysqli_fetch_assoc($rsOtherServices)); ?>
This all works fine if a record exists but if there is no record, a 'link' is available to click even though it's not visible.
I have tried <?php if ($totalRows_rsOtherServices['subMenuID'] === Null) { ?>, <?php if ($totalRows_rsOtherServices['subMenuID'] > 0) { ?>, <?php if ($totalRows_rsOtherServices['subMenuID'] == true) { ?>, <?php if ($totalRows_rsOtherServices['subMenuID'] == false) { ?>but to no avail.
I know nothing about programming and even less about PHP so I'm not even sure is I'm going in the right direction.
I need to get rid of the 'invisible link'.
Because you are using do ... while, use while only.
Try
<?php while (($row = mysqli_fetch_assoc($rsOtherServices))) { ?>
<li>
<a href="familyservices.php?idVal=<?php echo $row['contentID']; ?>">
<h4><?php echo $row['contentTitle']; ?></h4>
</a>
</li>
<? } ?>
OK, I've figured it out.
Instead of using $((totalRows_rsOtherServices['subMenuID']) > 0), I changed it to (($row_rsOtherServices) > 0). This did the trick.
However, if I use the while (($row = mysqli_fetch_assoc($rsOtherServices)))... as suggested, even if there is a record, it doesn't display.
At this moment in time I'm not going to worry to much about that but will investigate it in the future.

Getting only last message for each user

I am doing PM system for my site. I created subpage for each conversation by two users. I am having hard time programming the front page, where all conversations are printed. I cant get only one and last meassage for each user.
Here is my function:
public function fetch_data($id_uporabnika) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum");
$query->bindValue(1, $id_uporabnika);
$query->execute();
return $query->fetchAll();
}
And here is my code for printing conversations:
<?php
} else {
$zs = new Zs;
$id_uporabnika = $trenutni['id'];
$zsji = $zs->fetch_data($id_uporabnika);
?>
<h2>Zasebna sporočila</h2>
<ul class="vsi-zsji">
<?php foreach ($zsji as $sporocilo): ?>
<?php $od = $oseba->fetch_data($sporocilo['od']) ?>
<li>
<a href="<?php echo $url; ?>zs/poglej/<?php echo $sporocilo['od']; ?>">
<img src="<?php echo $url; ?>inc/timthumb.php?src=<?php echo $od['slika_potem'] ?>&w=60&h=60" alt="">
<p><b><?php echo $od['uporabnisko_ime'] ?></b></p>
<p><?php echo $sporocilo['vsebina'] ?></p>
</a>
</li>
<?php endforeach ?>
</ul>
<?php } ?>
I get 10 PMs from one user, 3 for another. I want to display just the latest one.
Just put a LIMIT clause in your SQL query and order by DESC to get the latest message:
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum DESC LIMIT 1");
something like this should help
SELECT id,datum, max(pm) FROM zs WHERE za = ? group by id,datum

while loop not cycling through as expected

I have a loop that runs through returned rows from a MySQL query and performs commands.
When the data is displayed on the webpage (seen at the end of the pasted code), the requested_date (from the $result_dec query) is cycling through correctly, but the memPayout(from the $emailcompleted query) is not. Where it shows the memPayout it is just listing the same number for each date.
When I run this in phpmyadmin, I see that different dates have different memPayouts..so I know there is a bug here.
I appreciate the help.
UPDATE: I've updated the old code with the new one that I adjusted. I tried to wrap the email earnings query with the original foreach. I also removed the unnecessary extra bgcolor switch. The result on my webpage is still the same as before. Any more advice is really appreciated.
<?php
//--------------------- Code for Decline TRANSACTION --------------------------------------
$u_id = $_SESSION['user_ses']['id'];
$result_dec = #mysql_query("(select trv.tr_user_id , usr.full_name ,usr.email , usr.paypal , trv.requested_date, trv.requested_status, trv.click_payment_status, trv.tracking_id
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and usr.id=trv.tr_user_id and usr.id='1454'
and trv.payment_status='pending' and trv.requested_status='declined' group by trv.tr_user_id, trv.requested_date order by trv.requested_date asc )
union all
(select trv.tr_user_id , usr.full_name ,usr.email , usr.paypal , trv.click_request_date, trv.requested_status, trv.click_payment_status, trv.tracking_id
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and usr.id=trv.tr_user_id and usr.id='1454'
and trv.payment_status='pending' and trv.click_payment_status='declined' group by trv.tr_user_id, trv.click_request_date order by trv.requested_date asc ) ");
$nr = mysql_num_rows($result_dec);
$categories_d = array();
while($row = mysql_fetch_array($result_dec))
{
$categories_d[] = $row;
}
if(count($categories_d)>0)
{
$counter=0;
foreach($categories_d as $index=>$rec)
{
$counter++;
if ($counter % 2 == 0)
{
$bgcolor = "#FFFFFF";
}
else
{
$bgcolor = "#F5F7D9";
}
$userId=$rec['tr_user_id'];
$EmailCompletedOffer=#mysql_query("select off.member_amount as memPayout
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and off.offer_type='mailchimp' and usr.id=trv.tr_user_id and
trv.tr_user_id=$userId and trv.requested_date='".$requested_date."' and trv.payment_status='pending' and trv.total_conversion !=0 and trv.requested_status='declined' ");
$rowemailEarn=#mysql_fetch_array($EmailCompletedOffer);
$totalEmailEarnAmount1=$rowemailEarn['memPayout'];
?>
<div class="datarow_his">
<div class="his_onecol1"><?php echo '$'. $totalEmailEarnAmount1;?> </div>
<div class="his_onecol1"> <?php echo "Declined"; ?> </div>
<div class="his_onecol2"><?php echo date("M j,Y " ,strtotime($rec['requested_date']));?></div>
<!--<div class="his_onecol1"><?php //echo date("M j,Y " ,strtotime($rec['paid_date']));?></div>-->
</div>
<p><?php echo $totalEmailEarnAmount1?></p>
<?php /*}
} */
}
}
?>
Your code roughly looks like this:
fetch categories
if(categories not empty) {
foreach(category) {
set $bgcolor and $userId (has no effect)
}
get query results for the last $userID and set $totalEmailEarnAmount1
if(categories not empty) {
foreach(category) {
set $bgcolor again (has no effect)
generate a div using $totalEmailEarnAmount1
}
}
}
Since you set $totalEmailEarnAmount1 outside the final foreach, it has the same value on every iteration of the loop.
(If you indent your code in a way that is consistent with its structure, errors like this will become obvious. The messy indentation makes it hard for you to see what is going on.)

variable result from sql query not showing

Is there anything wrong in this scenario? the result isn't showing. maybe i'm getting the syntax wrong?
// fetch the latest tweet
$lastTweet = '';
$q2 = "SELECT tweet FROM timel ORDER BY id DESC LIMIT 1";
list($lastTweet) = $conn->get_results($q2);
if(!$lastTweet){
$lastTweet = "You don't have any tweets yet!";
}
var_dump($lastTweet);
and this on the html body:
<span class="latest"><strong>Latest: </strong><span id="lastTweet"><?.=$lastTweet?></span></span>
If you changed your first line to
$lastTweet = array();
And your third line to
$lastTweet = $conn->get_results($q2);
Then you would be able to use
<?php var_dump($lastTweet); ?>
But in your case lastTweet contains a string of text, hence you need to use echo to print it's content.
<?php echo $lastTweet ?>
Nb: i'm not sure about your project details but i'm guessing you'd need to also get the date, maybe id and user_id of the tweet, if that's the case, you might want to make lastTweet an empty array()
Use this:
<span class="latest"><strong>Latest: </strong><span id="lastTweet">
<?php echo $lastTweet; ?></span> </span>
Saludos ;)

Categories