How do I count rows with matching id? - php

I'm currently having some difficulty with determining if any rows match a specific user id. The code runs fine, but the if statement (if($notifs !== false) always returns true and hence "No notifications found" never displays. How do I write the statement to only check for "receive_id" that match the current session id?
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if($notifs !== false)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT id FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetch(PDO::FETCH_ASSOC);
if($query2result !== false){
$follow .= '<button class="button">Remove Channel</button>';
}
else{
$follow .= '<button class="button">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
&nbsp<button class="button">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}

fetchAll only returns false if the query failed, but it's not failing. The result is an array. Your best to check if count($notifs) > 0 and also if $notifs === false for the possibility of the query failing.

http://php.net/manual/en/pdostatement.fetchall.php says:
An empty array is returned if there are zero results to fetch, or FALSE on failure.
A query that matches zero rows is not a failure. It's a success at giving you the information that there are zero matching rows.
So you shouldn't compare with $notifs !== false, which compares exactly to the boolean false. You might like to compare with:
if (!$notifs)
This will also test for the empty array.

Try
if ($stmt->RowCount() > 0) {
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
//code here
}
Instead of
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($notifs !== false) {
//code here
}

Related

if row equals parameter from url

my url i have a parameter called uid
in my sql i have
Select * from users Where uid = {$_GET['uid']}
now I have my while loop
while (($row = mysqli_fetch_assoc($result)) != false) {
$uid = $row['uid'];
}
every thing is fine to this point. what i want is if the uid in the database does not equal the $_GET from parameter redirect.
if ($uid == $_GET['uid']) {
return true;
} else {
redirect(ROOT_URI);
}
what i am trying to prevent is modifying uid in the url. that if the uid does not exists it will redirect.
simply you can do like this
$rowcount=mysqli_num_rows($result);
if($rowcount != 0)
{
return true;
}
else
{
redirect(ROOT_URI);
}
since if the uid is in the table mysqli_num_rows doesn't return 0
Use this. I've included some comments as explanation to what I am doing.
$x = 0; //checker
while (($row = mysqli_fetch_assoc($result)) != false) {
if($uid == $row['uid']){
$x = 1; //logic is if there is a match, $x will become 1, else it will stay at 0 value
}
}
//now check the value of $x
if ($x == 1){
//there is a match
return true;
}
else{
//there is no match
redirect(ROOT_URI);
}
To redirect in PHP, you can use the header() function:
header("Location: your_url");
Your sql query is wrong. Try with this one:
Select uid from users Where uid = {$_GET['soldier']}

How to use SELECT IFNULL in PDO?

i was looking for a way to return an error if no results were found in a MySql query, at first i declared a variable value false, and if the fetch() function is true it will set the value of that boolean to true, then i check if it is true or false, but then i searched for that in internet cause i didn't like my solution that much, so I found the function IFNULL(query, 'error message');
I tried it but I had an error, can you tell me what's wrong in my code?
if(isset($_POST['tosearchfor']))
{
$query = $db->query('SELECT IFNULL( (SELECT * FROM searchfor WHERE title LIKE \'%'.$_POST['tosearchfor'].'%) , \'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'strong');
while($result = $query->fetch())
{
echo '<div class="result"><a class="title" href="#">'.$result['title'].'</a><span class="link"><span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">‣</span>https://www.qsoft.com/'.$result['link'].'</span><span class="details">'.$result['details'].'</span></div>';
}
}
else
{
echo 'Error : empty search';
}
Thank you.
Hey i used a different method not in youre query but with $query->rowCount().
Let's use the IF outside of the query :)
And the $db->prepare protect youre query, because never put a $_POST directly inside a query without protection.
if(isset($_POST['tosearchfor'])){
//We prepare the query
$query = $db->prepare("SELECT * FROM searchfor WHERE title LIKE '%:tosearch%'");
//We had parameters
$query->bindParam(':tosearch',$_POST['tosearchfor'], PDO::PARAM_STR);
//We execute the query
$query->execute();
//We retrieve the results in array of objects
$results = $query->fetchAll(PDO::FETCH_OBJ);
if (count($results) > 0) {
foreach ($results as $result){
echo '<div class="result">
<a class="title" href="#">'.$result->title.'</a>
<span class="link">
<span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">‣</span>
https://www.qsoft.com/'.$result->link.'
</span>
<span class="details">'.$result->details.'</span>
</div>';
}
} else {
echo 'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'</strong>';
}
}else{
echo 'Error : empty search';
}
The default result value of IFNULL(expr1,expr2) is the more “general”
of the two expressions, in the order STRING, REAL, or INTEGER.
You cannot evaluate a group of records with IFNULL. Something like below
Also instead of using direct substitution values, you could use below methods to avoid sql injection.
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
if(empty($stmt)){
return false;
}
foreach ($stmt as $row) {
// do something with $row
}
return result;
If this method return false then there is no search result.
Finally, this is my code, i also added max number of results 20.
$db = new PDO('mysql:host=localhost;dbname=search','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['tosearchfor']))
{
$query = $db->query('SELECT * FROM searchfor WHERE title LIKE \'%'.$_POST['tosearchfor'].'%\'');
for($i=0; $i<20; $i++)
{
if($result = $query->fetch())
{
echo '<div class="result">
<a class="title" href="#">'.$result['title'].'</a>
<span class="link">
<span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">‣</span>
https://www.qsoft.com/'.$result['link'].'
</span>
<span class="details">'.$result['details'].'</span>
</div>';
}
else
{
if($i==0)
{
echo 'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'</strong>';
}
}
}
}
else
{
echo 'Error : empty search';
}

Running mysql query if column is false in PHP

I am trying to display results of a mysql query and some html if the first mysql queries coulmn returns false or is set to false. I've tried a few things but I can't seem to get it to work properly, I will show code below. Any help is much appreciated. In the code I want to only display site message if the user's acknowledgement is false otherwise don't display anything.
function siteWideMessage()
{
global $dbh;
$siteMessage = "";
$sUserInfo = $dbh->prepare("
SELECT acknowledgement
FROM user
WHERE uid = :uid
");
$sUserInfo->bindValue(":uid", $_SESSION["uid"]);
if ($sUserInfo->execute()) {
$res = $sUserInfo->fetch();
if ($res["acknowledgement"] = false) {
$stmt = $dbh->query("
SELECT message
FROM SiteWideMessages
ORDER BY idSiteWideMessages DESC
LIMIT 1
");
while ($row = $stmt->fetch()) {
$siteMessage .= "
<div class='siteMessage'>
<span>" . $row["message"] . "</span>
<br><br>
<span style='font-weight:normal;'>I acknowledge that I have read this important site message</span>
<br>
<input type='submit' name='submit' value='I Agree'></input>
</div>";
}
}
$sUserInfo->closeCursor();
}
if (isset($_POST["submit"])) {
$stmt = $dbh->prepare("
UPDATE user
SET `acknowledgement` = 'true'
WHERE uid = :uid
");
$stmt->bindValue(":uid", $_SESSION["uid"]);
if($stmt->execute()) {
$stmt->closeCursor();
}
}
return $siteMessage; }
UPDATE:
I managed to get it working the way I want it to I just had to do as the following.
if ($res["acknowledgement"] == 'false')
Thanks for everyone's help!
You are missing an = in your if statement. It should be:
...
if ($res["acknowledgement"] === false) {
...

if else condition 'else' is not working

/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}

PHP $result = mysql_query($query) returns true even if there is no value in database

I have the following code.
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus=$HealthStatus";
$result = mysql_query($query);
echo $HealthStatus;
if($result = false)
{
//do something
}
else
{
//print value already exists
}
I don't get any error or warning when the code is executed. But, even if $HealthStatus exists in database, the if part gets executed. When I give echo $HealthStatus, the value fetched is printed correctly.
I have tried using if(!$result). That doesn't work either. Can someone help me.
You have to use mysql_num_rows to know if the query returned any rows, eg:-
if($result && mysql_num_rows($result))
{
// a row exists
}
else
{
// do something
}
also if HealthStatus is a string it needs to be enclosed in quotes eg:-
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus='".$HealthStatus."'";
$result = mysql_query($query);
if($result && mysql_num_rows($result))
{
// a row exists
$row=mysql_fetch_array($result);
echo "Health status was ".$row["HealthStatus"];
}
else
{
// do something
echo "There were no rows found";
}
To understand how much rows were received use mysql_num_rows function.
if(mysql_num_rows($result) > 0) {
} else {
}
Also, you have error in your if:
if($result = false)
{
//do something
}
else
{
//print value already exists
}
You assign false to $result in your if statement.
You have to use if($result == false).
To avoid such mistakes you can change order:
if(false == $result)
This will work, but this:
if(false = $result)
Will cause error.
Hope, this will help.

Categories