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...
Related
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.
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'];
}
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;
}
I'm just getting started on writing functions instead of writing everything inline. Is this how a reusable function is typically written?
function test_user($user) {
$conn = get_db_conn();
$res = mysql_query("SELECT * FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
if (count($row) == 1) {
return true;
}
else {
return false;
}
}
When someone logs in, I have their UID. I want to see if that's in the DB already. It's basic logic will be used in a
"If exists, display preferences, if !exists, display signup box" sort of flow. Obviously it's dependent on how it's used in the rest of the code, but will this work as advertised and have I fallen for any pitfalls? Thanks!
Try this:
$conn = get_db_conn(); # should reuse a connection if it exists
# Have MySQL count the rows, instead of fetching a list (also prevent injection)
$res = mysql_query(sprintf("SELECT COUNT(*) FROM users WHERE uid=%d", $user));
# if the query fails
if (!$res) return false;
# explode the result
list($count) = mysql_fetch_row($res);
return ($count === '1');
Thoughts:
You'll want better handling of a failed query, since return false means the user doesn't already exist.
Use the database to count, it'll be faster.
I'm assuming uid is an integer in the sprintf statement. This is now safe for user input.
If you have an if statement that looks like if (something) { true } else { false } you should collapse it to just return something.
HTH
That is reuseable, yes. You may want to consider moving the SQL out of the PHP code itself.
Although you weren't asking for optimization necessarily, you might want to consider querying for the user's display preferences (which I assume are stored in the DB) and if it comes back empty, display the signup box. You'll save a trip to the database and depending on your traffic, that could be huge. If you decide to keep this implementation, I would suggest only selecting one column from the database in your SELECT. As long as you don't care about the data, there's no reason to fetch every single column.
First off, you need to call
$user = mysql_real_escape_string($user);
because there's an sql injection bug in your code, see the manual. Second, you can simplify your logic by changing your query to:
SELECT COUNT(1) FROM user WHERE uid = $user;
which just lets you evaluate a single return value from $row. Last thing, once you have the basics of php down, consider looking at a php framework. They can cause you trouble and won't make you write good code, but they likely will save you a lot of work.
Indent!
Overall it looks not bad...check the comments..
function test_user($user)
{
$conn = get_db_conn(); //this should be done only once. Maybe somewhere else...?
$res = mysql_query("SELECT uid FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
//I can't remember...can you return count($row) and have that forced to boolean ala C? It would reduce lines of code and make it easier to read.
if (count($row) == 1) {
return true;
}
else {
return false;
}
}
Also,
if (condition) {
return true;
}
else {
return false;
}
can be rewritten as:
return condition;
which saves quite a bit of typing and reading :)
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 ().