PHP problem with die() - php

So, I have this code:
} else {
$photograph_moderation = new PhotographModeration($this->photograph_id);
$photograph_moderation->purgePhotograph();
//eventually take to an error page
die('image is not big enough to upload');
}
the purgePhotograph() function gets called properly when this condition is met, but the script never appears to die. Is there a reason why die wouldn't get called here? purgePhotograph() has no script killing commands either.
Here's the purge_photograph function:
public function purgePhotograph() {
$db = Connect::connect();
$photograph_id = $db->real_escape_string($this->photograph_id);
$query = "SELECT * from photographs WHERE id='{$this->photograph_id}'";
$result = $db->query($query);
$photograph = $result->fetch_assoc();
if ($photograph['location'])
unlink($photograph['location']);
if ($photograph['thumbnail_location'])
unlink($photograph['thumbnail_location']);
if ($photograph['watermark_location'])
unlink($photograph['watermark_location']);
if ($photograph['xsmall_location'])
unlink($photograph['xsmall_location']);
if ($photograph['small_location'])
unlink($photograph['small_location']);
if ($photograph['medium_location'])
unlink($photograph['medium_location']);
if ($photograph['large_location'])
unlink($photograph['large_location']);
if ($photograph['xlarge_location'])
unlink($photograph['xlarge_location']);
if ($photograph['xxlarge_location'])
unlink($photograph['xxlarge_location']);
if ($photograph['xxxlarge_location'])
unlink($photograph['xxxlarge_location']);
$query = "DELETE from photographs WHERE id='{$this->photograph_id}'";
$result = $db->query($query);
$query = "DELETE from photograph_tags WHERE photograph_id='{$this->photograph_id}'";
$result = $db->query($query);
}

Check if purgePhotograph() returns. Maybe it has a deadloop or takes really long time.

Maybe now is the time to install a php debugger module and step into the code in question.
xdebug and e.g. netbeans as the frontend work well enough.

Wow, the problem was purgePhotograph() never had a return 1; at the end. I didn't know this was required for following lines to execute.

Try to put it into an try/catch block.
Maybe something is throwing an exception before die can get executed.
Are you getting any error?

Related

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...

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.

How do I optimize these two lines?

So, I have these two lines of PHP.
$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db));
$total_row_count = $total_row_count['count'];`
Is there any way to change the first declaration of $total_row_count so the 2nd line isn't necessary?
Something to this effect (I know this isn't functional code).
$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db))['count'];
Thanks so much!
You second snippet is perfectly functional since PHP 5.4. It's called direct array dereferencing.
However, you should never ever do mysql_fetch_assoc(mysql_query(...)). The mysql_query call may fail and return false, which propagates ugly errors into mysql_fetch_assoc. You need error handling!
$result = mysql_query(...);
if (!$result) {
die(mysql_error());
// or
return false;
// or
throw new Exception(mysql_error());
// or whatever other error handling strategy you have
}
$row = mysql_fetch_assoc($result);
$count = $row['count'];
If this is too much code for you to repeat often, wrap it in a function.
function getCount() {
$result = mysql_query(...);
...
return $row['count'];
}

Using PHP and oci8 to handle a query

This is a past paper question for a database class that I'm stuck with. I'm just preparing for my exam, so it's okay to give away the answer.
Consider the following schema:
Borrow(userid: string, callnum: string, copynum: integer, checkout: date, return: date)
Here is the PHP function that has an error.
function countCheckedOutBookCopies($callnum){
$sql = "SELECT COUNT(*) AS bookcount FROM borrow
WHERE return = null and callnum = '".$callnum."'";
$stid = oci_parse($this->conn, $sql); //assume $this->con is correct
if($row = oci_fetch_object($stid)){
return $row->bookcount;
} else{
return -1;
}
}
There are 3 questions.
1.Find the error and fix it.
2.Another error occurs, fix it.
3.Despite everything being fixed, the function would return -1 all the time. Why is this?
I'm only familiar with procedural PHP using MySQL. But I tried running the code and was resulted with $stid returning boolean all the time because I don't know which part is right and which part is wrong.
Here are the things I've tried
1.Changing '".$callnum."' to just simply '$callnum' (because this is how I've always done it in MySQL)
2.Changing return = null to return = 'null' (but I don't think this is the case)
3.Maybe there is something wrong with the concept of getting COUNT(*) instead of just *
EDIT: Just a thought: I feel like oci8 and MySQL do pretty much the same thing, but is there a reason to prefer one over another? I'm sure MySQL is the more popular one, but my school seems to prefer using oci8 for exam questions
Thanks in advance!
Despite the "Find the error" and "Another error occurs":
1.) "return is null",
2.) this->conn is probably supposed to be this->con,
3.) the code is missing oci_execute($stid);,
4.) oci_free_statement($stid);.
function countCheckedOutBookCopies($callnum){
$sql = "SELECT COUNT(*) AS bookcount FROM borrow
WHERE return is null and callnum = '$callnum'";
$stid = oci_parse($this->con, $sql); //assume $this->con is correct
oci_execute($stid);
$ret = -1;
if($row = oci_fetch_object($stid)){
$ret = $row->bookcount;
}
oci_free_statement($stid);
return $ret;
}

Web browser is returning nothing - function error?

When I access this from a web browser it returns nothing other than echo'd text, I know this is similar to another question I posted but I can't make sense of it?
<?php
include('config.php');
include('database.php');
class conversion{
public $amnt;
public $cc_from;
public $cc_to;
public function __construct (){
$this->amnt = htmlspecialchars($_GET["amnt"]);
$this->cc_from = htmlspecialchars($_GET["from"]);
$this->cc_to = htmlspecialchars($_GET["to"]);
}
function convert($this->amnt,$this->cc_from,$this-cc_to,$decimals=2){
$db_rate_from = mysql_query("SELECT * FROM _currency WHERE country_code='$this- >cc_from'") or die(mysql_error());;
$query_row_from = mysql_fetch_array($db_rate_from);
$rate_from = ($query_row_from['rate']);
echo $rate_from;
echo "</br>rate to</br>";
$db_rate_to = mysql_query("SELECT * FROM _currency WHERE country_code='$this->cc_to'") or die(mysql_error());;
$query_row_to = mysql_fetch_array($db_rate_to);
$rate_to = ($query_row_to['rate']);
echo $rate_to;
echo "</br>conversion</>";
$conversion = (number_format(($amnt/$rate_from)*$rate_to,$decimals));
echo $conversion;
} }
$var = new conversion();
$var->convert($amnt,$cc_from,$cc_to);
?>
Given this:
$db_rate_from = mysql_query("SELECT * FROM $db_tbprefix WHERE country_code='$this->cc_from'");
where is $db_tbprefix defined? Nowhere, causing your query to be SELECT * FROM WHERE .... If you had proper SQL error handling code, this would've been clear to you. At absolute bare minimum, you should have something like:
$result = mysql_query("...") or die(mysql_error());
which would abort the script on a query failure and tell you exactly why the query failed.
As well, htmlspecialchars is NOT intended for database operations. It does absolutely nothing to prevent SQL injection. For that, you have to use mysql_real_escape_string().
One thing I notice is that you call your method without parameters.
$var->convert();
Yet it is declared to take three mandatory parameters.
function convert($amnt,$cc_from,$cc_to,$decimals=2)
And btw, don't use $query_row_to[rate]. Use either $query_row_to['rate'] or $query_row_to[$rate].
Edit:
How about something like this? Use global $db_tbprefix and skip object orientation.
<?php
include('config.php');
include('database.php');
function convert($amnt,$cc_from,$cc_to,$decimals=2) {
global $db_tbprefix;
$db_rate_from = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_from'") or die mysql_error();
$query_row_from = mysql_fetch_assoc($db_rate_from);
$rate_from = $query_row_from['rate'];
$db_rate_to = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_to'") or die mysql_error();
$query_row_to = mysql_fetch_assoc($db_rate_to);
$rate_to = $query_row_to['rate'];
return number_format(($amnt/$rate_from)*$rate_to,$decimals);
}
echo convert(floatval($_GET["amnt"]), mysql_real_escape_string($_GET["from"]), mysql_real_escape_string($_GET["to"]));
?>
Edit 2: only select what you need, in this case rate. And use mysql_fetch_assoc rather than than mysql_fetch_array which will double your memory consumption and slow down your code.
haven' tested it ... but the possibility i can find is you are passing parameters in function convert while defining it so you need to pass the same param while calling it... OR if the variables are the reference from the predefined one then use them like this
function convert($this->amnt,$this->cc_from,$this->cc_to,$decimals=2){
}

Categories