How is it possible to retrieve the mysql_query from a function? For instance:
class A() {
...
function getAll($l=1) {
...
$result = mysql_query($query);
return $result
}
...
}
$a = new A();
$r = $a -> getAll(2);
while ($row = mysql_fetch_assoc($r)) {
// do something
}
This code above does not work when I return $result from the function. However, when I use the mysql_fetch_assoc function in getAll function, it works perfectly. So basically, my question is how to return a mysql result set from a function?
** EDIT **
I actually get no errors. The while statement used liked above will just not execute. But the query works perfectly when I execute it from within the getAll function.
Don't return the result resource from the query, but rather return the data extracted from that resource:
$data = array();
while ( $row = mysql_fetch_assoc($result) ) {
$data[] = $row;
}
return $data;
Absolutely it works.
Do a var_dump($r) to make sure you're getting a resource. If not, double-check your SQL. There may be an error in it.
Also turn on other error reporting at the top of your script (as well as checking mysql_error) for better clues as to what's wrong:
ini_set('display_errors', true);
error_reporting(E_ALL);
You've edited much of your code so it's difficult to investigate further. Just make sure that your method is not closing the mysql connection.
Related
I'm tried to call a method that contains execution of stored procedure in a loop but, in first tome procedure call working fine and returning result but, second time on wards it not working and even not returning any errors.
$list = array();
for($i = 0; $i < count($dataArr); $i++)
{
$Test = new Test();
$returnData = $Test->run_procedure($dataArr[$i]);
$list[] = $returnData;
}
and the run procedure method code is
public function run_procedure($data){
global $connection;
$result = mysqli_query($connection, "call sp_test('$data->site', '$data->user_id', '$data->order_user_id', '$data->credit', #ledger_id1, #paid_id)");
$procResult = mysqli_query($connection, "select #ledger_id1 as ledger_id, #paid_id paid_id;");
$returnData = mysqli_fetch_object($procResult);
return $returnData;
}
I tried to solve this but, i didn't find any needful information. Thank you.
Making a new connection for every time in a loop. Created a new method that returns a connection. Calling that method to create new connection and closing that connection before completion method execution.
This is the first time I've ever asked a question on here, but I've used stackoverflow many times in the past to find solutions for problems I'm having in my code.
I'm working on a database transfer page on a php site that uploads csv files and updates the database, and depending on the type of update the user selects this data can be updated/inserted by key. Because of this I want to run DBCC CHECKIDENT after the updates have been made to ensure that new entries will be incremented correctly after the largest key in the table.
This is the php code I'm running:
$getMaxID = new Query("SELECT MAX($tableKeys[$t]) as max from $t", __LINE__, __FILE__);
$maxID = $getMaxID->result(0,'max');
$result = new Query("DBCC CHECKIDENT ('$t', RESEED, $maxID)", __LINE__, __FILE__);
$t is the table name stored in an array of table names.
I get the following error from this code:
There has been a system error. We apologize for the inconvienience.
Error Details: [Microsoft][SQL Server Native Client 11.0][SQL Server]Checking identity information: current identity value '16', current column value '16'.
Line #: 615
File: C:\OCPOS\htdocs\OCPOS\menuTransfer\importMenu.php
Query: DBCC CHECKIDENT ('table', RESEED, 16)
What's confusing me is when I cut an paste DBCC CHECKIDENT ('table', RESEED, 16) into server management studio it works and i get:
Checking identity information: current identity value '16', current column value '16'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
If anyone has any ideas what is causing this or if there's a post I missed that addresses this issue any help would be much appreciated.
Below is the query class. I didn't make it:
class Query{
var $stmt; //hold link to result
var $queryStr; //hold string
var $queryLine;
var $queryFile;
function Query($str, $line, $file)
{
global $conn;
$this->queryStr = $str;
$this->queryLine = $line;
$this->queryFile = $file;
$this->stmt = #sqlsrv_query($conn, $this->queryStr, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET)) or $this->error(sqlsrv_errors());
}
function error($var)
{
echo "
<p style='border: 1px solid #c00; margin: 5px; padding: 5px;'>
There has been a system error. We apologize for the inconvienience.<br/>
Error Details: ". $var[0]['message'] ."<br/>
Line #: $this->queryLine<br/>
File: $this->queryFile<br/>
Query: $this->queryStr<br/>
</p>
";
}
function fetch_array()
{
$array = sqlsrv_fetch_array($this->stmt);
if(is_array($array))
return $array;
else
{
return false;
}
}
function fetch_assoc_array()
{
$array = sqlsrv_fetch_array($this->stmt, SQLSRV_FETCH_ASSOC);
if(is_array($array))
return $array;
else
{
return false;
}
}
function num_rows()
{
return sqlsrv_num_rows($this->stmt);
}
function numrows()
{
return $this->num_rows();
}
function result($row, $var)
{
$array = sqlsrv_fetch_array($this->stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_FIRST);
return $array[$var];
}
function all() {
$return = array();
while ($tmp = $this->fetch_array()) {
$return[] = $tmp;
}
return $return;
}
function arr() {
return $this->fetch_array();
}
function getAll() {
$return = array();
while ($tmp = $this->fetch_array()) {
$return = array_merge($return, $tmp);
}
return $return;
}
function extract($var) {
$rv = array();
while ($tmp = $this->fetch_array()) {
$rv[] = $tmp[$var];
}
return $rv;
}
}
I believe what is happening is that the database driver in PHP is assuming that any output from the database connection (as opposed to Result Sets, which are returned separately) is some form of error. Note that the output you get from SQL Server is actually identical in the two cases, except for some extra context information. I have seen similar problems when the ROW_COUNT setting is left on, with the textual "rows affected/returned" message interpreted as an error.
Since DBCC commands are, to put it nicely, not very standardised, I doubt there is any way to suppress this message at the SQL Server end. However, since you know that it is not really an error, you should be able to simply ignore it on the PHP side. You are already suppressing PHP's own error mechanism with the # operator, so just need a version of your Query method without the or $this->error(sqlsrv_errors());.
Incidentally, this is a good example of the value of separating responsibilities carefully: since the database abstraction class has taken responsibility for formatting the error into HTML and displaying it to the user, you are more-or-less forced to alter or replace that logic. If, instead, it threw an Exception, your calling code could catch this particular case while leaving others to pass through to a global error-handler which formatted the message appropriately.
I have a function which is using recursion to call itself and I need to know the correct syntax for calling itself.
Note: I am using Object oriented programming technique and the function is coming from a class file.
Below is my function
// Generate Unique Activation Code
//*********************************************************************************
public function generateUniqueActivationCode()
{
$mysql = new Mysql();
$string = new String();
$activation_code = $string->generateActivationCode();
// Is Activation Code Unique Check
$sql = "SELECT activation_id FROM ". TABLE_ACTIVATION_CODES ." WHERE activation_code='$activation_code' LIMIT 1";
$query = $mysql->query($sql);
if($mysql->rowCount($query) > 0)
{
// This function is calling itself recursively
return generateUniqueActivationCode(); // <- Is this syntax correct in Oops
}
else
{
return $activation_code;
}
}
Should the code to call it recursively be
return generateUniqueActivationCode();
OR
return $this->generateUniqueActivationCode();
or if something else other than these 2 ways.
Please let me know.
You would need to call it with the $this variable since your function is part of the instance. So:
return $this->generateUniqueActivationCode();
PS: Why not just try both methods and see if it generates any errors?
Recursion is the COMPLETELY WRONG WAY TO SOLVE THIS PROBLEM
Unlike iteration you're filling up the stack, and generating new objects needlessly.
The right way to solve the problem is to generate a random value within a scope which makes duplicates very unlikely, however without some external quantifier (such as a username) to define the scope then iteration is the way to go.
There are further issues with your code - really you should be adding records in the same place where you check for records.
I am using Object oriented programming technique and the function is coming from a class file
Then it's not a function, it's a method.
And your code is susceptibale to SQL injection.
A better solution would be:
class xxxx {
....
public function generateUniqueActivationCode($id)
{
if (!$this->mysql) $this->mysql = new Mysql();
if (!$this->string) $this->string = new String();
$limit=10;
do {
$activation_code = $string->generateActivationCode();
$ins=mysql_escape_string($activation_code);
$sql="INSERT INTO ". TABLE_ACTIVATION_CODES ." (activation_id, activation_code)"
. "VALUES ($id, '$ins)";
$query = $mysql->query($sql);
if (stristr($query->error(), 'duplicate')) {
continue;
}
return $query->error() ? false : $activation_code;
} while (limit--);
return false;
}
} // end class
I'm having this weird problem right now, I'm just working on a small admin backend thing that will allow users to upload a file and download it again, simple stuff.
I'm using PHP OOP with Classes and functions and things. Still pretty new at it. Currently on one page I have a "getRecentLinks" function that will call information from a couple tables and put it all out on the page in a table, it works just fine. One of the options on this page is to download the file that was uploaded to that individual row. So I just want it to be a link you click on to say, file-download.php?id=3.
Now on file-download.php I'm currently just testing to get the information on the page before I add the headers and things in there. So I just have a simple
$l = new Links();
$file = $l->getFileInfo($_GET['id']);
print_r($file);
this SHOULD just return information from the database, id, name of file, size, data, and mimetype.
Now this doesn't work. I have no idea why but it doesn't.
Now on my page where I have the getRecentLinks() function it works just fine. I even brought in the getRecentLinks() into my file-download.php page so it's setup like this.
$l = new Links();
$l->getRecentLinks();
$file = $l->getFileInfo($_GET['id']);
print_r($file);
This works just fine and dandy, The second I remove getRecentLinks() it stops calling information from getFileInfo() and I cannot figure it out. I mean it's not a huge deal i could just keep #l->getRecentLinks() there but I can see this getting annoying if I have to add it to every page I want to do something, I'm just at the start of this project.
Here's the code in the Links class
public function getFileInfo($id)
{
$result = $this->runQuery("SELECT * FROM file WHERE id ='".mysql_real_escape_string($id)."'");
$resultSet = $this->fetch($result);
return $resultSet;
}
and
public function getRecentLinks()
{
$result = $this->runQuery("SELECT * FROM links ORDER BY date DESC");
while($j = $this->fetch($result))
{
$resultSet[] = $j;
}
return $resultSet;
}
And heres my connections and fetch functions a friend helped me develop
public function runQuery($sql) {
$this->connection = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
if(!$this->connection) {
die("MySQL is down.");
} else {
mysql_select_db($this->dbname);
}
$result = mysql_query($sql,$this->connection) or die(mysql_error());
return $result;
}
public function fetch($result)
{
$resultSet = mysql_fetch_assoc($result);
return $resultSet;
}
mysql_real_escape_string requires a connection. Since getRecentLinks opens a connection it works. But you call mysql_real_escape_string before runQuery (in execution order) in getFileInfo. In this case, I assume the id is an integer, so you're better off and a lot cheaper to call intval($_GET['id']).
if running function returns server misconfiguration error
function build_path($cid)
{
$result = array();
$DB = new MySQLTable;
$DB->TblName = 'shop_categories';
$where['cat_id']['='] = $DB->CleanQuest($cid);
$res = $DB->Select('cat_id,cat_name,cat_parent', $where);
if($res !== 'false')
{
$pid = mysql_fetch_array($res);
if($pid['cat_parent'] !== 0)
{
Echo $pid['cat_parent'];
build_path($pid['cat_parent']);
} else {
Echo $pid['cat_id'];
return true;
}
}
return false;
}
I can't find an error here. Please help.
Sorry for disturbing you all. The trouble was in comparison 'if($pid['cat_parent'] !== 0)': $pid['cat_parent'] was a string with int(0)
Can i build this function to store full path without using GLOBALS and SESSION vars?
Things to check for:
Is cat_parent ever null?
Are there any recursively parented pairs (A is parent of B, B is parent of A; A->B, B->C, C->A)?
Are there any cases where the row is self parented (A is parent of A)
Try making this modification (for debugging):
function build_path($cid) {
static $done = array();
if (isset($done[$cid])) {
throw new Exception('We have already looked up CID: '.$cid);
} else {
$done[$cid] = true;
}
//.......
}
That will let you tell if you've got a recursive loop going on.
Also, set error_reporting to max, and check your error log. My guess is that it's either a stack overflow (your recursion is going too deep) or a memory limit issue (that it uses up too much memory and is killed)...