How to use SELECT IFNULL in PDO? - php

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';
}

Related

php "if" without answer

This problem should be simple to resolve, but I can't...
After a request, a condition has to verify if the concerned article really exists, verifying the URL ($_GET).
My code : ( a testing file with simple echos )
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
while ($dataID = $id->fetch()) {
if (empty($dataID) or $dataID == null or !isset($dataID)) {
echo 'No content';
} else {
echo 'Can load the page';
}
}
$id->closeCursor();
The page behaviour : "can load the page" is writing when numArticle is right, but if it is not, nothing appears, neither an error message or something.
Any idea/advice? Thank you.
One way to do this is by checking the number of rows returned by mysqli:
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
if($id->num_rows > 0){
echo "can load page";
}else{
echo 'No content';
}
You can use fetchAll() function of PDO then run a foreach loop on data:
$rows = $id->fetchAll(PDO::FETCH_ASSOC);
if(!empty($rows)){
foreach($rows as $row){
echo "content";
}
}
else{
echo "No Content";
}
Assuming you are using Pdo, it looks like you want to be using Pdo's fetchColumn method.
<?php
$stmt = $db->prepare('SELECT content FROM articles WHERE idArticle = ? LIMIT 1');
$stmt->execute(array($_GET['numArticle']));
if ($result = $stmt->fetchColumn()) {
echo 'A result';
} else {
echo 'Db fetch returned false (or could be a string that evaluates to false).';
}

How do I count rows with matching id?

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
}

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 mySQL search script for website

I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !

PHP MYQSLi Returning a different value if field is empty

This should be simple.... but it's taking a while... Here's the code that's not working (it either shows nothing or the blank state message each time). $show image is the query and I know it's running fine.
// BLANK STATE TOGGLE
$result = mysqli_fetch_array($showimage, MYSQLI_ASSOC);
if($result == ''){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}
If you only want to check for the existence of rows in the result from your query, why don't you simplify it like this
// $db is your MySQLi connection object
$query = 'SELECT COUNT(1) FROM `table` WHERE `something` = ?';
$stmt = $db->prepare($query);
$stmt->bind_param('s', $something);
$stmt->execute();
$stmt->bind_result($rowCount);
$stmt->fetch();
$stmt->close();
if ($rowCount > 0) : ?>
<p>There is an image!</p>
<?php else : ?>
<p>Sorry- no image.</p>
<?php endif ?>
mysqli_fetch_array returns null if there is no match in the database. So you need to check for null.
You may need to try this:
if $showimage is your query ..
//This should run fine
//$link is ur connection
$new_result = mysqli_query($link,$showimage);
$result = mysqli_fetch_array($new_result, MYSQLI_ASSOC);
if($result == null){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}

Categories