PHP & MYSQL Return blank page - php

I'm working on the PHP and MYSQL for a project and I encountered a weird problem here where I click on the submit button at the form, it will run these codes. However the weird problem is the the page return blank instead of going back to the page with the form. I had searched for few hours for the error but couldn't find it.
Please point out my mistake. Thank you for the help.
<?php
include '../database.php';
if(isset($_POST['submit'])) {
if (isset($_POST['stuid_0'])){
$student = $_POST['stuid_0'];
//query moderator details
$query = mysql_query(" SELECT ModeratorID FROM Student WHERE StuID ='$student' ") or die(mysql_error());
$info = mysql_fetch_assoc ($query);
$dbmoderator = $info['ModeratorID'];
//check for changes of status in supervisor
$query2 = mysql_query(" SELECT SupervisorID FROM Student WHERE StuID ='$student' ") or die(mysql_error());
$value = mysql_fetch_assoc ($query2);
$dbsupervisor = $value['SupervisorID'];
$query3 = mysql_query(" SELECT LectStatus FROM Lecturer WHERE LectID ='$dbsupervisor' ") or die(mysql_error());
$value2 = mysql_fetch_assoc ($query3);
$dbsupervisorstatus = $value2['LectStatus'];
//if no changes in supervisor
if ($dbsupervisorstatus=='2'){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Moderator can't be promoted')
window.location.href='../committee/committee_supervisor2.php'
</SCRIPT>");
}
else{
//newly assigned a supervisor if previous supervisor status is not active
$query4 = "UPDATE Student SET SupervisorID='$dbmoderator', SupervisorStatus='1', ModeratorID=NULL WHERE StuID='$student'";
mysql_query($query4);
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Successfully updated')
window.location.href='../committee/committee_supervisor2.php'
</SCRIPT>");
}
}
else
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You must choose a moderator to be promoted')
window.location.href='../committee/committee_supervisor2.php'
</SCRIPT>");
}
?>
UPDATE:
I think the problem happen when the system run at this point
if ($dbsupervisorstatus=='2'){
As i put an echo "Test"; before this line and it still work.
UPDATE 2:
I found that the code can be run when I put
if ($dbsupervisorstatus=='2'){
echo "Moderator can't be promoted";
}
as well as
if($dbsupervisorstatus == 2){
header("location:commitee_supervisor2.php");
}
However I don't see the reason why my original code
if ($dbsupervisorstatus=='2'){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Moderator can't be promoted')
window.location.href='../committee/committee_supervisor2.php'
</SCRIPT>");
}
Not working.. A little help pls.. :)
FINAL UPDATE
Guys, I know why.
It's because the
window.alert('Moderator can't be promoted')
have 3 apostrophe in it.
I simply remove the word "can't" and its working already.
Thank you guys for the help :)

Using the JavaScript codes code still work but the starting point of your debugging is to echo ordinary texts at all the places where you echo JavaScript. That will help you know at what point you codes started failing. Example
//if no changes in supervisor
if ($dbsupervisorstatus=='2'){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Moderator can't be promoted')
window.location.href='../committee/committee_supervisor2.php'
</SCRIPT>");
}
Replace with
//if no changes in supervisor
if ($dbsupervisorstatus=='2'){
echo "Moderator can't be promoted";
}
Do this at all echo points then start replacing one after the other with your JavaScript codes again then you'll spot out where your code fails.

Instead of doing it through javascript, try using a much better approach in pure PHP. Something like:
if($dbsupervisorstatus == 2){
header("location:commitee_supervisor2.php");
}
And if you must use JS, then make an AJAX request, then you can manipulate the behaviour through JS anyway you like.

Where do you put your HTML form? Is it in the same page or different page? From your code, looks like there's nothing being done, so I suggest you to check whether your submit button name is correct (submit). The HTML should be like this:
<form name="your_form">
<!-- Your form here -->
<input type="submit" name="submit" value="Submit"/>
</form>

Related

PHP session ends when submit button is clicked

I want to make profile upload image for users so they can upload their own avatars on their profile...So the issue here is whenever i click the upload button session gets destroyed.
Here is the form:
if(isset($_SESSION['profileimgID'])){
echo "<form action='upload.php' method='POST' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit' name='uploadimgsubmt' class='button1'>upload</button></form>";
}
?>
partial code of upload.php file:
<?php
session_start();
include_once 'includes/dbh.inc.php';
$id = $_SESSION['profileimgID'];
if(isset($_POST['uploadimgsubmt'])){
**code code code**
if($fileError === 0){
if($filesize < 1000000){
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($filetmpname, $fileDestination);
$sql = "UPDATE profileimg SET STATUS=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?upload=success");
}
}
**code code code**
Code if user is successfully logged in, inside loginCheck.php:
session_start();
$_SESSION['userID'] = $row['idusers'];
$_SESSION['username'] = $row['uidusers'];
$cmpor = $row['idusers'];
$sql = "SELECT * FROM profileimg WHERE id";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
if($row['id'] == $cmpor){
$_SESSION['profileimgID'] = $row['id'];
}
}
header("Location: ../index.php?login=success");
exit();
}
And the last code section that is related to the problem is located to index.php:
<?php
session_start();
include_once 'includes/dbh.inc.php';
?>
**code code**
<?php
if(isset($_SESSION['profileimgID'])){
echo 'Show this content';
}else{
echo 'Show this content';
}
?>
**code code**
If i remove the 'profileimgID' to nothing ('') everything works fine but isset method doesnt hide-show the content.
If i keep it as it's isset method works fine but upload button destroys the session and user is logged out.
print_r($_SESSION) results in both index.php and upload.php if user is successfully logged in:
for user #2
Array ( [userID] => 2 [username] => popa [profileimgID] => 2 )
I checked the console for requests , when i click the upload button i get this message:
Form contains a file input,
but is missing method=POST and
enctype=multipart/form-data on the form.
The file will not be sent.
This part (isset($_SESSION['profileimgID'])) is interfering somehow with this process. When i remove it, session is maintained and it works fine upload works too.
UPDATE:
this is what i get when i click the upload-button:
https://i.stack.imgur.com/So7OD.png
this is i guess the right one ?:
https://i.stack.imgur.com/HcBqz.png
Im new to php so... sorry for my mistakes.
Exactly how are you maintaining the session-identifier now? "Sessions" rely upon a "session-id" being somehow sent from the client to the host with each exchange: normally, this is done using a cookie, but it could be done using a GET parameter (e.g. &sessionid=XXXX) It sounds to me like this information isn't being sent: the session hasn't been "destroyed," actually, but you can't find it.
Probably the fastest way to solve this is to use the network debugging features of your browser: look at the complete packet of data that's being sent, including the HTML headers (which is where cookies will be). First, look at "normal" exchanges. Then, look at the one that happens when you click that button. "Cookies" will be sent every time since they live in the header. But, if you're actually using a GET parameter to send the session-info, you'll have to do it.
Found the problem it seems like i didnt close the form on the index isset condition where logout form was located, my bad because i didnt show u guys the code :D so the problem was </form> ... pff sorry
Lesson of the day , guys always close ur </...> :)

the webpage auto-submits with previous session variables after refresh

I have a webpage that allows users to submit a query and get result in email.The user selects values for three variables and the email address. My problem is that everytime I refresh the page the form resubmits itself with old values and send the email (i.e I am not even clicking on submit query). I tried using $_POST=array() but it is still not working.
Here is my code:
<?php
if(isset($_POST['submit'])){
$varApp= $_POST['App'];
$varConfig = $_POST['Config'];
$varCtrType = $_POST['CtrType'];
$varEmail = $_POST['mailid'];
exec("/py $varApp $varConfig $varCtrType 2>&1",$output );
if ($output[8] == "Empty"){
echo "<div style ='font:22px Arial,tahoma,sans-serif;color:#ff0000'><br>No Data Available! <br></div>";
}
else {
exec(' printf "Please find attached the query result for following selection:\n\nApp: '.$varApp.' \nConfig: '.$varConfig.' \nCounter Type: '.$varCtrType.' \n\n Thanks! " | /bin/mail -s "Database Query Result" -a '.$output[8].' '.$varEmail.' 2>&1', $output2 );
echo "<div style ='font: 18px Arial,tahoma,sans-serif;color:#10ac84'><br><b> Please check your email for result !<b> <br>";
echo '<script language="javascript">';
echo 'alert("Please check your email for result! Submitted Query details: Selected App: '.$varAPP.' Configuration:")';
echo '</script>';
}
$_POST=array();
}
?>
</body>
I have not given the html part here.
So, everytime a user refreshes the page he gets an email again with previous session query results.
Any guidance here is highly appreciated.
Note: I am not using mail or pHPmailer here but that is not what I need to discuss here.
Thanks,
Taken from this answer:
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.

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.');";

After login pull data for respective users from db

M building a web app here.The authentication php code looks like this (Please ignore the threats for time being) :
<?php
session_start();
if(isset($_POST['submit']))
{
mysql_connect('localhost','*****','******') or die(mysql_error());
mysql_select_db('cl29-demodb') or die(mysql_error());
$name=$_POST['name'];
$pwd=$_POST['password'];
if($name!='' && $pwd!='')
{
$query=mysql_query("select * from EmployeeTable where EmployeeName ='".$name."' and password='".$pwd."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
$_SESSION['id']=$res['id'];
header('location: profileindex.php');
}
else
{
echo "user name and password are incorrect" ;
echo "<a href=index.php> click here to go back </a>";
}
}
if(!isset($_SESSION['id'])){
echo "Sorry, Please login and use this page";
exit;
}
}
?>
I am able to login successfully and reach the profile of the user.But I want the profile to display only the information for respective users.The profile looks like this:
I have written the php to retrive the name,designation,weekly points,overall points,weekly rank and overall rank respectively.
I tried to echo the variables in the html.
But I am not able to do so.It isnot pulling any data.I have column for all the above fields in the table.
Kindly help.
May be this is the cause
mysql_fetch_row() return the numeric array and you are accessing as $res['id']
either replace mysql_fetch_row with mysql_fetch_array or try numeric index of your id
$_SESSION['id']=$res[0]; or $_SESSION['id']=$res[1];
use mysqli_fetch_assoc so you could call the columns by name if you are using mysql_fetch_array you should call the columns by their index no the by the column name.
There is no need to start a session again in the profileindex.php as the session has already started in the login page.
print the sql and run it in the backend to check if you are getting the desired result in order to further debug this.

why code displaying on browser while running php script using tomcat 6.0

i am trying to run php script using apache tomcat6.0. am using netbeans as my editor. there is no errors while running and got a message build succesfull. i have two programs welcome.php and form.jsp. the form.jsp is used for user entry form and its displaying on the browser. but when i submit the form the welcome.php is not working and its giving me program code on browser. this is my welcome.php.
$query1="select * from company";
$result1 = odbc_exec($connect, $query1);
#fetch the data from the database
while(odbc_fetch_row($result1)){
$cnamearray[$count] = odbc_result($result1, 1);
$enamearray[$count] = odbc_result($result1, 2);
if($cnamearray[$count]==$_POST['cname'])
{
print "<script> alert(\"cname Exists\"); </script>";
exit();
}
if($enamearray[$count]==$_POST['ename'])
{
print "<script> alert(\"eName Exists\"); </script>";
exit();
}
}
$query=("INSERT INTO company(cname,ename) VALUES ('$_POST[cname]','$_POST[ename]') ");
$result = odbc_exec($connect, $query);
echo "<script> alert(\"Row Inserted\"); </script>";
?>
am getting
"; exit(); } if($enamearray[$count]==$_POST['ename']) { print ""; exit(); } }
$query=("INSERT INTO company(cname,ename) VALUES ('$_POST[cname]','$_POST
[ename]') ");
$result = odbc_exec($connect, $query); echo ""; ?>
these codes on browser.
why the codes are displaying on the browser . what i must do to get output. how can i run php script in tomcat
Tomcat by itself is a Java servlet/JSP container, and knows nothing about PHP -- you realize that, right? You need to do some sort of unholy hack to get PHP working on Tomcat. Here is a Google hit for "Tomcat PHP", and it looks like it does indeed describe just such a hack.
May Cthulhu have mercy on your soul.
It looks like you need to add a closing quotation mark and semi-colon to your $query1 line
$query1="select * from company
Should be...
$query1="select * from company";

Categories