PHP: Undefined shown on blank page - php

I'm trying to print/echo values from previous file however instead of showing error, all that is shown is 'Undefined' on a blank page. I've researched and tried several method but nothing works. Please help.
<?PHP
$user_name = "root";
$password = "";
$database = "leadership_program";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
if (isset($_POST['marks'])) {
foreach ($_POST['marks'] as $value) {
echo"$value";
}
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
echo $id;
}
// $SQL2 = "UPDATE answer_table SET marks='$value' WHERE survey_id= '$survey_id' AND student_id= '$id'";
//$result2 = mysql_query($SQL2);
//mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
// header("Location: surveyView.php");
}
?>
Here is displayresult.php
<form action="student_mark_save.php" method="POST"> //<?php...more codes here
if ($strucrow["qns$i"] === 'radio' || $strucrow["qns$i"] === 'checkbox') {
foreach ($arr as $b) {
echo "<br/>";
if (strpos($b, '%#%') !== false) {
$c = substr($b, 3, -2);
//echo $c;
$d = str_replace("$arr[0] :-", ':', $c);
echo $d, "<br/>";
echo "<br/>";
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
//echo $b;
} else {
echo $b;
// echo "is not with comment qns";
}
}
} else if ($strucrow["qns$i"] === 'comment') {
foreach ($arr as $b) {
echo $b;
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
// echo "is not with comment qns";
}
} else {
}
echo "<p/>";
}
$marksquery = sprintf(
"SELECT marks FROM answer_table WHERE survey_id = '%d' AND student_id = '$studentid' ", mysql_real_escape_string($survey_id)
);
$marksQuer = mysql_query($marksquery) or die(mysql_error());
$marksrow = mysql_fetch_assoc($marksQuer);
echo "<td><input type=\"hidden\" value= \"$survey_id\" name=\"survey_id\"></td><br />" ;
echo "<td><input type=\"hidden\" value= \"$studentid\" name=\"id\"></td><br />" ;
echo "<p><input type=\"submit\" value=\"Update\"></p>";
?>
</form>

for undefined mean, there is something which is not existing in global $_POST[]
check try to print $_POST in your first if statement as:
if ($db_found) {
print_r($_POST);
exit();
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
now just see what do you have in $_POST, It might help you...Thanks

Most likely some Post data is not set. Try vardump($_POST); die('happy');.
It would also be better to handle missing Post data instead of just ignoring it so maybe if ($db_found) { should be
<?php
if ( $db_found
&& isset($_POST['survey_id'])
&& isset($_POST['marks'])
&& isset($_POST['id'])
)
{
$survey_id = $_POST['survey_id']; //maybe ensure int
$id = $_POST['id']; //maybe ensure int
$values = array(); //this is important $value will not be available outside the for loop or contain only the last value
foreach ((array)$_POST['marks'] as $value) { //ensure $_POST['marks'] is an array
$values[] = $value; //maybe mysql escape each $value here
}
$SQL2 = sprintf(
"UPDATE answer_table SET marks='%s' WHERE survey_id=%d AND student_id=%d",
impolde(',' $values), //assuming comma separated list here
$survey_id,
$id
);
$result2 = mysql_query($SQL2);
mysql_close($db_handle);
} else { ...
Please also consider to escape the values you read from POST. Doing it this way makes it very easy to SQL inject into your script!

Related

adding and removing value to session array

I post values to be added to a session array. If a value already exists in the array it should be removed. Both are not resulting in a change of the array.
<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT'] . '/v5/functions/connect_li.php');
//if (!isset($_session['cart'])) $_SESSION["cart"]= 9;
if (isset($_POST['myresort']) && !empty($_POST['myresort'])) {
$resorts = $_POST['myresort'];
$_SESSION['cart'][] = $resorts;
}
echo '<pre>';
print_r($_SESSION["cart"]);
if (isset($_POST['myresort'])) {
$key = array_search($_POST['myresort'], $_SESSION['cart']);
if ($key !== false) {
unset($_SESSION['cart'][$key]);
$_SESSION["cart"] = array_values($_SESSION["cart"]);
}
}
echo '</pre>';
if (!empty($_SESSION["cart"])) {
echo '<a href="/skirerport/">my resorts: ';
$_SESSION["cart"] = array_unique($_SESSION["cart"]);
$_SESSION["cart"] = array_filter($_SESSION["cart"], 'strlen');
$arr_as_string = implode(',', $_SESSION["cart"]);
$sql = "SELECT resort FROM sv_resorts WHERE res_id IN ($arr_as_string) ORDER BY resort LIMIT 10";
//echo $sql;
$res = mysqli_query($conn, $sql);
while ($ro = mysqli_fetch_array($res)) {
echo $ro['resort'] . " ";
}
print_r($_SESSION["cart"]);
echo "</a>";
}
?>
(Ignore this answer, it wont let me delete it via the app)

Why can't I echo all variables correctly?

Edited, please scroll down
I am trying to display 3 variables which consist of data stored in a SQL database. However, only the first gets echoed successfully (topLeftUrl). It is worth noting that the same PHP file also receives data from an input (also in the same PHP file) and stores it in the same SQL database. This code was written for testing purposes and may not be entirely safe.
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Store input in SQL database
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//First echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done2 == 0)
{
$topLeftUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
//Second echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topRight" && $done3 == 0)
{
$topRightUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
//Third echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "message" && $done == 0)
{
echo $row["cont"];
}
}
Edit:
I updated the code, and the problem seems to have changed. For some reason, echo $messageCont; displays an old value of cont WHERE id='message'. The database itself is updated successfully, though, and I see the new value of cont once I refresh the page/re-submit the form. Why do I not see the current value of cont immediately after form submission, though? Here is the new code:
/* Before <!DOCTYPE html> */
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Query and update
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//Query again and read
$done0 = 0;
$done1 = 0;
$done2 = 0;
mysqli_data_seek ($result, 0);
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done0 == 0)
{
$topLeftUrl = $row["cont"];
$done0 = 1;
}
else if ($row["id"] == "topRight" && $done1 == 0)
{
$topRightUrl = $row["cont"];
$done1 = 1;
}
else if ($row["id"] == "message" && $done2 == 0)
{
$messageCont = $row["cont"];
$done2 = 1;
}
else null;
}
/* After <!DOCTYPE html> */
/* Form code was omitted as it works perfectly. It is in this same file, though. */
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo $messageCont;
Any help is appreciated.
Edit: I only had to replace mysqli_data_seek () with the line beginning by $result (cut/paste). Thank you.
I ran into this same problem on my site....you run multiple mysql_fetch_array() on the same query ($result)...I thought this would work on my site but this failed for all but the first of 6 while loops which all referenced the same query on my site (I'm sorry but I don't remember the exact error message in my error_log). Try condensing your 3 while loops into 1 loop, something like this:
while ($row = mysqli_fetch_array ($result)) {
if ($row["id"] == "topLeft" && $done2 == 0) {
$topLeftUrl = $row["cont"];
} else if ($row["id"] == "topRight" && $done3 == 0) {
$topRightUrl = $row["cont"];
} else if ($row["id"] == "message" && $done == 0) {
echo $row["cont"];
} else null;
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";

Submit button needs to be clicked twice to get my results from radio buttons in a php script

The problem with this code is that I can't read the results in $survey_Answers1 except after clicking on the submit button twice.
file:survey.php
<?PHP
session_start();
//=========================================================
//The following page is used to create a dynamic survey.
//=========================================================
$qNum = 'q1';
$question = 'Question not set';
$answerA = 'unchecked';
$answerB = 'unchecked';
$answerC = 'unchecked';
$qID = array();
$question = array();
$A = array();
$B = array();
$C = array();
$survey_Answers = array();
$survey_Answers1 = '';
//============================================
// OPEN A CONNECTION TO THE DATABASE
//============================================
$user_name = "root";
$password = "";
$database = "surveyTest";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="survey.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
if (isset($_POST[$qNum])){
$survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
}
//var_dump($survey_Answers1);
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
//$_SESSION['answers'] = $survey_Answers1;
//var_dump($_SESSION['answers']);
echo "<INPUT TYPE = 'hidden' Name = 'h2' VALUE = '".$survey_Answers1."'>";
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
var_dump($_POST['h2']);
echo '</form>';
mysql_close($db_handle);
}
else {
print "Error getting Survey";
mysql_close($db_handle);
}
?>
The value stored in var_dump($_POST['h2']); after hitting clicking the submit button once is: string '' (length=0)
P.S., using session variables doesn't resolve the problem, so please don't suggest this answer!!!!
Try to insert after for-loop
for ($i = 1; $i <= 2; $i++)
{
// your code here
}
if (empty($_POST['h2'])) $_POST['h2'] = $survey_Answers1; // insert this line
Or use JavaScript, insert to the end of file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var answers = '';
$('input[type=Radio]:checked').each(function() {
if (answers !== '') {
answers += ',';
}
answers += $(this).val();
})
$('input[name=h2]').val(answers);
});
}
})
</script>
From what I see your problem is with your for loop try to see whats returning survey_Answers1 in each loop. you can try this to see whats returning each time it loops and part from there
if (isset($_POST[$qNum])){
$survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
?>
<script type="text/javascript"><?php echo $survey_Answers1; ?></script>
<?php
}

Invalid argument supplied for foreach() working locally but not remotely

I'm trying to read a .CSV file and print it in a table format in HTML. At the end of the page is a comments text field where comments get submitted and saved in the database.
When I tested the code below locally it works fine. When I tried to run it on the linux server, it prints out fine when first opened, but when I press submit to save a comment, the page refreshes and the table does not print. Giving an "Invalid argument supplied for foreach()" error. (Note: this doesn't happen locally, i can submit all I want and it does not return an error.)
I've searched on stackoverflow and it seems that most of these problems are related to declaring the variable as an array. However, it seems odd to me as the code works fine the first time with no error, but once I submit it returns an error.
UPDATE: full code for file posted below.
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
<?php
//---------------------------------Head/BG---------------------------------------
//Request Case ID
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
$patientID = "";
if(isset($_REQUEST['patient'])) {
$patientID = $_REQUEST['patient'];
}
//Include basic functions to allow connection to SQL db.
include("generic.php");
//Include css and header information.
$printTitle = "Volume Report for Case ".$case."";
$printHeader = "Volume Report for Case ".$case."";
$printFooter = "";
$printBreadcrumb = "";
include("header.php");
//submit tableStatus update
if(isset($_REQUEST['submit'])) {
saveTableStatus($case);
}
//-----------------------------Start of Content----------------------------------
showStatusComment($case);
printVolumeTable($case,$patientID);
tableStatus($case);
//---------------------------End of Content--------------------------------------
//---------------------------Functions Definitions-------------------------------
//print report.csv Table
function printVolumeTable($case,$patientID){
echo "<html><body><table border='1'>\n\n";
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
}
function showStatusComment($case) {
$connection = getMySqlConnection();
$sql = "SELECT p.STATUS_NAME, c.volume_comments FROM cases c, primary_status_lookup as p WHERE c.volume_status=p.STATUS_ID and c.caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
if($status == 'Clear Status') {$status = 'None'; $comments = 'None';}
print("<p><b>Table Status: </b>".$status." / <b>Comments: </b>".$comments."</p>");
}
}
}
//Status & Comments
function tableStatus($case) {
$connection = getMySqlConnection();
$sql = "SELECT volume_status, volume_comments FROM cases WHERE caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
print("<form><p>");
showStatusComment($case);
statusDropdown($case,$status);
print("<input type=hidden name='case' value='".$case."'/>");
print(" <label><b>Comments:</b><textarea name='comments' cols=70 rows=2 >".$comments."</textarea></label><br/><br/>");
print("<input type='submit' name='submit' value='Submit'/><INPUT type='button' value='Close Window' onClick='window.close()'></form>");
}
}
}
//Status Dropdown
function statusDropdown($case,$status){
print("<b>Status:</b>");
$dropdown = "<select name = 'status'><option selected='selected' value=NULL>--Select Status--</option>";
$connection = getMySqlConnection();
$sql = "SELECT STATUS_ID, STATUS_NAME FROM primary_status_lookup ORDER BY STATUS_ID ASC";
$result = mysql_query($sql, $connection) or die(mysql_error());
while($record=mysql_fetch_array($result)){
if ($status == '') {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if (($status == $record['STATUS_ID']) && ($status == '99')) {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if ($status == $record['STATUS_ID']) {
$dropdown .= "<option value = '{$record['STATUS_ID']}' selected='selected'> {$record['STATUS_NAME']}</option>";
} else {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
}
}
$dropdown .="</select>";
echo $dropdown;
}
function saveTableStatus($case)
{
//retrieve selected status
$status = '';
if(isset($_REQUEST['status'])) {
$status = $_REQUEST['status'];
}
//retrieve typed comments
if(isset($_REQUEST['comments'])) {
$comments = $_REQUEST['comments'];
}
if($status=='NULL') {
print("<p class='error'>No status selected, please select a status and try again.</p>");
}
else if (($status!=='NULL')){
$connection = getMySqlConnection();
mysql_query("START TRANSACTION", $connection);
if ($status =='99') {$comments = '';}
$result= mysql_query("Update cases Set volume_status=".$status.", volume_comments ='".mysql_real_escape_string($comments)."' Where caseid='".mysql_real_escape_string($case)."'", $connection);
if($result) {
mysql_query("COMMIT", $connection);
print("<p class='saved'>Table Status Updated!</p>");
} else {
mysql_query("ROLLBACK", $connection);
}
mysql_close($connection);
}
}
?>
If you form, and the script that takes the posted form are not on the same path, then your
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
will not open the same file.
Edit -
Okay I think your problem is your $case variable. If there is no request, the $case is blank (""). So the above line will open "analyze///report.csv" As you can see depending on this code
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}

php oci_fetch_array and pass value to function issue

1) I want to save case 1 value to an array. Return this array and pass it to a function. The code become case 2, but no result come out, where is the problem?
2) In function display_urls, i want to echo both $url and $category. What should i do in IF condition or add another line of code?
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url."";
echo "".$category."";
}
}
echo "";
}
case 1: work fine
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$i=0;
echo "";
while( $row = oci_fetch_array($result) ){
$i++;
echo "";
echo "".$row['USERNAME']."";
echo "".$row['BM_URL']."";
echo "".$row['CATEGORY']."";
echo "";
}
echo "";
case 2:
$url_array = array();
while( $row2 = oci_fetch_array($result, OCI_BOTH)){
$i++;
$url_array[$count] = $row[0];
}
return $url_array;
I think you probably want something like this:
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url['BM_URL']."";
echo "".$url['CATEGORY']."";
}
}
echo "";
}
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$url_array = array();
while( $row = oci_fetch_array($result, OCI_ASSOC)){
$url_array[] = $row;
}
display_urls($url_array);
This will store all the information on the URLs in $url_array with a lookup by column name.

Categories