Here is my code. Basically it generates a random string and I want to regenerate if the generated code exists in my db, but I always get recurring error.
What can I do to stop recurring error?
Here's my error
cannot redeclare exists_in_db (previously declared)
Code:
function exists_in_db($str)
{
$check_badge_in_paids = "sql query";
return mysqli_num_rows($check_badge_in_paids) > 0;
}
function rand_string()
{
$str = "";
do
{
$str = substr(md5(microtime()), 0, 5);
}
while(exists_in_db($str));
return $str;
}
Well Crys that error would only occur if you've previously declared that function, so here's what I advice you do, clear this code and do this:
var_dump(function_exists('exists_in_db'));
OR:
at the top where you have declared the function, do this:
var_dump(function_exists('exists_in_db'));
die;
if it returns true, then you have to check you code for previous declarations, probably included files etc.
Related
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 set in myFile.php this function:
function monthLanguage()
{
if ($this->lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
}
I was thinking to wrap this if statement into a function to call it where is needed as a kind of short code.
I call it like this:
monthLanguage();
but I get error message: Call to undefined function
Any help on how to reach my short code intent?
Are you including the monthLanguage function the file you are using it in? Also, I spotted two issues with this code. You are not initiating the array called $dayName and nothing is being returned so the function will not send back output. It should be like this.
function monthLanguage()
{
$dayName = array();
if ($this->lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
return $dayName;
}
Also, the $this is not clear since that is usually used in the scope of a class, so perhaps you need to set the function like this:
function monthLanguage($lang)
{
$dayName = array();
if ($lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
return $dayName;
}
And you would then call the function in PHP like this:
monthLanguage($this->lang);
Or like this:
monthLanguage($lang);
But it is unclear where this function is being placed or used, so clarify that to decide which is the best way to handle.
I don't think you can use $this->lang - it's usually reserved for a method if I'm not mistaken.
Try replacing the function with this, should work like a charm.
function monthLanguage($lang) {
if ($lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
}
Ok, so I just finished off a function for validating the firstname field on a form.
This function works correctly on its own.
But since I want to make this function re-usable for more than one website, I added an if statement for whether or not to use it. The following code explain this:
Related PHP code:
//Specify what form elements need validating:
$validateFirstname = true;
//array to store error messages
$mistakes = array();
if ($validateFirstname=true) {
//Call first name validation function
$firstname = '';
if (!empty($_POST['firstname'])) {
$firstname = mysql_real_escape_string(stripslashes(trim($_POST['firstname'])));
}
$firstname = validFirstname($firstname);
if ($firstname === '') {
$mistakes[] = 'Your first name is either empty or Enter only ALPHABET characters.';
}
function validFirstname($firstname) {
if (!ctype_alpha(str_replace(' ', '', $firstname))) {
return '';
} else {
return $firstname;
}
}
}
So without this if ($validateFirstname=true) the code runs fine, but the moment I add it; I get the following error message:
Fatal error: Call to undefined function validFirstname()
Are you not able to use functions in if statements at all in PHP? I'm fairly new to using them in this way.
Conditional functions (functions defined inside the conditions) must be defined before they are referred. Here's what manual says:
Functions need not be defined before they are referenced, except when
a function is conditionally defined as shown in the two examples
below.
When a function is defined in a conditional manner such as the two
examples shown. Its definition must be processed prior to being
called.
So if you want to use it that way, you should put it either at the beginning of the if condition or outside the condition.
// Either:
if ($validateFirstname==true) {
function validFirstname($firstname) {}
}
// Or, and I'd rather do it this way, because function is
// created during "compilation" phase
function validFirstname($firstname) {}
if ($validateFirstname==true) {
// ...
}
Also not that function (even if created inside the condition) is pushed to global scope:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
So once code is evaluated it doesn't matter if it's declared inside condition or intentionally in global scope.
Functions that are declared in a conditional context (like if body), you can only use after their declaration.
if ($validateFirstname == true) {
//Call first name validation function
function validFirstname($firstname) {
// function body
}
// $firstname initialisation
$firstname = validFirstname($firstname);
// ...
}
(P.s.: changed $validateFirstname = true to $validateFirstname == true which should be what you want)
if($validateFirstname=true)
you are assigning the value "true" to $validateFirstname here
you should use a "==" for comparison e.g
if($validateFirstname==true)
that might help your "if" problem
I am trying to get some errors returned in JSON format. So, I made a class level var:
public $errors = Array();
So, lower down in the script, different functions might return an error, and add their error to the $errors array. But, I have to use return; in some places to stop the script after an error occurs.
So, when I do that, how can I still run my last error function that will return all the gathered errors? How can I get around the issue of having to stop the script, but still wanting to return the errors for why I needed to stop the script?!
Really bare bones skeleton:
$errors = array();
function add_error($message, $die = false) {
global $errors;
$errors[] = $message;
if ($die) {
die(implode("\n", $errors));
}
}
If you are using PHP5+ your class can have a destructor method:
public function __destruct() {
die(var_dump($this->errors));
}
You can register a shutdown function.
Add the errors to the current $_SESSION
Add the latest errors to any kind of cache, XML or some storage
If the code 'stops':
// code occurs error
die(print_r($errors));
You can use a trick involving do{}.
do {
if(something) {
// add error
}
if(something_else) {
// add error
break;
}
if(something) {
// add error
}
}while(0);
// check/print errors
Notice break, you can use it to break out of the do scope at any time, after which you have the final error returning logic.
Or you could just what's inside do{} inside a function, and use return instead of break, which would be even better. Or yes, even better, a class with a destructor.
I ran into a very strange behaviour in some of our PHP code today. We have a class for dealing with files. It's something like this:
class AFile {
//usual constructor, set and get functions, etc.
//...
public function save() {
//do some validation
//...
if($this->upload()) { //save the file to disk
$this->update_db(); //never reached this line
}
}
private function upload() {
//save the file to disk
//...
return ($success) ? true : false;
}
}
It looked pretty normal to us, but the $this->upload() function never returned anything but NULL. We checked that the correct function was running. We echoed out its return value before it returned. We tried only returning a true value or even a string. Everything was checking out right. But $this->upload still evaluated to NULL. Also, there was nothing in the logs and ERROR_ALL is on.
In exasperation we changed the function name to foo_upload. All of a sudden everything worked. "upload" is not in the list of PHP reserved words. Anyone have any thoughts why a class function named "upload" would fail?
Make sure the return statement at the end of the upload method is the only return statement in that method.
One way to get null when "calling" upload would be if you had this (trying to access an inexisting property) :
if($a = $this->upload) { // => NULL
$this->update_db(); //never reached this line
}
var_dump($a);
instead of this (from OP) (trying to call an existing method):
if($a = $this->upload()) { // => true or false
$this->update_db(); //never reached this line
}
var_dump($a);
Did you check you didn't forget the () ?
If it's not this, try with error_reporting set to E_ALL, and displaying the errors :
ini_set('display_errors', true);
error_reporting(E_ALL);
(you said "ERROR_ALL is on", so not sure it's what you meant)