...

View Full Version : News Script problems



elitis
05-30-2011, 02:25 AM
I have a news script which is only suppose to allow admins to edit,delete, add, etc news. Anyone else the script is suppose to redirect. My problem is that the script redirects me even though I am an admin. I've tried !=4 as well but still have problems.


$level = get_level();
if ($level <=4)
header('Location: http://www.example.com/');


function get_level()
{
$sql = mysql_query("SELECT level from users WHERE userid='" . $_SESSION['userid'] . "'") or die(mysql_error());
$result = $sql;
mysql_fetch_array($result);
}

This is the entire script.

<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if ($level <=4)
header('Location: http://www.example.com/');
?>

<?php
if (empty($_POST['title']))
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if (empty($_POST['news']))
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = @mysql_query($query);
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

?>

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="TRUE" />
</form>

Old Pedant
05-30-2011, 03:56 AM
Your function never returns any value at all, let alone the value of the level from the array.

elitis
05-30-2011, 05:02 AM
Your function never returns any value at all, let alone the value of the level from the array.

how would I get it to return a value? I've already tried
echo $row['level']

bullant
05-30-2011, 05:05 AM
$level = get_level();
if ($level <=4) header('Location: http://www.example.com/');

Looks like you just need to do some Basic Debugging 101 (http://www.codingforums.com/showthread.php?p=1082858#post1082858)

echo the value of $level that is being returned and I think you'll find an issue there.



$level = get_level();
echo 'level = '.$level; die();
if ($level <=4) header('Location: http://www.example.com/'); (http://www.example.com/%27%29;)

Old Pedant
05-30-2011, 07:03 AM
Bullant just repeated what I said.

I'm not a PHP person, but as I said, you need to RETURN a value from your function.

Remembering that I don't use PHP, but that I can read manuals, I think you need this:


function get_level()
{
$result = mysql_query("SELECT level from users WHERE userid='" . $_SESSION['userid'] . "'") or die(mysql_error());
$row = mysql_fetch_array($result);
$level = $row[0];
mysql_free_result($result);
return $level;
}


Based on reading this:
http://www.php.net/manual/en/function.mysql-fetch-array.php

Old Pedant
05-30-2011, 07:06 AM
Actually, for completeness you probably want this:


function get_level()
{
$result = mysql_query("SELECT level from users WHERE userid='" . $_SESSION['userid'] . "'") or die(mysql_error());
$level = 0; // assume the userid isn't found?
if ( $row = mysql_fetch_array($result) ) {
$level = $row[0]; // only get the level is there was at least one record
}
mysql_free_result($result);
return $level;
}

bullant
05-30-2011, 08:03 AM
Bullant just repeated what I said.



I did more than that. I showed the op how he/she could check for themself where the problems are.

Since you admit you don't use php then if you want to risk misleading op's like you did in another thread (http://www.codingforums.com/showthread.php?p=1094931&highlight=pedant%27s#post1094931) (post 2), where your suggested code was riddled with errors, that is up to you. It's not my role to go round cleaning up your php mistakes when you make them ;)

Old Pedant
05-30-2011, 07:22 PM
All you did was show him code that would have echoed out a completely blank value for $level, since his get_level() code was returning nothing.

It was a correct comment, but pretty much useless to him if he doesn't know how to return a value from a function and/or get a value from a SQL query.

I was HOPING that you would correct my PHP if it's wrong and show him how to return an actual value.

Instead, you take me to task for attempting an answer. If it's wrong, it's wrong. But at least it's an answer.

bullant
05-31-2011, 12:08 AM
I also posted a link showing how I go about testing/debugging my code.



I was HOPING that you would correct my PHP if it's wrong and show him how to return an actual value.


As I said, it's not my role to go behind you cleaning up your code.

You have posted code that has turned out to be garbage on too many occasions for me to justify wasting my time checking your code. (Blue52's factorising thread and the link I posted earlier).

If you can't handle your code with errors in it being highlighted here and elsewhere then maybe consider getting it right before you post it or don't post it at all. I assume you are prepared to stand by whatever you post.

If you are genuinely interested in learning php and not post error riddled code then maybe Read This For More (http://php.net/manual/en/index.php)

Old Pedant
05-31-2011, 09:20 PM
I have ZERO interest in learning PHP.

The same way you have zero interest in being TRULY helpful and instead enjoy attacking people more than helping others.

MattF
06-01-2011, 12:03 AM
As I said, it's not my role to go behind you cleaning up your code.

When someone doesn't know PHP yet is trying to help the O.P with the skills they have available to them, it's a common courtesy for someone more experienced in a certain area to step in and help.

Anyhow, with regards to the function:



function get_level()
{
$result = mysql_query('SELECT level from users WHERE userid=\''.$_SESSION['userid'].'\'') or die(mysql_error());

return ((mysql_num_rows($result)) ? mysql_result($result, 0) : 0);
}


Then change this part:



$level = get_level();
if ($level <=4)


to:



if (get_level() <= 4)


No use assigning it to a var when that's the only place you use it.

bullant
06-01-2011, 12:25 AM
I have ZERO interest in learning PHP.

The same way you have zero interest in being TRULY helpful and instead enjoy attacking people more than helping others.

no problem - you are entitled to an opinion :)

I just call it as I see it.

bullant
06-01-2011, 12:34 AM
When someone doesn't know PHP yet is trying to help the O.P with the skills they have available to them, it's a common courtesy for someone more experienced in a certain area to step in and help.


Yes that is true, but when someone posts garbage code on more than 1 occasion I refuse to waste more time cleaning up after them.

It's a question of priorities for me. I would prefer to spend time helping someone else directly rather than clean up someone else's "solution" that contains errors. Imo everyone should take responsibility for their own posts and be accountable for them.

Like I said, it's not my role at all to go cleaning up other peoples "solutions". Maybe it's the moderators' or some other members' role:confused:

If you take Old pedant's opinion
If it's wrong, it's wrong. But at least it's an answer.that sounds a bit narcissistic to me.

If everyone took the attitude that any answer, correct or not, is better than no answer then the forums would be riddled with rubbish.

bazz
06-01-2011, 03:53 AM
This is the MySql forum all said and done.

If the OP requires php help, then it would've been better to move the thread to the php forum.

If the question involved both, php and MySQL, then the MySql could be fixed here and the OP then sent to the php forum for other assistance. It makes much more sense doing it that way when others may come to CF later to search for stuff. otherwise why should there be numerous forums.

If we look back at Old_Pedants many previous threads, it is clear that any php 'advice' is a pointer at least and imho, is therefore useful even if not conclusive.


my 2c.

bullant
06-01-2011, 04:16 AM
yep :), agree this is more of a php issue.

Old Pedant made an unconditional statement saying he hoped I would correct any errors in his code.

I simply gave an honest reason, with supporting evidence (Blue52's factorising thread and the link I posted earlier), why I won't waste anymore time cleaning up after Old Pedant.

If people want to post "solutions" about something they know little about, that is fine :). But imo they still should take responsibility for any errors they post and be accountable for them and not "hope" (as old pedant appears to) that I or someone else will come up behind them to clean up any errors. I refuse to clean up after them since it does nothing more than waste my time.

If someone else (moderators or other members) has the time and is willing to clean up after Old Pedant, or anyone else for that matter, I have no issue with that all :).

elitis
06-01-2011, 09:31 PM
oops. sorry guys. Its always when I think something is a mysql problem its really a php problem... Someone told me about debugging in another thread of mine. I just wish I knew when to debug. And I feel like such a noob when it comes to programming. e.g returning values. But thanks anyway for all your help guys. I really appreciate it.:thumbsup:

@bullant: you were correct. The script isn't echoing any level. So this is where my problem resides.

MattF
06-01-2011, 09:57 PM
The script isn't echoing any level. So this is where my problem resides.

Obviously, and it will continue to fail to do so unless you update that function as advised.

bullant
06-02-2011, 12:03 AM
@bullant: you were correct. The script isn't echoing any level. So this is where my problem resides.

no problem :)


I just wish I knew when to debug.

Basically whenever something isn't working correctly, you need to find the source of the problem and fix it. The process is called debugging.

I posted how I generally go about coding/testing in this thread (http://www.codingforums.com/showthread.php?p=1082858#post1082858). Essentially, "Code a little, test a lot"

bazz
06-02-2011, 12:14 AM
Essentially, "Code a little, test a lot"

in the 'olden' days (gawd I have reached that stage :( ), carpenters, joiners etc would have used the expression 'measure twice, cut once'.

same principle.

bullant
06-02-2011, 12:28 AM
in the 'olden' days (gawd I have reached that stage :( ), carpenters, joiners etc would have used the expression 'measure twice, cut once'.

same principle.

yep :) I've heard that expression as well and use it myself when fixing things around the house :thumbsup:

elitis
06-02-2011, 10:47 AM
no problem :)



Basically whenever something isn't working correctly, you need to find the source of the problem and fix it. The process is called debugging.

I posted how I generally go about coding/testing in this thread (http://www.codingforums.com/showthread.php?p=1082858#post1082858). Essentially, "Code a little, test a lot"

yea I read that thread. Seems like that would be obvious but guess not considering I'm here :)

As for my function: Didn't have the variable there when I added in your echo, which I guess is why it just echoed," level =". Now, after readding in the variable it says my level is 4 (the admin level). Was it really the variable that made it work correctly, or am I overlooking something? Or was it the echo? Because once I remove the echo part the script redirects me.

These are all with the echo intact:
EDIT: Now getting: Cannot modify header information - headers already sent by (output started at /home/xtraz/public_html/test/news/post_news/index.php:7) in /home/xtraz/public_html/test/news/post_news/index.php on line 8 Guessing this is because of the redirect header?

It also echoes these as soon as the page is done loading:
You need to enter a title.

You need to enter a message.

Error #101: News could not be added. Please try again

bullant
06-02-2011, 11:28 AM
Without seeing your updated code, I'm not sure what you have done.

But the header() will not work if any output (echo statements, html etc) has been generated before header() is called.

If you are now getting a valid value for $level, then delete any echo statements before header() and also make sure your include() files do not generate any output when their include() is called.

elitis
06-03-2011, 11:26 AM
Without seeing your updated code, I'm not sure what you have done.

But the header() will not work if any output (echo statements, html etc) has been generated before header() is called.

If you are now getting a valid value for $level, then delete any echo statements before header() and also make sure your include() files do not generate any output when their include() is called.


function get_level()
{
$result = mysql_query("SELECT level from users WHERE userid='" . $_SESSION['userid'] . "'") or die(mysql_error());
$level = 0; // assume the userid isn't found?
if ( $row = mysql_fetch_array($result) ) {
$level = $row[0]; // only get the level is there was at least one record
}
mysql_free_result($result);
return $level;
}


<?php
session_start();
include "database.php";
include "functions/index.php";
$level = get_level();
echo 'level = '.$level;
if (get_level() <= 4)
header('Location: http://www.example.com/');
?>

<?php
if (empty($_POST['title']))
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if (empty($_POST['news']))
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = @mysql_query($query);
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

?>

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="TRUE" />
</form>

if I remove that echo the script redirects me. But if I keep it I get the header error but am on the news page.

bullant
06-03-2011, 01:04 PM
That is what is supposed to happen as far as I can tell without actually running your code.

In my previous post I suggested



But the header() will not work if any output (echo statements, html etc) has been generated before header() is called.

If you are now getting a valid value for $level, then delete any echo statements before header() and also make sure your include() files do not generate any output when their include() is called.

elitis
06-03-2011, 09:58 PM
That is what is supposed to happen as far as I can tell without actually running your code.

In my previous post I suggested

I have deleted output before header() but the only output is echo 'level = '.$level; and if I delete that the script redirects me. This is only supposed to happen if the user's level is below 4. But according to my database, and that echo, (and well obviously my memory of making my level 4) my level is 4. So, it is supposed to keep me on the news page. Again, this only happens if I delete the output, which is that echo.

bullant
06-04-2011, 02:57 AM
This is only supposed to happen if the user's level is below 4.

so why have you got


if (get_level() <= 4)
header('Location: http://www.example.com/'); (http://www.example.com/%27%29;)

<= is less than or equal to.

bullant
06-04-2011, 03:01 AM
I find it humorous that the code that bullant told me was utter crap.....

Now you are resorting to posting blatant unthruths. Post the thread and post number where you claim I made that statement.

I didn't even look at the code you originally posted in this thread and I haven't referred to it at all because as I posted earlier (with supporting evidence) you have posted code in the past that has turned out to be total garbage on too many occasions for me to waste anymore time cleaning up after you.

bullant
06-04-2011, 04:56 AM
From the feedback I have got so far, you are the only one who seems to have "misunderstood" what was clear to others.

MattF
06-04-2011, 05:15 AM
From the feedback I have got so far, you are the only one who seems to have "misunderstood" what was clear to others.

Oh good grief. Pack it in ladies. We'll be running out of handbags at this rate. :D On the above point you make though, you appear to be the one who took your meaning any other way than that you are slagging off Old Pedant's coding. If you don't like each other, ignore. Simple as. This is reaching playground level now though. No-one is either asking or forcing you to clean up anyone elses code. Neither do you need to slag it off in the process, either.

Also, to the O.P, the code you are being given is to help and guide. That doesn't mean people are here to wipe your arse and write every single line point perfect for you. Pay attention to the code and find the minor errors by putting in a tad of effort yourself.

bullant
06-04-2011, 05:21 AM
No-one is either asking or forcing you to clean up anyone elses code.

yep not actually "asking" but Old Pedant did say (post 8)


I was HOPING that you would correct my PHP if it's wrong...... and I gave an honest answer why I refuse to.

Yes it was slagging the garbage he had posted in the past and I provided the supporting evidence and is the reason I will not waste anymore time looking at his code or correcting any errors.

It's as simple as that :)

MattF
06-04-2011, 05:29 AM
For the benefit of everyone, in future just ignore what you don't like rather than giving an indepth explanation. This type of bickering serves no purpose other than to clutter a thread with irrelevant and useless text.

elitis
06-04-2011, 05:22 PM
so why have you got


if (get_level() <= 4)
header('Location: http://www.example.com/'); (http://www.example.com/%27%29;)

<= is less than or equal to.

ah, thought it was just less than

Oh good grief. Pack it in ladies. We'll be running out of handbags at this rate. :D On the above point you make though, you appear to be the one who took your meaning any other way than that you are slagging off Old Pedant's coding. If you don't like each other, ignore. Simple as. This is reaching playground level now though. No-one is either asking or forcing you to clean up anyone elses code. Neither do you need to slag it off in the process, either.

Also, to the O.P, the code you are being given is to help and guide. That doesn't mean people are here to wipe your arse and write every single line point perfect for you. Pay attention to the code and find the minor errors by putting in a tad of effort yourself.

I have been trying to find errors, but obviously as you can see I'm not the best at programming. I merely misunderstood <= was less than or equal to

EDIT: ok so now how would I get the script to echo: "You need to enter a title.

You need to enter a message.

Error #101: News could not be added. Please try again." after the submit has been pressed. I've tried isset() but it still echoes all of that after the page loads.


<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
header('Location: http://www.example.com/');
?>

<?php
if (empty($_POST['title']))
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if (empty($_POST['news']))
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = @mysql_query($query);
}

if (isset($_POST['submit']))
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

?>

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="TRUE" />
</form>

NVM. Thanks for all your help guys

EDIT 2: How would I get it to stop echoing "Error #101: News could not be added. Please try again." until the problem actually occurs. Right it just echoes that after the page loads. It also echoes this every time I try to add news.


<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
header('Location: http://www.example.com/');
?>

<?php
if ($_POST['title'] = "")
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if ($_POST['news'] = "")
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = @mysql_query($query);
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

?>

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="TRUE" />
</form>

MattF
06-04-2011, 06:06 PM
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}


A header call doesn't terminate the script. You need the exit() call.

As to the other issue, add a hidden input with a value of 1 and check for that value when you submit. Enclose all of your form and processing code within an if block so that it will only run if the form has been submitted.



<input type="hidden" name="form_sent" value="1"/>


Then:



if (!empty($_POST['form_sent']))
{
[processing and form code here]
}

elitis
06-04-2011, 06:41 PM
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}


A header call doesn't terminate the script. You need the exit() call.

As to the other issue, add a hidden input with a value of 1 and check for that value when you submit. Enclose all of your form and processing code within an if block so that it will only run if the form has been submitted.



<input type="hidden" name="form_sent" value="1"/>


Then:



if (!empty($_POST['form_sent']))
{
[processing and form code here]
}


Wouldn't enclosing all of the processing and form code into an if block cause an error since most of the processing code is already if statements? Never mind, guess I was thinking of if else elseif. This is the updated code but I am still getting:
Error #101: News could not be added. Please try again. at page load. Also after submitting another test entry it says news successfully added but nothing is added into the database table.


<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}
?>

<?php
if (!empty($_POST['submitted']))
{
if ($_POST['title'] = "")
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if ($_POST['news'] = "")
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = @mysql_query($query);
}

echo '<p>News was successfully added!</p>';
} else
echo '<p>Error #101: News could not be added. Please try again.</p>';
?>

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="1" />
</form>

MattF
06-04-2011, 06:45 PM
Nope. It's an encompassing block.



<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}

if (!empty($_POST['form_sent']))
{ # New if clause.

if ($_POST['title'] = "")
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if ($_POST['news'] = "")
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = mysql_query($query) or die(mysql_error());
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> # DO NOT use an unsanitised PHP_SELF.

<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="form_sent" value="1"/>
</form>
<?php

} # End of new clause.

?>



Edit: Don't use error suppression.

elitis
06-04-2011, 07:03 PM
Nope. It's an encompassing block.



<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}

if (!empty($_POST['form_sent']))
{ # New if clause.

if ($_POST['title'] = "")
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if ($_POST['news'] = "")
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = mysql_query($query) or die(mysql_error());
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> # DO NOT use an unsanitised PHP_SELF.

<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="form_sent" value="1"/>
</form>
<?php

} # End of new clause.

?>



Edit: Don't use error suppression.

now I'm just getting a blank screen. No errors, but a blank screen. Is it because of the '!' in the bolded line?

MattF
06-04-2011, 07:15 PM
<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}

if (!empty($_POST['form_sent']))
{ # New if clause.

if ($_POST['title'] = "")
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if ($_POST['news'] = "")
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = mysql_query($query) or die(mysql_error());
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

} # End of new clause.

?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> # DO NOT use an unsanitised PHP_SELF.

<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="form_sent" value="1"/>
</form>

elitis
06-04-2011, 07:22 PM
<?php
session_start();
include "database.php";
include "/functions/index.php";
$level = get_level();
if (get_level() != 4)
{
header('Location: http://www.example.com/');
exit(0);
}

if (!empty($_POST['form_sent']))
{ # New if clause.

if ($_POST['title'] = "")
echo '<p>You need to enter a title.</p>';
else
$title = $_POST['title'];

if ($_POST['news'] = "")
echo '<p>You need to enter a message.</p>';
else
$news = $_POST['news'];

if ($title && $news) {
$query = "INSERT INTO news (title, news, date) VALUES ('$title', '$news', NOW())";
$result = mysql_query($query) or die(mysql_error());
}

if ($result)
echo '<p>News was successfully added!</p>';
else
echo '<p>Error #101: News could not be added. Please try again.</p>';

} # End of new clause.

?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> # DO NOT use an unsanitised PHP_SELF.

<input type="input" name="title" size="25" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; else echo 'Title'; ?>" />
<textarea rows="7" cols="55" name="news"><?php if (isset($_POST['message'])) echo $_POST['message']; else echo 'News Message'; ?></textarea>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="form_sent" value="1"/>
</form>


wow thats weird. It works now. Was mysql_error() the only thing you added?
EDIT: It appeared to work. But now it says it couldn't add the news entry after trying to add it. To clarify, it doesn't echo it after page load but it now echoes after any news entry I try to add.
Huh I can't find anything wrong in the code.

MattF
06-04-2011, 07:50 PM
Look harder. :) The code is to give you the general base. You still need to work on the code though. Check the overall logic. The script needs some work still.

elitis
06-04-2011, 07:58 PM
Look harder. :) The code is to give you the general base. You still need to work on the code though. Check the overall logic. The script needs some work still.

guess that means its time to debug :D

bullant
06-04-2011, 11:59 PM
I have been trying to find errors, but obviously as you can see I'm not the best at programming.

Everyone was a "beginner" at some stage and you never really stop learning with new technologies and techniques becoming available all the time.

To not waste a lot of time coding, good debugging skills is essential. Some Basic Debugging 101 (http://www.codingforums.com/showthread.php?p=1082858#post1082858).

elitis
06-05-2011, 12:52 AM
Got it! :) Just moved variables to top instead of in the if statements and changed one of the form field's I found from message to news. Thanks guys. Now, on to editing and deleting news entries... :( Might be seeing you guys again. But I'll "code a little, and test a lot" ;)

bullant
06-05-2011, 01:00 AM
But I'll "code a little, and test a lot" ;)
___:)

elitis
06-05-2011, 01:55 AM
___:)

hehe

EDIT: quick question. Just finished with delete news page and edit news page and they work perfectly. But on the home page how would I get the edit/delete links to display only if your level is 4. Even though those two pages will redirect you to the homepage if your level isn't 4 I still don't want the links to display.

Heres the code for the homepage. After this I'm completely done with the news system (except for adding a design)


<?php
session_start();
include('includes/database.php');
include('functions/index.php');
if ($_SESSION['loggedin'] == 0)
{
header('Location: http://blah.com/');
exit();
}
?>

<head>
<link href="../style.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../images/homepage.png"/>
<title> - Home</title>
</head>

<body>

<div id="logo">
<!-- Start Logo -->
<img src="/images/blah.png" alt="Destination X" />
</div>
<!-- End Logo -->

<ul id="nav">
<!-- Start Navigation -->
<a href="http://blah.com" target="_blank"> <img src="../images/Home.png" border="0"></a>
<a href="http://blah.com" target="_blank"> <img src="../images/play2.png" border="0"></a>
<a href="http://blah.com" target="_blank"> <img src="../images/connect.png" border="0"></a>
<a href="http://blah.com" target="_blank"> <img src="../images/redeem.png" border="0"></a>
</ul>
<!-- End Navigation -->

<div id="frame">
<!-- Start Frame -->
</div>
<!-- End Frame -->

<div id="signininfo">
<!-- Start SigninInfo -->
<div class="name">
<!-- Start Name -->
<?php
if ($_SESSION['loggedin'] == 1) {
echo "Hello, ";
find_name();
}
?>
</div>
<!-- End Name -->
<br>
<a href="http://blah.com/">My Account</a> | <a href="http://blah.com/">Sign Out</a>
</div>
<!-- End SigninInfo -->

<div id="sidecontent">
<!-- Start Side Content -->

<div class="fullname">
<?php
echo find_name();
echo last_name();
?>
</div>

<div class="subnavleft">
<ul id="subnavleft">
<li><a href="#">Alerts</a></li>
<li><a href="#">Connections</a></li>
<li><a href="#">Photos</a></li>
</ul>
</div>

<h3><u>About Me</u></h3>
<!-- End Side Content -->
</div>


<div id="content">
<!-- Start Content -->
<div class="subnavtop">
<input type="button" class="button" value="All" />
<input type="button" class="button" value="Mine" />
<input type="button" class="button" value="Friends" />
<input type="button" class="button" value="News" />
</div>
<hr>

<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}
<a href='/news/edit_news?newsid=$news[ID]'>Edit</a>
<a href='/news/delete_news?newsid=$news[ID]'>Delete</a>
<hr>
</div>";
}
}
else
{
print "<div style='text-align:justify;'>
<h2>No News</h2>
<p>There is currently no news to report.</p>
</div>";
}
?>

</div>
<!-- End Content -->

<div id="footer">
<!-- Start Footer -->
<div class="footer">
<a href="http://blah.com">Terms of Service</a> | <a href="http://blah.com">About</a> |
<a href="http://blah.com/faq/">FAQ</a> | <a href="http://blah.com">Testimonials</a> |
<a href="http://blah.com/contact/">Contact Us</a></div>
<div class="ptz"><?php echo get_points(); echo " <b>PTZ</b>"; ?> </div>
</div>
<!-- End Footer -->

bullant
06-05-2011, 02:20 AM
But on the home page how would I get the edit/delete links to display only if your level is 4.

You could use an IF statement to check the value of $level and if it is the required value, then print/echo the links etc.

elitis
06-05-2011, 03:08 AM
You could use an IF statement to check the value of $level and if it is the required value, then print/echo the links etc.

tried that but links still appeared on a second account I made with a level of 1. It also echoed "echo edit;" as plain text and echoed "Delete" as a link. Guess I did something wrong, but are there any other ways?

bullant
06-05-2011, 04:16 AM
Guess I did something wrong,....

Without posting your code I'm not sure how you expect anyone to help you fix it.

elitis
06-05-2011, 04:49 AM
Without posting your code I'm not sure how you expect anyone to help you fix it.


<?php
session_start();
include('/includes/database.php');
include('/functions/index.php');
$level = get_level();
if ($_SESSION['loggedin'] == 0)
{
header('Location: http://www.example.com/');
exit();
}
?>

<head>
<link href="../style.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../images/homepage.png"/>
<title>- Home</title>
</head>

<body>

<div id="logo">
<!-- Start Logo -->
<img src="/images/example.png" alt="Destination X" />
</div>
<!-- End Logo -->

<ul id="nav">
<!-- Start Navigation -->
<a href="http://example.com/" target="_blank"> <img src="../images/Home.png" border="0"></a>
<a href="http://example.com" target="_blank"> <img src="../images/play2.png" border="0"></a>
<a href="http://example.com" target="_blank"> <img src="../images/connect.png" border="0"></a>
<a href="http://example.com/" target="_blank"> <img src="../images/redeem.png" border="0"></a>
</ul>
<!-- End Navigation -->

<div id="frame">
<!-- Start Frame -->
</div>
<!-- End Frame -->

<div id="signininfo">
<!-- Start SigninInfo -->
<div class="name">
<!-- Start Name -->
<?php
if ($_SESSION['loggedin'] == 1) {
echo "Hello, ";
find_name();
}
?>
</div>
<!-- End Name -->
<br>
<a href="http://example.com/">My Account</a> | <a href="http://example.com/">Sign Out</a>
</div>
<!-- End SigninInfo -->

<div id="sidecontent">
<!-- Start Side Content -->

<div class="fullname">
<?php
echo find_name();
echo last_name();
?>
</div>

<div class="subnavleft">
<ul id="subnavleft">
<li><a href="http://example.com">Alerts</a></li>
<li><a href="http://example.com">Connections</a></li>
<li><a href="http://example.com">Photos</a></li>
</ul>
</div>

<h3><u>About Me</u></h3>
<!-- End Side Content -->
</div>


<div id="content">
<!-- Start Content -->
<div class="subnavtop">
<input type="button" class="button" value="All" />
<input type="button" class="button" value="Mine" />
<input type="button" class="button" value="Friends" />
<input type="button" class="button" value="News" />
</div>
<hr>

<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}
<?php if ($level = 4) { echo '<a href='/news/edit_news?newsid=$news[ID]'>Edit</a>';
echo '<a href='/news/delete_news?newsid=$news[ID]'>Delete</a>'; } ?>
<hr>
</div>";
}
}
else
{
print "<div style='text-align:justify;'>
<h2>No News</h2>
<p>There is currently no news to report.</p>
</div>";
}
?>

</div>
<!-- End Content -->

<div id="footer">
<!-- Start Footer -->
<div class="footer">
<a href="http://example.com/terms/">Terms of Service</a> | <a href="http://example.com/about/">About</a> |
<a href="http://example.com">FAQ</a> | <a href="http://example.com/">Testimonials</a> |
<a href="http://example.com">Contact Us</a></div>
<div class="ptz"><?php echo get_points(); echo " <b>PTZ</b>"; ?> </div>
</div>
<!-- End Footer -->

this is what it echoes: Posted on: 2011-05-27 14:40:47 Edit'; echo 'Delete'; } ?>
Although in the page source it shows this:
<?php if (4 = 4) { echo '<a href='/news/edit_news?newsid=3'>Edit</a>';
echo '<a href='/news/delete_news?newsid=3'>Delete</a>'; } ?>

bullant
06-05-2011, 04:59 AM
What happened to "Code a little, test a lot"?:confused:


if (4 = 4) is always going to evaluate to true. Is that what you want? If not then all you have to do is fix the php code.

I'm not into spoon feeding so I am not going to fix it for you.

hint: have a read up on how the print statement works and comparison operators.

And why have you got php tags within php tags?



<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}
<?php if ($level = 4) { echo '<a href='/news/edit_news?newsid=$news[ID]'>Edit</a>';
echo '<a href='/news/delete_news?newsid=$news[ID]'>Delete</a>'; } ?>
<hr>
</div>";
}
}
else
...
...

elitis
06-05-2011, 05:43 AM
What happened to "Code a little, test a lot"?:confused:


if (4 = 4) is always going to evaluate to true. Is that what you want? If not then all you have to do is fix the php code.

I'm not into spoon feeding so I am not going to fix it for you.

hint: have a read up on how the print statement works and comparison operators.

And why have you got php tags within php tags?



<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}
<?php if ($level = 4) { echo '<a href='/news/edit_news?newsid=$news[ID]'>Edit</a>';
echo '<a href='/news/delete_news?newsid=$news[ID]'>Delete</a>'; } ?>
<hr>
</div>";
}
}
else
...
...
yes that is what I want. If the user's level is 4 I want it to echo the links. As for code a little, test a lot. I already know everything else works.

bullant
06-05-2011, 05:53 AM
yes that is what I want. If the user's level is 4 I want it to echo the links.

Then you need to fix your code because your code, as is, is not checking if the level is 4 or not.

The hints I posted in my previous post should point you in the right direction.

elitis
06-05-2011, 06:12 AM
Then you need to fix your code because your code, as is, is not checking if the level is 4 or not.

The hints I posted in my previous post should point you in the right direction.

I've tried all of that before I asked if there was a way to do this and none of it works.

bullant
06-05-2011, 06:16 AM
saying none of it works without posting your updated code is a bit like going to the doctor and saying I am feeling sick but I'm not going to tell you what the symptoms are and then expect the doctor to make you better.

post your updated code otherwise there is nothing more I can do and hopefully someone else will come along to give you the code.

elitis
06-05-2011, 06:19 AM
saying none of it works without posting your updated code is a bit like going to the doctor and saying I am feeling sick but I'm not going to tell you what the symptoms are and then expect the doctor to make you better.

post your updated code otherwise there is nothing more I can do and hopefully someone else will come along to give you the code.


<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}
if ($level == 4) print <a href='http://test.xtraz.cz.cc/news/edit_news?newsid=$news[ID]'>Edit</a>
print <a href='http://test.xtraz.cz.cc/news/delete_news?newsid=$news[ID]'>Delete</a>
<hr>
</div>";
}
}
else
{
print "<div style='text-align:justify;'>
<h2>No News</h2>
<p>There is currently no news to report.</p>
</div>";
}
?>

bullant
06-05-2011, 06:23 AM
It appears you haven't yet done the first part of my previous hint. When you do, your error should become obvious.


hint: have a read up on how the print statement works and comparison operators.let google be your friend :thumbsup:

elitis
06-05-2011, 06:28 AM
It appears you haven't yet done the first part of my previous hint. When you do, your error should become obvious.

let google be your friend :thumbsup:

are you talking about the difference between single and double quotes with print?

bullant
06-05-2011, 06:30 AM
print (http://php.net/manual/en/function.print.php)

elitis
06-05-2011, 06:40 AM
print (http://php.net/manual/en/function.print.php)

escaping characters?:confused: I have no clue what your trying to get at

bullant
06-05-2011, 07:09 AM
I have no clue what your trying to get at
What I said was is that it appears you haven't done the first part (the red bit) of the hint I posted. If you have done it, then your error should be obvious.


hint: have a read up on how the print statement works and comparison operators.

elitis
06-05-2011, 07:17 AM
What I said was is that it appears you haven't done the first part (the red bit) of the hint I posted. If you have done it, then your error should be obvious.

I've read up on how it works and the error is still not obvious

bullant
06-05-2011, 07:24 AM
ok, then it looks like you have bitten off more than you can chew at this stage.

So assuming you want to learn php are not just looking for someone to give you the code then maybe consider working through the w3schools php tutorials to get a grasp of the basics first before tackling a project like this.

If you are looking for someone to just give you the code, then hopefully someone else will come along to give it to you.

I can't explain things any clearer than what I posted in the Basic Debugging 101 link and the description/examples in the print link. Between the 2 links fixing your code should be pretty straight forward.

elitis
06-05-2011, 07:33 AM
ok, then it looks like you have bitten off more than you can chew at this stage.

So assuming you want to learn php are not just looking for someone to give you the code then maybe consider working through the w3schools php tutorials to get a grasp of the basics first before tackling a project like this.

If you are looking for someone to just give you the code, then hopefully someone else will come along to give it to you.

I can't explain things any clearer than what I posted in the Basic Debugging 101 link and the description/examples in the print link. Between the 2 links fixing your code should be pretty straight forward.

oh great more stuff I've already looked at... wouldn't it save me and you a lot of time if you just told me what exactly your talking about. Not give me the code. But tell me what exactly your trying to get me to see. escaping characters? difference between quotation marks?

bullant
06-05-2011, 08:00 AM
wouldn't it save me and you a lot of time if you just told me what exactly your talking about.
Like I said, I can't explain it any clearer than what I posted in the Basic Debugging 101 link and the description/examples in the print link.

Hopefully someone else will come along who can explain it clearer for you.

bazz
06-05-2011, 12:14 PM
oh great more stuff I've already looked at.


read and inwardly digest it. :) I guess you stressed so that won't help :(

post 54 elitis!

look at your 'own' print statements. see how they differ. I don;t sdo php so they may both be wrong but at least they will show you waht to look for in the link bullant sent you.

MattF
06-05-2011, 01:47 PM
Only had a brief scan through the last couple of pages, (so may have missed something), but what Bullant appears to be saying is that you are now correctly checking the status rather than assigning it, (== vs =), but your print syntax sucks and won't work. Do read the link to the print documentation he posted.

This is all part of the debugging process. You can't just jump in, code shedloads of bad code then keep getting the lip on when someone tries to guide you without doing it all for you. You have to go through every line one by one and actually look and check. Also, enable strict error reporting. Your logs will be having a field day with error messages which should keep you entertained for a while.

Coding and debugging isn't easy. It's a long, laborious learning and revision process which needs to be done from thread to needle. There are no quick ways to learn if anyone wishes to be good at what they do.

elitis
06-05-2011, 10:24 PM
not sure if I partially got what you were saying or not but I fiddled with the code a bit and got it to stop printing the whole line in the page source.

if ($level == 4) blah blah blah
Now, just need it to stop printing this to lower levels... and yes I was stressed. Its very annoying to me to work on a code again and again and never be able to get it working without having to come here and post a thousands threads. But I guess I'll have to get used to editing code multiple times before I get it working.

updated code:

<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}";
if ($level == 4) print "<a href='http://test.xtraz.cz.cc/news/edit_news?newsid=$news[ID]'>Edit</a>
<a href='http://test.xtraz.cz.cc/news/delete_news?newsid=$news[ID]'>Delete</a>
<hr>
</div>";
}
}
else
{
print "<div style='text-align:justify;'>
<h2>No News</h2>
<p>There is currently no news to report.</p>
</div>";
}
?>

EDIT: And I got it working right. I can finally close this thread... Now if I could figure out whats wrong in the registration and close that thread..
EDIT2: Sigh now its not displaying the <hr>... Ah, I see. its only displaying for users with a level of 4...
And now I can this thread. :D

MattF
06-05-2011, 11:56 PM
Glad you got it working. :) It's not awkwardness with the vague answers, btw, but merely that getting the crappy faults and working through, debugging them piece by piece, is the best way of learning. The head scratchers are one simple fact of coding, no matter how accomplished the coder. :D

bazz
06-06-2011, 12:48 AM
maybe the OP didn't update their post (2 up) but there's a syntax error in it.



if ($level == 4) { print "<a href='ht



the red bit is missing.

elitis
06-06-2011, 02:03 AM
maybe the OP didn't update their post (2 up) but there's a syntax error in it.



if ($level == 4) { print "<a href='ht



the red bit is missing.

I get a syntax error if I use {. Without it script works.

Complete working updated code:


<?php
$nq=mysql_query("SELECT * FROM news ORDER BY `date` DESC LIMIT 5");
$num=mysql_num_rows($nq);
if($num > 0)
{
while($news=mysql_fetch_array($nq))
{
print "<div style='text-align:justify;'>
<h2>{$news['title']}</h2>
<p>{$news['news']}</p><br/>Posted on: {$news['date']}";
if ($level == 4) print "<a href='/news/edit_news?newsid=$news[ID]'>Edit</a>
<a href=/news/delete_news?newsid=$news[ID]'>Delete</a>";
echo "<hr>";
echo "</div>";
}
}
else
{
print "<div style='text-align:justify;'>
<h2>No News</h2>
<p>There is currently no news to report.</p>
</div>";
}
?>

bazz
06-06-2011, 09:03 AM
except its not complete and it's not doing what you think it is.

when you added that { did you also add the closing } afterwards?

look at the containing if($num > 0){

...code ...

}

the structure is there to see.

bazz

MattF
06-06-2011, 01:04 PM
It's fine as is Bazz. If clauses don't need the braces, but the caveat is that they're limited to executing one single line of code after the comparison. This:



if (1 == 1)
print('Completed');


is exactly the same as:



if (1 == 1)
{
print('Completed');
}


The braces merely make it possible for more than one line to be associated with that clause. The reason people use them regardless of whether it's a one liner or not are for the reasons of consistency and clarity of code.

bazz
06-06-2011, 03:23 PM
I don't recall ever knowing that but, i shan't use it anyway for the reason you gave at the end; clarity :)

Thanks Matt.

bazz

bullant
06-06-2011, 08:59 PM
The braces merely make it possible for more than one line to be associated with that clause. The reason people use them regardless of whether it's a one liner or not are for the reasons of consistency and clarity of code.

Imo it's good practice to include the brackets whether you have one or many lines of code because if you originally have only 1 line and then add lines to that IF block without then also adding the brackets, you will get at least logic errors in your code.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum