Else block not executing - php

I have a php script, with if and else blocks. Both contain echo statements only. The if block executes perfectly but when the else block executes nothing at all is printed to screen (not even the echo statements OUTSIDE the blocks). I have tried many things such as capitalising the ELSE statement, checking all the braces are there, double and triple checking the syntax to no avail. Please help.
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
$usr = mysql_real_escape_string($_POST['****ID']);
// Retrieve email address and message from database according to user's input
$query = "SELECT * FROM users WHERE username = '$usr'";
$result = mysql_query($query) or die(mysql_error());
// Put the id numbers in array $row
$row = mysql_fetch_array($result) or die(mysql_error());
// Test for ID match
if (mysql_num_rows($result) == 1)
{
echo 'The email address of ';
echo $usr;
echo ' is: ';
echo $row['email'];
echo '<p>Message: ';
echo $row['firstname'];
}
else
{
echo 'Sorry it appears that ';
echo '$usr';
echo ' has not registered yet. Why dont you tell him about ****Jacker?';
}
// Executing outside if..else blocks for testing
echo 'Sorry, it appears that ';
echo '$usr';
echo ' has not registered yet. Why dont you tell him about ****Jacker?';
?>

You will have an error in
$row = mysql_fetch_array($result) or die(mysql_error());
Since the number of results is zero, your script will print a warning. Depending on your configuration, it's possible you see a white-page in stead of the warning.
Please note the
or die(..)
part.
Since the first part failed (fetching an empty result), the script will die and stop. No code lower than this line will be executed, so no logs, no if, ...
Best solution is to put the fetch_array inside the if (mysql_num_rows(..) == 1 statement, so we are sure there is at least 1 user to fetch

Related

PHP If Else statement not working for database

Ok, I'm confused. I have some code that searches a database table for a username, and then uses an if else statement to run some code depending on if the user is found or not. My code is below. The problem is that the code isn't even seeing the if else statement, and I have no idea why. Any help is appreciated.
$sqluser = "select * from users where username='" . $user ."'"; //Searching to see if the user is in the database
echo $sqluser . "<br><br>"; //writes out the select statement to make sure it is correct
$query = mssql_query($sqluser); //returns the results
$num_rows = mssql_num_rows($query); //gets the number of rows returned
echo $num_rows; //writes out the number of rows
if ($num_rows==0) //determines what happens next if the user exists or not
{
//displays an error box if the user doesn't exist
echo "<script type=text/javascript>";
echo "alert('That user doesn't exist. Please try again.')";
echo "</script>";
}
else
{
//will be code to run if the user does exist
echo "<script type=text/javascript>alert('Testing.')</script>";
}
I couldn't add a comment. So I will write this as an answer instead.
Since you state that the alert JavaScript is showing in the page source, this mean that the IF/ELSE statement in PHP is working fine. The problem is with the single quote. You have a single quote inside a single quoted alert function. Hence the JavaScript alert function cannot be executed.
echo "alert('That user doesn't exist. Please try again.')";
Try using this instead
echo "alert('That user doesn\'t exist. Please try again.');";

Check if post exists

So i want to check if a post exists in the database but i have some problems with redirection.
This is my work so far:
echo '<br>';//the $row part tells the DB what post his looking on
echo 'View comments';
This is the show comment button that leads to the section where you see the comments for the post.
<?php
require_once ('checkp.php');
I have it to require the post checking script once.
<?php
include ('variables.php');
//connects to DB
$dbc=mysql_connect($host,$user,$pass);
if ($dbc) {
} else {
echo ('Failed to connect to MySql; '. mysql_error());
}
//selects db from MySQl
$sqldb=mysql_select_db('a2318052_blog');
$pid=$_GET['post_id'];
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
if ($sql) {
} else {
echo "cant run query";
}
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
?>
And this is the script that checks for a empty result and then redirects back. I believe its something with the redirect here (header ("location: comments.php?post_id='. $pid.'");)
You mixed the quotes on the redirect:
"location: comments.php?post_id='. $pid.'"
should be
"location: comments.php?post_id=". $pid
The dot in php is used to concatenate strings. Bu there you are opening the string with " and closing it with '.
EDIT : Also as someone else already noticed you're using query instead of query1.
Also i suppose instead of:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
you wanted something else:
if (mysql_num_rows($sql) == 0) {
echo "that post does not exist!";
You probably don't want single quotes around the post_id...
header ("location: comments.php?post_id=$pid");
first change pid
$pid = intval($_GET['post_id']); // for security
after that
if (mysql_num_rows($sql) == 0)
{
echo "that post does not exist!";
}
else
{
header("Location: comments.php?post_id=".$pid);
}
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
You're using $query instead of $query1. That's probably the problem (along with the concatenation stuff other users have pointed out).
There's also a few other things, like I think you mixed up your if/else statement here:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
Maybe you want the order to be reversed?
Also, you should look into avoiding SQL injection!
Sending a query with a $GET variable is pretty dangerous, as users can manipulate the URL and send malicious queries.
$pid=$_GET['post_id'];
Prepared statements are ideal, but for now, you could use mysql_real_escape_string around your $GET variable. It stops people from sending queries you really don't want done.

check if row mysql exist with php

i'm trying to check if a row exist in my database using php, and the problem is that i can't understand what i wrong, this is the code:
while ($db_field = mysql_fetch_assoc($result))
{
print "||" . $db_field['id_n']."||".$db_field['network_name']."||".$db_field['country']."||".$db_field['country_Name']."||"."<BR>";
$query = "SELECT * FROM countries WHERE english_name='$db_field['country_Name']'";
$doquery = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($doquery))
{
print 'Found';
} else {
print 'Not Found';
}
}
if i write these i receive no output, and also no error, i try to insert some print in the code at the start of my php or in the middle but no print is displayed, so i found that the error is in this line:
$query = "SELECT * FROM countries WHERE english_name='$db_field['country_Name']'";
my question is, what is the error, and why display anything, i'd like it display an error or something else, or just print me the log i put in the code but nothing, seems that the php is blank, anyone can explain me these please?

trying to set session variable

if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.

Session variables in PHP

Hey guys, Im doing a series of if statements based on a session variable that is set (which looks at a value in the DB and then decides whether to empty the session, or name it. However I'm having problems in that the session is always named, regardless of whether the record in the database is '0' or not. The query works fine when run in mysql. Here's the code:
session_start();
$_SESSION['MemberType'] = '';
mysql_select_db($database_choices, $choices);
$query = "Select lifemember from registrants where username = '" . $_SESSION[kt_login_user] . "'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
while($row = mysql_fetch_array($result))
{
if ($row['lifemember'] == '1')
{
$_SESSION['MemberType'] = 'LifeMember';
}
else if($row['lifemember'] == '0')
{
$_SESSION['MemberType'] = '';
}
}
Precheck: If you are getting any 'Headers already sent...' then you have some output already on the page which is preventing the setting of session.
Otherwise try debugging steps like:
1) Do an echo $row['lifemember'] inside the while loop so that you know REAL value of what's been fetched from DB.
2) In else block, change it to $_SESSION['MemberType'] = 'Hello'; Then see, whether Hello is printed or not?

Categories