Problems with variables set inside While Loop being undefined outside. - php

Okay, so i have created a new support ticket system, but in my ticket search page it keeps giving me errors like undefined variable in line 197. the weird thing is that the variable is defined right above it. Please assist me in this here is a link to the code: http://pastebin.com/AMzRLDK4
I'm trying to make it possible for me to view the support tickets that are open and mark them as read or change the status and to reply to them by going to the pm system. I had it working last night but i must have changed something without realizing its effect.
Thanks in advance,
Matt.

It looks like this is the first time you use $Sid or $Sname in your code. They are inside a code block for the while, which means that is the only place they exist. Also, I think you want to use mysql_fetch_assoc(). It'll actually work with the column names, instead of the indexes. (And probably best off to use the newer MySQLi for several reasons)
while($raw = mysql_fetch_array($ret)){ $Sid = $raw['id']; $Sname = $raw['username']; }
Quick Fix:
$Sid = null; //or 0 whichever makes sense for you
$Sname = null; //or ''
while($raw = mysql_fetch_assoc($ret)){ $Sid = $raw['id']; $Sname = $raw['username']; }
However, with the LIMIT 1 in the MySQL Query, you could drop the WHILE all together
$raw = mysql_fetch_assoc($ret);
if($raw === false)
{
//Error Condition
}
$Sid = $raw['id'];
$Sname = $raw['username'];

Related

PHP - Can if-statement being ignored/skipped for some reason?

What I want to achieve : if a user pass a PHP parameter to the server, it will return the same parameter value back to the user, instead of returning the value from the database itself.
while($row = mysqli_fetch_assoc($result)){
$classId = $row['classId'];
if($obj['classId'] != ""){
$classId = $obj['classId'];
}
...
}
For some reason, I found out that the $classId still using the $row['classId'] value, even if the user had inserted the classId parameter. It seems that the PHP has ignored/skipped the if statement.
if($obj['classId'] != ""){..} //SKIPPED?
The code works fine right now and I do get the return of the same parameter value. Only one user out of hundreds got this issue and I assumed that the he/she had sent the parameter when the server was busy.
Questions:
1.Can if-statement being ignored/skipped for some reason?
2.How to make the if-statement more reliable even if the server in a high-traffic?
Excuse me for posting here. I don't find the right keywords for googling myself.
Thank you.
You could try having your if statement more strict.
if($obj['classId'] != ""){
$classId = $obj['classId'];
} else {
$classId = $row['classId'];
}
I'd also recommend using isset instead of checking for an empty string.
if(isset($obj['classId'])) { }

Unreachable Statement in PHP

require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
return $SelectRowByIncrementQuery;
return $SelectedRow; //HERE is the error <-------------------------------
return $result;
}
$row = $SelectedRow;
echo $row;
if ($row['Id'] === max(mysqli_fetch_assoc($Id))){
$row['Id']=$row['Id'] === min(mysqli_fetch_assoc($Id));#TODO check === operator
}
else if($row['Id']=== min(mysqli_fetch_assoc($Id))){
$row['Id']=max(mysqli_fetch_assoc($Id));#TODO check === operator //This logic is important. DONT use = 1!
Ok, I am trying to write a program for the server end of my website using PHP. Using Netbeans as my IDE of choice I have encountered an error while attempting to write a function which will store a single row in an associative array.
The issue arises when I try to return the variable $SelectedRow. It causes an 'Unreachable Statment' warning. This results in the program falling flat on its face.
I can get this code to work without being contained in a function. However, I don't really feel that that is the way to go about solving my issues while I learn to write programs.
Side Notes:
This is the first question I have posted on SO, so constructive criticism and tips are much appreciated. I am happy to post any specifications that would help an answer or anything else of the sort.
I do not believe this is a so-called 'replica' question because I have failed to find another SO question addressing the same issue in PHP as of yet.
If anybody has any suggestions about my code, in general, I'd be stoked to hear, as I have only just started this whole CS thing.
You can only return one time. Everything after the first return is unreachable.
It's not entirely clear to me what you want to return from that function, but you can only return one value.
The return command cancels the rest of the function, as once you use it, it has served its purpose.
The key to this is to put all of your information in to an array and return it at the end of the function, that way you can access all of the information.
So try changing your code to this:
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
$returnArray = array();
$returnArray["SelectRowByIncrementQuery"] = $SelectRowByIncrementQuery;
$returnArray["SelectedRow"] = $SelectedRow;
$returnArray["result"] = $result;
return $returnArray;
}
And then you can access the information like so:
$selectedArray = SelectRowByIncrementFunc();
$row = $selectedArray["SelectedRow"]
And so forth...

Update and Insert into three tables simultaneously

I have a record that needs to be updated. If the update is successful, then it should insert record into three different tables. I did it with the code below,but one of the table(tab_loan_targetsave)is not inserting.I need a third eye to looked into this, as I have had a lot of pain in fathoming where the problem lies.
Pls i need assistance.Also, I welcome better approach if possible.
<?php
if(isset($_POST["savebtn"])){
$custNo = $_POST["custid"];
$transDate = $_POST["transDate"];
$grpid = $_POST["custgrp"];
$contAmount =$_POST["amtCont"];
$amount = $_POST["amount"];
$disAmount =$_POST["disbAmt"];
$savAmount =$_POST["savAmt"];
$intAmount =$_POST["intAmt"];
$postedBy = $_SESSION["staffid"];
//$preApproved =$_POST["preAmount"];
$loanRef = $_POST["refid"];
$st = "Approved";
$appDate = date("Y-m-d H:i:s");
$appBy = $_SESSION['staffid'];
$counter = 1;
$locate = $_SESSION['location'];
$insure = $_POST["insuAmt"];
$dis = $_POST["DisAmt"];
$update = mysqli_query($connection,"UPDATE tab_loan_request SET approval_status='$st',approvalDate='$appDate',approvedBy='$appBy',loanRef='$loanRef' WHERE custid='$custNo' AND RepayStatus='1'");
if($update && mysqli_affected_rows($connection)>0){
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef,'$savAmount','Cr','$postedBy','$locate','1')");
$insertInt = mysqli_query($connection,"INSERT INTO tab_loan_interest(custid,requestAmt,transactionDate,interestFees,postedBy,loanRef,InsuranceFees,DisasterFees)VALUES(
'$custNo','$amount','$transDate','$intAmount','$postedBy','$loanRef','$insure','$dis')");
//if($insertInt){
//}if($insertTar){
$insertSav = mysqli_query($connection,"INSERT INTO tab_loan_saving(custid,grpid,transactionDate,loanRef,loanAmount,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$amount','0','Cr','$postedBy','$locate','1')");
}//first if
if($insertSav){
echo "<span style='font-weight:bold;color:red;'>"." Application Approval is successful!"."</span>";
}else{
//Unable to save
echo "<span style='font-weight:bold;color:black;>"."Error! Application Approval not Successful!"."</span>";
}
}else{
$custid = "";$saving=0.00;$st="";
$transDate = "";
$grpid = "";
$amount = "";
$postedBy = "";$loanRef="";
}
?>
"#Fred: See the error generated when i used mysqli_error($connection). Could you please interprete this: ErrorMessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1000.00','Cr','SPL002','Ojo','1')' at line 2 – Dave"
Seeing the error generated by the suggestion I've given you to check for errors.
You're missing a quote here '$loanRef
in your query:
VALUES('$custNo','$grpid','$transDate','$loanRef , '$savAmount'...
^ right there
I suggest to escape all of your incoming data.
I.e.:
$var = mysqli_real_escape_string($connection, $_POST['var']);
and apply that same logic to all your POST arrays.
Plus, as I stated; make sure you started the session, since there is no mention of that in your question and session_start(); wasn't included in your posted code.
The session needs to be started inside all pages using sessions.
Using a prepared statement will is better.
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/pdo.prepared-statements.php
which is what you really should be using.
Additional references:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting
Also make sure there aren't any constraints in your table(s).
Dude make sure you properly escape your variables http://php.net/manual/en/mysqli.prepare.php
i would check the Table Name! make sure it is case sesntive, also just wondering if you could do something to your database design? It seems a lot of duplicate data is going into your tables. Think about a better way to organise and store that data
I got where the error is emanting from . Just because I forgot to add a single quote to one of the values. ie missing the quote- near $loanRef. No closing string. Anyway, I was able to detect that through the error message stated parameter as adviced by Fred nad Mark. Correct
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$savAmount','Cr','$postedBy','$locate','1')");
Thank you all.

MYSQLi PHP function fetch array

I am trying to retrieve a zone by running a PHP function based off of a place that has already been submitted.
Using FORM method GET, after submission, the variable that I am retrieving is:
$place = mysqli_real_escape_string($_GET['place]);
The variable immediately after is zone:
$zone = getZone($pol); // here is the PHP function call
Above both of these variables is the function getZone, which looks like this:
function getZone($place)
{
$searchZone = "SELECT ZONE FROM zones WHERE PLACE = '".$place."'";
$result = mysqli_query($dbc, $searchZone);
$row = mysqli_fetch_array($result);
return $row['ZONE'];
}
I can run the query in the database, and it returns the ZONE.
Now, the mysqli_fetch_array, which normally works for me, is failing to produce the result from the query.
Does anyone see what is wrong?
You've forgotten about PHP's variable scope rules:
$result = mysqli_query($dbc, $searchZone);
^^^^---- undefined
Since $dbc is undefined in the function, you're using a local null handle, which is invalid. If you'd had ANY kind of error handling in your code, you'd have been told about the problem.
Try
global $dbc;
$result = mysqli_query(...) or die(mysqli_error($dbc));
instead. Never assume success. Always assume failure, check for that failure, and treat success as a pleasant surprise.
This might help
//Assuming $dbc as connection variable
function getZone($dbc,$place)
{
$searchZone = "SELECT ZONE FROM zones WHERE PLACE = '".$place."'";
$result = mysqli_query($dbc, $searchZone);
$row = mysqli_fetch_array($result);
return $row['ZONE'];
}
include 'path/to/connectionfile';//Only if you haven't already done that
$zone = getZone($dbc,$pol);
Ok... I figured it out, thanks to the assistance of Marc B. I took into account that I was not providing my connection string, so I added it to the file. Problem is, I needed to add it to the actual function, like so:
function getZone($place)
{
include ("../include/database.php");
// then the rest of the code
After I included the database connection, I am now able to retrieve the zone.
Thank you.

Adding a secondary WHERE statement to PDO/MySql statement

I have a PDO/MySQL database connection. My database holds content for various landing pages. To view these landing pages I enter *localhost/landing_page_wireframe.php* and append with ?lps=X (where X represents the Thread_Segment) to display the particular page in the browser. I am now getting to second iterations of these pages and need to add a secondary classifier to follow "Thread_Segment" to distinguish which version I am trying to pull up. Here is a snippet of my current working query.
<?php
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps";
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
$thread = "";
$threadSegment = "";
$version = "";
$categoryAssociation = "";
while($row = $stmt->fetch()) {
$thread = $row["Thread"];
$threadSegment = $row["Thread_Segment"];
$version = $row["Version"];
$categoryAssociation = $row["Category_Association"];
}
?>
So I need to now change this to add in the secondary classifier to distinguish between versions. I would imagine my query would change to something like this:
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps AND Version = :vrsn";
if this is correct so far, then where I am beginning to get lost is in the following PHP code.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
I imagine I need to include some secondary iteration of this in my php to talk to the secondary classifier, but not totally sure how to go about this, and then I would imagine my url appendage would go from ?lps=X to something like this ?lps=X&vrsn=Y (Y representing the version).
I should state that I am somewhat new to PHP/MySql so the answer here may be simple, or may not even be possible. Perhaps I am not even going about this the correct way. Thought you all might be able to shed some insight, or direction for me to curve my research on the matter to. Thanks and apologies for any improper terminology, as I am definitely new to these technologies.
The URL change is as you describe. Just add another bindParam call to use that parameter:
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
Adding another bindParam() should work here.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
You can access it via ?lps=X&vrsn=Y but just as a warning, the query will fail if those $_GET params are not requested. I recommend defaulting it to something prior to sending it through the query:
$stmt = $connection->prepare($result);
$lps = isset($_GET['lps']) ? $_GET['lps'] : 'default lps value';
$vrsn = isset($_GET['vrsn ']) ? $_GET['vrsn '] : 'default vrsn value';
$stmt->bindParam(':lps', $lps);
$stmt->bindParam(':vrsn', $vrsn);
$stmt->execute();

Categories