How do I optimize these two lines? - php

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'];
}

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

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

PHP Variable - Multiply pages

I have a functions.php page, I have included in ALL my other php pages. What I want is a function in my functions.php page, I can use in all the other pages.
I have tried this:
function getSetting()
{
$r=mysql_query("SELECT * FROM settings");
if(mysql_num_rows($r) == 0)
return false;
else
$sdata=mysql_fetch_assoc($r);
return $sdata;
}
The thing I want to, I want to get the data from the row next to the name in the following picture: http://awesomescreenshot.com/0bci8x472
Example:
If I write $sdata['sitename'], I want it to output "ptcify"
Thanks!
Try using mysql_fetch_array() with MYSQL_ASSOC as documented at this link http://www.php.net/manual/en/function.mysql-fetch-array.php.
There are a lot of things you could do to further improve your code implementation i.e OOP, using better database abstraction libraries(even switching to PDO insted of PHP_MYSQL is an improvement), but this should work straight of the bat.
Most questions usually have a ? in them somewhere, to indicate an actual question. I'm not sure what the problem with your code is, but I'm guessing you're only getting a single "setting" result - if that query returns multiple rows, you have to loop over the result set and get each row, THEN return:
$r = mysql_query(...) or die(mysql_error());
$sdata = array()
while ($row = mysql_fetch_assoc($r)) {
$sdata[] = $row;
}
return $sdata
edit
$sql = "SELECT setting_name, setting_value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
$sdata = array();
while($row = mysql_fetch_assoc($result)) {
$sdata[$row['setting_name']] = $row['setting_value'];
}
return $sdata;

PHP problem with die()

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?

mysql_fetch_assoc() returning unexpected value

I am working on a project where I use mysql_fetch_assoc to return an associative array.
However, I am puzzled as to why it would return TRUE
I have looked at the PHP manual page, and the only boolean value it should be returning is FALSE, and then only on a fail.
Although I am using a custom set of abstraction classes, it is basically doing this:
$result = mysql_query("SELECT * FROM table WHERE filename = 'test1.jpg'");
var_dump(mysql_fetch_assoc($result)); // bool(true)
Does anyone know why it would be returning TRUE instead of an array?
Update
Well, after trying a few things, I've determined its my library, as running the above code returns an associative array. I don't know why exactly it was returning TRUE, but for now, I am going to stop making things more complicated than they have to be (a problem of mine) and just use mysqli (thanks for the tip, Michael) instead of my own ActiveRecord classes, which apparently don't work.
Thanks!
I ran into the same thing. It was a stupid coding error on my part.
I started out with:
$result = mysql_query($someSql);
while($row = mysql_fetch_assoc($result)) {
// do stuff
}
which worked fine. Then I changed it to:
$result = mysql_query($someSql);
while($row = mysql_fetch_assoc($result) && $someCondition) {
// do stuff
}
This is interpreted as $row = (mysql_fetch_assoc($result) && $someCondition), which means $row becomes true while there are rows left and the second condition is true.
What I meant to write was:
$result = mysql_query($someSql);
while(($row = mysql_fetch_assoc($result)) && $someCondition) {
// do stuff
}
Start using mysqli_query mysqli_fetch_assoc, . The old version is soon to be outdated - the new one is better anyways.
Have you tried:
print_r (mysql_fetch_assoc($result));
It may give what you are looking for.
Oh, and silly me, var_dump () returns nothing, it directly outputs its findings like print_r ().

Categories