having issues with php_self - php

I am trying to implement a page where a user enters a comment and it gets displayed right in the same page. The problem i am having is that every time you go to the page there are no comments in the page(there are actually comments).
This is my sceneario i am having:
I go to the page and there are no comments, i enter a comment 'hello' and it gets displayed right away.
I go to a different page and then i come back to the comments page and there are no comments.(the comment "hello" should be already displayed)
I enter a comment "hi" and both comments "hello" and "hi" get displayed
I cant resolve this issue..
This is my code, its pretty long
<?php
session_start(); //starts or continues the session
require_once('functions.php'); //needed for some function calls
error_reporting(E_ALL ^ E_NOTICE);
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<script type = "text/javascript" src = "functions.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
GetUserLayout($_SESSION['userId'], $_SESSION['superUser']);
?>
<div id = "shareyouridea_form" class = "post">
<h1> Share your post</h1>
<!-- used for the form -->
<form id = "idea_form" method = "post"
action = "<?php echo $PHP_SELF;?>"
onkeypress = "return DisableEnterKey(event);">
<table>
<caption>
<strong>
<br /> Share post form:
</strong>
</caption>
<tr class = "spacearound"> <!-- input for bright idea -->
<td>  Post: </td>
<td>
<textarea form = "idea_form" name = "b_idea" rows = "12"
cols = "85" title = "Please describe your product idea"
id = "bright_idea" maxlength = "1000"
onkeypress =
"return InputLimiter(event, 'lettersSpacePunctuation');">
</textarea>
</td>
</tr>
</table>
<p>
   
<input type = "reset" value = "Reset" />
  
<input type = "submit" value = "Share Idea!"
title = "complete form first to submit"
id = "submit_button"
name = "add_comment"
onmousedown = "IsIdeaFormCompleted();" />
</p>
</form> <!-- end idea_form -->
</div>
</div> <!-- end of ShareYourIdea_middle -->
<script>
DisplayFooter();
</script>
<?php
if(isset($_POST['add_comment'])){ // if add comment was pressed
// get variables
$name = $_SESSION['firstName'];
$empId = $_SESSION['userId'];
$idea = $_POST['b_idea'];
// CONNECTING TO OUR DATABASE
$db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
if (mysqli_connect_errno()) { //if connection to the database failed
echo("<p id = 'greatideadescription'>
Connection to database failed: " .
mysqli_connect_error($db) . "</p>");
exit("goodbye");
} //by now we have connection to the database
// WE WRITE OUR QUERY TO INSERT POST INFO TO DATABASE
$query = "INSERT INTO posts(postId,empl_Id,post,postDate)
VALUES('','$empId','$idea',NOW())";
$result = mysqli_query($db, $query);
}
?>
<?php
// WE DO A QUERY TO SHOW ALL COMMENTS IN THE PAGE
$query = "SELECT firstName,lastName, post,
date_format((date_add(postDate,interval -7 hour)),'%a, %M, %d, %Y at %I:%i%p' ) as mydatefield
FROM users INNER JOIN posts ON userId = empl_Id
ORDER BY postDate DESC";
$result = mysqli_query($db,$query);
if (!$result) { //if the query failed
echo("<p id = 'greatideadescription'>
Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);}
if (mysqli_num_rows($result) == 0) { //if no rows returned
echo("<div id = 'blogs'>
<div id ='name'>
No posts detected
</div>
</div>
<div class='fb-like' data-href='http://jacobspayroll.zxq.net/index/blog.php' data-send='true' data-width='450' data-show-faces='true'></div>
");
mysqli_close($db); //close the database
exit("</table></div></form></div></div>
<script>DisplayFooter();</script></body></html>");
} //by now we know that we have some products purchases returned
$numRows = mysqli_num_rows($result); //gets number of rows
$numFields = mysqli_num_fields($result); //gets number of fields
//prints the data in the table
while($row = mysqli_fetch_assoc($result)){
$posted = $row['post'];
$message = wordwrap($posted,5);
echo
'<div id ="blogs">
<table id = "blog_id">
</br>
<div id = "name">
<strong>'.$row['firstName'] . ' ' .$row['lastName'].
'</strong>
: ' .$message .
'<br/>
</div>
<div id ="date">'.
$row['mydatefield'] . '
</div>
<div id ="delete_comment">
Delete this comment
</div>
<p>
</table>
</div>';
}
mysqli_close($db);
?>
</body>
</html>

You have the wrong Usage of PHP_SELF
//You must use Server and execution environment information `$_SERVER[]`
$_SERVER['PHP_SELF'];
// For your form action like this
action = "<?php echo $_SERVER['PHP_SELF'];?>"

as Kail mentioned you got it wrong but you might want to use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF'] then you might want to add some script to get GET parameters if you use them for your script(s). If you use PHP_SELF you might have a user link to script.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo might look like action="script.php/"><script>alert('xss')</script> or could be a redirect to collect cookies and the alike in other words XSS attack.
$_SERVER['PHP_SELF'] vs $_SERVER['SCRIPT_NAME'] vs $_SERVER['REQUEST_URI']
XSS Woes
What's the difference between $_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME']?

Related

Insert a random image in mysql database using php

I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)

Confirmation box before running a php script

<?php
//Connect to Database
$link = mysqli_connect('localhost', 'xxxxxxx', 'xxxxxxx', 'xxxxxxx');
mysqli_set_charset($link,'utf8');
$delistpost= htmlspecialchars($_GET["delistpost"]);
//$request = $_SERVER['QUERY_STRING'];
$request = $delistpost;
//Error message on unsuccessful connection (connection failure)
if ($link==false){
//Print error information
echo(" ERROR: Could not connect.<br>".mysqli_connect_error());
}
//Successful connection message
else{
//Split the query string taking '=' as the delimiter
if (strpos($request, '='))
{
$n=split("=",$request);
// $queryStringType=$n[0];
$offset =$n[1];
}
$userchar = substr($offset,0,2);
$key = ltrim(substr($offset, 2, -1), '0');
$status = substr($offset,-1,1);
$query = "SELECT postid FROM userwisePost WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
$updatequery = "UPDATE userwisePost SET post_status = 'draft' WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
//Print the confirmation of SQL query
$verify = mysqli_query($link,$query);
if(mysqli_num_rows($verify) > 0){
$updateresult = mysqli_query($link,$updatequery);
if($updateresult==true){
RUN FUNCTION TO SHOW SUCCESS UPDATION.
}
else RUN FUNCTION TO SHOW FAILURE.
?>
Here I'm connecting to a database. I decrypt the query-string as per my requirement. After i decrypt the query-string, I match it with a record in the database, if everything matches, I need to run an update query.
Currently my program is updating it without confirmation. I need the user to press a confirmation button to run the update query.
I know I require javascript to track user button click. I need to display a HTML page on button click if the user confirms else the page should redirect to the homepage.
<?php
//Connect to Database
include "dbconnect.php";
$delistpost= htmlspecialchars($_GET["delistpost"]);
//$request = $_SERVER['QUERY_STRING'];
//$request = $delistpost;
//Split the query string taking '=' as the delimiter
$userchar = substr($delistpost,0,2);
$key = ltrim(substr($delistpost, 2, -1), '0');
$status = substr($delistpost,-1,1);
$query = "SELECT postid FROM userwisePost WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
$verify = mysqli_query($dbconnect,$query);
if($verify==true){
if(mysqli_num_rows($verify) > 0)
{
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Confirmation</title>
<link rel="stylesheet" href="alertstyle.css">
</head>
<body>
<div class="container">
<form id="contact" action="changepoststatus.php?delistpost='.$delistpost.'" method="post">
<center><h3>Confirmation</h3>
<h4>Are you sure you want to delist your post?<br>If you wish to activate the post again, please contact the system administrator or email us at xxxxxxxxxx.</h4>
</center>
<fieldset>
<center>
<button name="delistpost" type="submit" id="contact-submit" style="width: 49%;">Confirm</button>
</center>
</fieldset>
</form>
</div>
</body>
</html>';
}
else {
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Failure</title>
<link rel="stylesheet" href="alertstyle.css">
</head>
<body>
<div class="container">
<form id="contact" action="https://xxxxxxxxxx" method="post">
<center><h3>Failure</h3>
<h4>Something went wrong<br>Please contact the system administrator or email us at xxxxxxxxxx.</h4>
</center>
<fieldset>
<center>
<button name="delistpost" type="submit" id="contact-submit" style="width: 49%;">Homepage</button>
</center>
</fieldset>
</form>
</div>
</body>
</html>';
}
}
?>
This is how I did it. I call another link on press of the button. changepoststatus.php has almost the same code but with update query instead of the select query.

PHP POST and GET in same statement

I've found similar questions, but have been unable to tie them into my example. I am very new to PHP and completely self teaching.
At present I have a form for entering a new customer. In that form I want the user to be able to select an existing DB item (business) and insert that BusinessID into the CUSTOMER table. My problem is that I can GET the BusinessID, but then I can't POST that same ID with the other field inputs. Code below
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>New Contact</title>
<!--Declare CSS and JavaScript-->
<link rel="stylesheet" type="text/css" href="RealtyCRM_Style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.resmenu.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
$('.toresponsive').ReSmenu();
});
</script>
<!--Begin Header Code-->
<!--Begin Header Code-->
<div class="BodyHeader">
<div>
</div>
</div>
<!--Begin Menu Code-->
<div class="menu_container" style="position:relative; z-index:11;">
<ul class="toresponsive">
<li>Log In</li>
<li>Contact</li>
<li>News</li>
<li class="current-menu-item">Dashboard
<ul>
<li>Add New Data</li>
<li>Update Data</li>
<li>Search</li>
<li>Report</li>
<li>Admin Page</li>
<li>Log Interaction</li>
</ul>
</li>
</ul>
</div>
<br>
<!--Begin Dashboard Buttons Code-->
<div class="DashboardButtonsTop">
<h1 class="centeredDashBoardButtonInactive">New Retailer</h1>
<h1 class="centeredDashBoardButton">New Contact</h1>
<h1 class="centeredDashBoardButtonInactive">New Property</h1>
</div>
<hr style="width:700px; height:5px;">
<br>
<br>
<!--END Dashboard Buttons Code-->
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'leasingl_dbwrite';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$contactFirstName = addslashes ($_POST['contactFirstName']);
$contactLastName = addslashes ($_POST['contactLastName']);
}
else
{
$contactFirstName = $_POST['contactFirstName'];
$contactLastName = $_POST['contactLastName'];
}
$contactPhoneNumber = $_POST['contactPhoneNumber'];
$contactEmail = $_POST['contactEmail'];
$Business = $_POST['BusinessID'];
$sql = "INSERT INTO Contact ". "(ContactFName,ContactLName, ContactMobilePhone, contactEmail, BusinessID, CreatedDate) ". "VALUES('$contactFirstName','$contactLastName','$contactPhoneNumber', '$contactEmail', '$Business', NOW())";
mysql_select_db('applicationDatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<div style='text-align:center;'>Entered data successfully\n</div>";
echo "<br><div><a href='contactdataentry.php' class='redirectButton'>Add More Contacts</a>\n</div>";
echo "<br><div><a href='dashboard.php' class='redirectButton'>Return to Dashboard</a></div>";
mysql_close($conn);
}
else
{
?>
<div class="Form_container">
<form method="post" action="<?php $_PHP_SELF ?>">
Contact First Name<br>
<input class="largeInput" type="text" name="contactFirstName" ID="contactFirstName"><br>
Contact Last Name<br>
<input class="largeInput" type="text" name="contactLastName" ID="contactLastName"><br>
Contact Phone Number<br>
<input class="largeInput" type="text" name="contactPhoneNumber" placeholder="### - ### - ####" ID="contactPhoneNumber"><br>
Contact Email<br>
<input class="largeInput" type="text" name="contactEmail"><br>
Business<br>
<?php
$servername = "localhost";
$username = "leasingl_dbread";
$password = "password";
$dbname = "applicationDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT RetailerID, RetailerName FROM Retailer ORDER BY RetailerName DESC";
$result = $conn->query($sql);
?>
<select style='text-align:center;' class='largeInput' name='Business' ID='Business'>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["RetailerID"]. "'>" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option><br><br>";
}
} else {
echo "0 results";
}
?>
</select><br><br>
<?php
$conn->close();
?>
<input name="add" type="submit" id="add" value="Add Contact" class="button">
</form>
<br>
<hr style="width:400px; height:10px;">
</div>
<?php
}
?>
</body>
</html>'
So being able to insert the value from my drop down is the main issue. Additionally, I'm sure there is unnecessary / incorrect code in what I posted, I've been piecing together examples one at a time.
Thank you for all the help, if I can get this working I can have a functioning basic version of my application
EDIT
I have successfully prepopulated my drop down, and the user then chooses from that list. I want to pass that choice via my INSERT statement. I worry that the two different CONNECTIONS which I establish are part of the reason my INSERT won't recognize $Business
It appears you are referring to GET in a confusing way. In PHP there is $_GET and $_POST variables, and when you mention GET in all-caps, in implies you are using $_GET - which in fact you are not.
The solution - as I understand the question - is actually fairly straightforward.
Inside your form, add a hidden input that stores (and then passes) the BusinessID variable, like so:
<input type="hidden" name="BusinessID" value="<?php echo $Business; ?>">
As you mention you are just learning, here's some additional tips:
Name your variables consistently throughout. If the name of the database column is BusinessID, then name your variable $businessID" and your inputBusinessID".
Kudos to you for good indenting / formatting! That will save you gobs of time when troubleshooting / reading your own code!
EDIT
If what you are trying to do is pre-select the record in the dropdown, then alter your loop like so:
while($row = $result->fetch_assoc()) {
// Note: I've removed the <br> tags here, they don't belong in a select dropdown
echo "<option value='". $row["RetailerID"]. "'";
// If the ID matches, make this the selected option
// NOTE: Per my tip above, I'd strongly recommend changing the variable name $Business to match the field name - $RetailerID in this case
echo ($row['RetailerID'] == $Business) ? ' selected' : '';
echo ">" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option>";
}

Form only Submitting on 2nd Attempt

I have created a form for a quiz, where you have to enter the answers and a PHP script will total them and send them to en E-Mail address and save them to a file. However, the user is only redirected on the 2nd attempt (submission) of the form. The results are totalled and sent on the first submission, but it does not redirect. On the 2nd submission, the results are not totalled, but an e-mail is sent and the user is redirected to the completion page.
Here is my code:-
<!DOCTYPE html>
<head>
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="../styles.css" />
<link rel="shortcut icon" href="../img/favicon.ico" type="image/x-icon" />
</head>
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
if (isset($_SESSION['username'])) $username = $_SESSION['username'];
else header("Location: http://quiz.dibdibguy.com/client/index");
include_once($_SERVER['DOCUMENT_ROOT']."/scripts/sql.php");
$qid = $_SESSION['quiz'];
$con = connect();
$data = mysqli_query($con, "SELECT * FROM `qs` WHERE `id`='$qid' LIMIT 1");
$qinfo = mysqli_fetch_array($data, MYSQLI_ASSOC);
?>
<body><div id="white"> </div>
<div id="content" class="text">
<div class="header">Quizzes</div>
<div class="subheader">Quiz: <?php echo($qinfo['name']); ?></div>
<table width="85%" class="menu text" align="center">
<tr>
<td>
<div align="center"><?php if ($qinfo['desc'] == NULL) echo($qinfo['name'] . ", has no description available."); else echo($qinfo['desc']); ?></div>
</td>
</tr>
</table>
<br>
<?php
$table = $qinfo['table'];
$questionsTable = mysqli_query($con, "SELECT * FROM `$table`");
?>
<table width="85%" class="menu text" align="center">
<tr>
<td>
<div align="left"><b>Please Remember:</b> For questions that require you to type an answer, you must spell it correctly, as the system cannot detect spelling errors.<br>
<b>Playing as: <i><?php echo($_SESSION['username']); ?></i></b></div>
</td>
</tr>
</table>
<br>
<table width="85%" class="menu text" align="center">
<tr>
<td>
<form method="post" name="quiz" action="">
<?php
$amt = mysqli_num_rows($questionsTable);
$count = 1;
echo($questions['que']);
while($ques = mysqli_fetch_array($questionsTable)){
echo("Question: " . $ques['que'] . "<br>");
echo("Answer: <input type=\"text\" name=\"$count\"><br><br>");
$count = $count + 1;
}
?>
<input type="submit" name="submit" value="Submit Answers" id="btn">
</form>
</td>
</tr>
</table>
<?php
if (isset($_POST['submit'])){
$answers = mysqli_query($con, "SELECT `ans` FROM `$table`");
$u_answers = $_POST;
$correct = 0;
while($answer = mysqli_fetch_assoc($answers)){
echo("Hi");
foreach($u_answers as $u_ans){
if ($answer['ans'] == strtolower($u_ans)) $correct = $correct + 1;
$count = $count + 1;
}
}
header("Location: http://quiz.dibdibguy.com/client/index");
#WRITE DATA TO FILE
$file = fopen("../results/" . strtoupper($_SESSION['username']) . "_" . date("d-m-Y_h:i_sa") . "_" . strtoupper($_SESSION['quiz'] . ".txt"), 'w');
fwrite($file, ($correct) . "/" . ($amt));
fclose($file);
mail("aaron#dibdibguy.com", $_SESSION['username'] . "quiz results", $correct . "/" . $amt);
$_SESSION['quiz'] = $qinfo['name'];
}
close($con);
?>
<br>
<?php include "../footer.php"; ?>
<br>
<br>
</div>
</body>
</html>
On the 1st attempt, if I get 1 question correct, I receive an e-mail stating; '1/39', which is what should happen, but on the 2nd attempt, I get an e-mail stating '0/', even if I get some correct.
Thanks in advance for any assistance. If you need anything else, please, E-Mail me (aaron#dibdibguy.com), or comment on this question!
Web Host: unlimitedwebhosting
PHP Version: 5.5
I see two problems.
First - HTML headers have to be sent before any content is sent. If you look in your error logs there are likely warnings about this. You print quite a lot of html to the page before your location header is used for the redirect. Since it's too late for headers it's ignored (you don't get redirected). To fix this either move the redirect logic further up the page before any output (and plain HTML counts as output) or use output_buffering to keep the output from being sent to the browser until you've sent all your headers.
Second - The '0/' email seems to be an error in your logic. If you look at this block:
if (isset($_POST['submit'])){
... Other Stuff
mail("aaron#dibdibguy.com", $_SESSION['username'] . "quiz results", $correct . "/" . $amt);
... More Stuff
}
The logic you've written says that the email will be sent any time the submit button is pressed. You never did a 'sanity check' to see if you actually have any valid information in the form first.

Using PHP to pull data from Access Database PHP Warning: odbc_fetch_array(): 4 is not a valid ODBC result resource in EditRecord.php on line 91

I'm trying to create a set of webpages that work together to allow users to view, delete, and edit rows of a MS Access database using PHP.
Membership.php shows a list of the names of members in the Access database. Their names are also hyperlinks that, when clicked, take users to another page EditRecord.php where all of information on the member whose name was clicked on Membership.php is displayed in text boxes with the option to completely delete the record, or just update certain fields.
Membership.php and EditRecord.php are displayed below. The error code is for line 91 of my source for EditRecord.php, but I cut some things out of this post for privacy. Instead, the line has been marked like so:
//--------This is the error line----------
code
[Membership.php]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Accounts.css">
<style type="text/javascript" src="Validate.js"></style>
<style type="text/javascript" scr="Redirect.js"></style>
<style type="text/javascript" src="Utilities.js"></style>
<title>Member Information Input</title>
</head>
<body>
<div id="content">
<?php
//Establish data connection using external file
require("connection.php");
//Issue SQL SELECT Statement
$sql = "SELECT * FROM Membership";
//Stores any results that match the search term.
$rs = odbc_exec($conn, $sql);
//Set counter for search results to zero
$results = 0;
//Iterates through search results and prints information on records that match
while($row = odbc_fetch_array($rs))
{
$results += 1;
echo '<p>' . $row['FirstName'] . " " . $row['LastName'] . "</p>";
}
?>
</div>
</body>
</html>
[EditRecord.php]
<?php
//Retrieve ID value - if the page is loading for the first time, use $_GET[]. If the
//delete or edit button has been clicked, use $_POST[]
if (isset($_GET['ID'])) {
$userID = $_GET['ID'];
}
else {
$userID=$_POST['ID'];
}
//Establish data connection
require("connection.php");
//If the Delete Button is clicked
if (isset($_POST['DelBtn'])) {
//Issue SQL Statement to Delete Selected Record
$sqlDelete = "DELETE FROM Membership WHERE ID = $userID";
//Execute the SQL Delete Query
$rsDelete = odbc_exec($conn,$sqlDelete);
if(odbc_num_rows($rsDelete) == 1) {
echo "Record successfully deleted!";
}
}
//If the Edit Button is clicked
else if (isset($_POST['EditBtn'])) {
//Collect form field values in scalar variables
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$State = $_POST['State'];
$Email = $_POST['Email'];
$Gender = $_POST['Gender'];
$Comments = $_POST['Comments'];
//Issue SQL Statement to Update Selected Record
$sqlUpdate = "UPDATE Membership SET FirstName = '$FirstName', LastName = '$LastName', Address = '$Address', City = '$City', State = '$State'" .
"Email='$Email', Gender = '$Gender', Comments = '$Comments' WHERE ID = $userID";
//Execute the SQL UPDATE Query
$rsEdit = odbc_exec($conn,$sqlUpdate);
if(odbc_num_rows($rsEdit) == 1) {
echo "Record successfully updated!";
}
}
//Issue SQL SELECT Statement to Select Record to Edit or Delete
$sql = "SELECT * FROM Membership WHERE ID = $userID";
//Execute the SQL Query
$rs = odbc_exec($conn, $sql);
odbc_close($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Accounts.css">
<style type="text/javascript" src="Validate.js"></style>
<style type="text/javascript" src="Utilities.js"></style>
<title>Member Information Input</title>
</head>
<body>
<div id="content">
<form method="post" action="EditMember.php" name="EditForm">
<?php
// Loop through and display the recordset returned by SELECT statement. Display the record values in HTML Text Boxes
**//--------This is the error line----------
while ($row = odbc_fetch_array($rs)) {
?>**
First Name: <input type="text" name="FirstName" value="<?php echo $row['FirstName']?>"><br>
Last Name: <input type="text" name="LastName" value="<?php echo $row['LastName']?>"><br>
Address: <input type="text" name="Address" value="<?php echo $row['Address']?>"><br>
City: <input type="text" name="Telephone" value="<?php echo $row['City']?>"><br>
State: <input type="text" name="Telephone" value="<?php echo $row['State']?>"><br>
Email: <input type="text" name="Email" value="<?php echo $row['Email']?>"><br>
Gender: <input type="text" name="Telephone" value="<?php echo $row['Gender']?>"><br>
Comments: <input type="text" name="Comments" value="<?php echo $row['Comments']?>"><br><br>
<input type="hidden" name="ID" value="<?php echo $row['ID']?>" >
<?php
}
?>
<input type="submit" name="EditBtn" value="Edit Record"> <input type="submit" name="DelBtn" value="Delete Record">
</form>
</div>
<div id="footer">
<?php require("Footer.php"); ?>
</div>
</body>
</html>
I also find this strange, because there are five records in my database, not four. Is that because it starts counting at zero?
Any insight or advice would be greatly appreciated.
Your problem is that you are calling odbc_close() and closing the connection before your loop calls odbc_fetch_array(). You need to leave the connection open until after you've fetched all of the rows.
Also, the "4" in the error message does not refer to a number of rows or anything like that; it's just the numeric representation of result identifier for the resource created by the odbc_exec() call.

Categories