Reference - What does this error mean in PHP?
What is this?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix. This is also a Community Wiki, so everyone is invited to participate in adding to and maintaining this list.
Why is this?
Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in his/her particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.
What should I do here?
If your question has been marked as a duplicate of this, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.
If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.
The List
Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)- Code doesn't run/what looks like parts of my PHP code are output
- Warning: Cannot modify header information - headers already sent
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource a.k.a.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given (or similar variations)- Warning: [function] expects parameter 1 to be resource, boolean given
- Warning: [function]: failed to open stream: [reason]
- Warning: open_basedir restriction in effect
- Warning: Division by zero
- Warning: Illegal string offset 'XXX'
- Parse error: syntax error, unexpected '['
- Parse error: syntax error, unexpected T_XXX
- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
- Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
- Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
- Parse error: syntax error, unexpected T_VARIABLE
- Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
- Fatal error: Call to a member function ... on a non-object
- Fatal Error: Call to Undefined function XXX
- Fatal Error: Cannot redeclare XXX
- Fatal error: Can't use function return value in write context
Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB() '- Fatal error: Using $this when not in object context
- Notice: Array to string conversion
- Notice: Trying to get property of non-object error
- Notice: Undefined variable
- Notice: Undefined Index
Notice: Undefined offset XXX [Reference]- Notice: Uninitialized string offset: XXX
- Notice: Use of undefined constant XXX - assumed 'XXX'
- MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
- Strict Standards: Non-static method [<class>::<method>] should not be called statically
- Warning: function expects parameter X to be boolean/string/integer
- HTTP Error 500 - Internal server error
Also, see
- Reference - What does this symbol mean in PHP?
php mysql debugging warnings
|
show 1 more comment
What is this?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix. This is also a Community Wiki, so everyone is invited to participate in adding to and maintaining this list.
Why is this?
Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in his/her particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.
What should I do here?
If your question has been marked as a duplicate of this, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.
If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.
The List
Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)- Code doesn't run/what looks like parts of my PHP code are output
- Warning: Cannot modify header information - headers already sent
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource a.k.a.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given (or similar variations)- Warning: [function] expects parameter 1 to be resource, boolean given
- Warning: [function]: failed to open stream: [reason]
- Warning: open_basedir restriction in effect
- Warning: Division by zero
- Warning: Illegal string offset 'XXX'
- Parse error: syntax error, unexpected '['
- Parse error: syntax error, unexpected T_XXX
- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
- Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
- Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
- Parse error: syntax error, unexpected T_VARIABLE
- Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
- Fatal error: Call to a member function ... on a non-object
- Fatal Error: Call to Undefined function XXX
- Fatal Error: Cannot redeclare XXX
- Fatal error: Can't use function return value in write context
Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB() '- Fatal error: Using $this when not in object context
- Notice: Array to string conversion
- Notice: Trying to get property of non-object error
- Notice: Undefined variable
- Notice: Undefined Index
Notice: Undefined offset XXX [Reference]- Notice: Uninitialized string offset: XXX
- Notice: Use of undefined constant XXX - assumed 'XXX'
- MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
- Strict Standards: Non-static method [<class>::<method>] should not be called statically
- Warning: function expects parameter X to be boolean/string/integer
- HTTP Error 500 - Internal server error
Also, see
- Reference - What does this symbol mean in PHP?
php mysql debugging warnings
1
@PeterSmit: The php-errors tag has no wiki summary, can you help us create it?
– hakre
Oct 8 '12 at 12:44
7
Also, to move discussion out of comments, please go to this meta question
– Earlz
Oct 8 '12 at 13:56
2
X-Ref: PHP Parse/Syntax Errors; and How to solve them?; Elsewhere: Common PHP Errors and Solutions
– hakre
Aug 11 '13 at 21:47
1
see this coding.smashingmagazine.com/2011/11/30/… and this also mediawiki.org/wiki/Manual:Errors_and_symptoms
– krishna
Aug 27 '13 at 14:26
1
X-Ref: Fixing PHP Errors (May 2013; by Jason McCreary)
– hakre
Sep 3 '13 at 16:37
|
show 1 more comment
What is this?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix. This is also a Community Wiki, so everyone is invited to participate in adding to and maintaining this list.
Why is this?
Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in his/her particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.
What should I do here?
If your question has been marked as a duplicate of this, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.
If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.
The List
Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)- Code doesn't run/what looks like parts of my PHP code are output
- Warning: Cannot modify header information - headers already sent
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource a.k.a.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given (or similar variations)- Warning: [function] expects parameter 1 to be resource, boolean given
- Warning: [function]: failed to open stream: [reason]
- Warning: open_basedir restriction in effect
- Warning: Division by zero
- Warning: Illegal string offset 'XXX'
- Parse error: syntax error, unexpected '['
- Parse error: syntax error, unexpected T_XXX
- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
- Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
- Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
- Parse error: syntax error, unexpected T_VARIABLE
- Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
- Fatal error: Call to a member function ... on a non-object
- Fatal Error: Call to Undefined function XXX
- Fatal Error: Cannot redeclare XXX
- Fatal error: Can't use function return value in write context
Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB() '- Fatal error: Using $this when not in object context
- Notice: Array to string conversion
- Notice: Trying to get property of non-object error
- Notice: Undefined variable
- Notice: Undefined Index
Notice: Undefined offset XXX [Reference]- Notice: Uninitialized string offset: XXX
- Notice: Use of undefined constant XXX - assumed 'XXX'
- MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
- Strict Standards: Non-static method [<class>::<method>] should not be called statically
- Warning: function expects parameter X to be boolean/string/integer
- HTTP Error 500 - Internal server error
Also, see
- Reference - What does this symbol mean in PHP?
php mysql debugging warnings
What is this?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix. This is also a Community Wiki, so everyone is invited to participate in adding to and maintaining this list.
Why is this?
Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in his/her particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.
What should I do here?
If your question has been marked as a duplicate of this, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.
If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.
The List
Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)- Code doesn't run/what looks like parts of my PHP code are output
- Warning: Cannot modify header information - headers already sent
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource a.k.a.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given (or similar variations)- Warning: [function] expects parameter 1 to be resource, boolean given
- Warning: [function]: failed to open stream: [reason]
- Warning: open_basedir restriction in effect
- Warning: Division by zero
- Warning: Illegal string offset 'XXX'
- Parse error: syntax error, unexpected '['
- Parse error: syntax error, unexpected T_XXX
- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
- Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
- Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
- Parse error: syntax error, unexpected T_VARIABLE
- Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
- Fatal error: Call to a member function ... on a non-object
- Fatal Error: Call to Undefined function XXX
- Fatal Error: Cannot redeclare XXX
- Fatal error: Can't use function return value in write context
Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB() '- Fatal error: Using $this when not in object context
- Notice: Array to string conversion
- Notice: Trying to get property of non-object error
- Notice: Undefined variable
- Notice: Undefined Index
Notice: Undefined offset XXX [Reference]- Notice: Uninitialized string offset: XXX
- Notice: Use of undefined constant XXX - assumed 'XXX'
- MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
- Strict Standards: Non-static method [<class>::<method>] should not be called statically
- Warning: function expects parameter X to be boolean/string/integer
- HTTP Error 500 - Internal server error
Also, see
- Reference - What does this symbol mean in PHP?
php mysql debugging warnings
php mysql debugging warnings
edited Dec 19 '18 at 1:24
community wiki
62 revs, 24 users 25%
hakre
1
@PeterSmit: The php-errors tag has no wiki summary, can you help us create it?
– hakre
Oct 8 '12 at 12:44
7
Also, to move discussion out of comments, please go to this meta question
– Earlz
Oct 8 '12 at 13:56
2
X-Ref: PHP Parse/Syntax Errors; and How to solve them?; Elsewhere: Common PHP Errors and Solutions
– hakre
Aug 11 '13 at 21:47
1
see this coding.smashingmagazine.com/2011/11/30/… and this also mediawiki.org/wiki/Manual:Errors_and_symptoms
– krishna
Aug 27 '13 at 14:26
1
X-Ref: Fixing PHP Errors (May 2013; by Jason McCreary)
– hakre
Sep 3 '13 at 16:37
|
show 1 more comment
1
@PeterSmit: The php-errors tag has no wiki summary, can you help us create it?
– hakre
Oct 8 '12 at 12:44
7
Also, to move discussion out of comments, please go to this meta question
– Earlz
Oct 8 '12 at 13:56
2
X-Ref: PHP Parse/Syntax Errors; and How to solve them?; Elsewhere: Common PHP Errors and Solutions
– hakre
Aug 11 '13 at 21:47
1
see this coding.smashingmagazine.com/2011/11/30/… and this also mediawiki.org/wiki/Manual:Errors_and_symptoms
– krishna
Aug 27 '13 at 14:26
1
X-Ref: Fixing PHP Errors (May 2013; by Jason McCreary)
– hakre
Sep 3 '13 at 16:37
1
1
@PeterSmit: The php-errors tag has no wiki summary, can you help us create it?
– hakre
Oct 8 '12 at 12:44
@PeterSmit: The php-errors tag has no wiki summary, can you help us create it?
– hakre
Oct 8 '12 at 12:44
7
7
Also, to move discussion out of comments, please go to this meta question
– Earlz
Oct 8 '12 at 13:56
Also, to move discussion out of comments, please go to this meta question
– Earlz
Oct 8 '12 at 13:56
2
2
X-Ref: PHP Parse/Syntax Errors; and How to solve them?; Elsewhere: Common PHP Errors and Solutions
– hakre
Aug 11 '13 at 21:47
X-Ref: PHP Parse/Syntax Errors; and How to solve them?; Elsewhere: Common PHP Errors and Solutions
– hakre
Aug 11 '13 at 21:47
1
1
see this coding.smashingmagazine.com/2011/11/30/… and this also mediawiki.org/wiki/Manual:Errors_and_symptoms
– krishna
Aug 27 '13 at 14:26
see this coding.smashingmagazine.com/2011/11/30/… and this also mediawiki.org/wiki/Manual:Errors_and_symptoms
– krishna
Aug 27 '13 at 14:26
1
1
X-Ref: Fixing PHP Errors (May 2013; by Jason McCreary)
– hakre
Sep 3 '13 at 16:37
X-Ref: Fixing PHP Errors (May 2013; by Jason McCreary)
– hakre
Sep 3 '13 at 16:37
|
show 1 more comment
32 Answers
32
active
oldest
votes
1 2
next
Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING
and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start()
function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html>
element to the output stream. You'd have to move the session_start()
to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>
. It is considered a standard practice to omit ?>
when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php
has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one <?php ... ?>
code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
- Headers already sent by PHP
- All PHP "Headers already sent" Questions on Stackoverflow
- Byte Order Mark
- What PHP Functions Create Output?
1
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
1
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of<?php ?>
and so "more than one block" would be<?php ?> <?php ?>
?
– Andrew Fox
Jan 30 '14 at 8:40
1
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
add a comment |
Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
can not be called.
This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
is a "non-object" because the value is a boolean.
Figure out why your function returned a boolean instead of an object. For example, check the $pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.
If even the ->prepare
is failing then your $pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.
Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
- Call to a member function on a non-object
- List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow
add a comment |
Nothing is seen. The page is empty and white.
Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.
If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g. /var/log/apache2
on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).
Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.
This can be easily done by adding at the top of the script the following PHP code:
ini_set('display_errors', 1); error_reporting(~0);
The code will turn on the display of errors and set reporting to the highest level.
Since the ini_set()
is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the display_startup_errors
directive to true
. Do this either in the php.ini
or in a .htaccess
or by any other method that affects the configuration before runtime.
You can use the same methods to set the log_errors and error_log directives to choose your own log file location.
Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.
Related questions:
- PHP's white screen of death
- White screen of death!
- PHP Does Not Display Error Messages
- PHP emitting 500 on errors - where is this documented?
- How to get useful error messages in PHP?
- All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
- Parse error: syntax error, unexpected T_XXX
- Fatal error: Call to a member function ... on a non-object
- Code doesn't run/what looks like parts of my PHP code are output
2
error_reporting(~0);
why not-1
? That is what~0
evaluates to, and is much less cryptic.
– Fabrício Matté
Mar 31 '13 at 2:43
2
I think both are similarly cryptic.~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary1111'1111'1111'1111
(for 32 bits).
– nalply
Mar 31 '13 at 12:04
1
Oops,1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.
– nalply
Mar 31 '13 at 13:38
1
There is E_ALL constant forerror_reporting
.
– Ivan Solntsev
May 12 '14 at 11:30
2
@IvanSolntsev, sorry no, for versions before 5.4,E_STRICT
is not included inE_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down toE_STRICT
.
– nalply
May 12 '14 at 20:07
add a comment |
Notice: Undefined Index
Happens when you try to access an array by a key that does not exist in the array.
A typical example of an Undefined Index
notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach
and 1
do not exist in the array, causing an E_NOTICE
to be triggered.
The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists
or isset
:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
echo $data['spinach'];
}
else {
echo 'No key spinach in the array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
<input type="text" name="message">
...
then $_POST['message']
will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST) .. // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') .. // page was requested with POST
Related Questions:
- Reference: “Notice: Undefined variable” and “Notice: Undefined index”
- All PHP "Notice: Undefined Index" Questions on Stackoverflow
- http://php.net/arrays
add a comment |
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This happens when you try to fetch data from the result of mysql_query
but the query failed.
This is a warning and won't stop the script, but will make your program wrong.
You need to check the result returned by mysql_query
by
$res = mysql_query($sql);
if (!$res) {
die(mysql_error());
}
// after checking, do the fetch
Related Questions:
- mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
- All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
- Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql*
functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.
3
Just a note. Ifmysql_query
isn't bad enough, addingor die
on top of it is adding insult to injury.
– Madara Uchiha♦
Oct 7 '12 at 22:16
The problem I encounter is$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result ofmysql_query
tomysql_fetch_array()
the notice shows.
– mboy
Nov 27 '16 at 16:09
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this errormysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?
– mboy
Nov 28 '16 at 4:26
1
@mboymysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).
– xdazz
Nov 28 '16 at 4:35
|
show 1 more comment
Fatal error: Using $this when not in object context
$this
is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again,
$this
can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Useself::$static_property
to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the
$this
special variable.
How to fix: Review the code and replace$this
with a different substitution variable.
Related Questions:
- Call non-static method as static: PHP Fatal error: Using $this when not in object context
- Copy over code: Fatal error: Using $this when not in object context
- All "Using $this when not in object context" Questions on Stackoverflow
1
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
1
@hakre I was talking about a static call inside a Closure. Like$closure = function() { self::method(); }
.
– Kendall Hopkins
Oct 9 '12 at 16:55
1
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" :$closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
add a comment |
Fatal error: Call to undefined function XXX
Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.
Example 1 - Conditional Function Declaration
$someCondition = false;
if ($someCondition === true) {
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn()
will never be declared because $someCondition
is not true.
Example 2 - Function in Function Declaration
function createFn()
{
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn
will only be declared once createFn()
gets called. Note that subsequent calls to createFn()
will trigger an error about Redeclaration of an Existing function.
You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.
In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt
in Debian or Ubuntu, yum
in Red Hat or CentOS), or a control panel in a shared hosting environment.
If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.
In case of missing includes, make sure to include the file declaring the function before calling the function.
In case of typos, fix the typo.
Related Questions:
- https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function
add a comment |
Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- Parse Error: syntax error: unexpected '{'
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error: syntax error, unexpected '<' in - Fix?
- Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.
add a comment |
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false
. Expressions (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
- Fatal error: Can't use function the return value
add a comment |
MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes? $query
will end up with:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!
Documentation:
- How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
- How does the SQL injection from the "Bobby Tables" XKCD comic work?
- SQL injection that gets around mysql_real_escape_string()
2
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
1
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
1
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
add a comment |
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the php.ini
file or by using ini_set('memory_limit', '128 M');
in the script (which will overwrite the value defined in php.ini
). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.
The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.
If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The memory_get_usage
function is your friend.
Related Questions:
- All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow
add a comment |
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}
.
The error case:
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE
. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
add a comment |
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים. which means "double colon" or "double dot twice".
This error typically happens if you inadvertently put ::
in your code.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- What do two colons mean in PHP?
- What's the difference between :: (double colon) and -> (arrow) in PHP?
- Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
- Scope Resolution Operator (::)
The easiest way to trigger this error is runninga()::b;
or$a=::;
.
– Ismael Miguel
Apr 13 '15 at 13:39
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
add a comment |
Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
This means you're either using the same function/class name twice and need to rename one of them, or it is because you have used require
or include
where you should be using require_once
or include_once
.
When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.
Consider the following code:
class.php
<?php
class MyClass
{
public function doSomething()
{
// do stuff here
}
}
index.php
<?php
function do_stuff()
{
require 'class.php';
$obj = new MyClass;
$obj->doSomething();
}
do_stuff();
do_stuff();
The second call to do_stuff()
will produce the error above. By changing require
to require_once
, we can be certain that the file that contains the definition of MyClass
will only be loaded once, and the error will be avoided.
2
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
add a comment |
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include
, require
or fopen
and PHP couldn't find the file or have not enough permission to load the file.
This can happen for a variety of reasons :
- the file path is wrong
- the file path is relative
- include path is wrong
- permissions are too restrictive
- SELinux is in force
- and many more ...
One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__
or dirname(__FILE__)
:
include __DIR__ . '/inc/globals.inc.php';
or:
require dirname(__FILE__) . '/inc/globals.inc.php';
Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.
The best way to solve this problem quickly is to follow the troubleshooting checklist below.
Related Questions:
- Troubleshooting checklist: Failed to open stream
Related Errors:
- Warning: open_basedir restriction in effect
add a comment |
Notice: Use of undefined constant XXX - assumed 'XXX'
or, in PHP 7.2 or later:
Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)
This notice occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
- What does the PHP error message “Notice: Use of undefined constant” mean?
2
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
add a comment |
Notice: Undefined variable
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
foreach ($items as $item) {
// do something with item
$counter++;
}
If you didn't define $counter
before, the code above will trigger the notice.
The correct way would be to set the variable before using it, even if it's just an empty string like
$counter = 0;
foreach ($items as $item) {
// do something with item
$counter++;
}
Related Questions:
- All PHP "Notice: Undefined Variable" Questions on Stackoverflow
- PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
- Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
add a comment |
Notice: Uninitialized string offset: *
As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.
Consider you, are trying to show every letter from $string
$string = 'ABCD';
for ($i=0, $len = strlen($string); $i <= $len; $i++){
echo "$string[$i] n";
}
The above example will generate (online demo):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D
you'll get the error, because inside the for()
loop, you have told PHP to show you the from first to fifth string character from 'ABCD'
Which, exists, but since the loop starts to count from 0
and echoes D
by the time it reaches to 4
, it will throw an offset error.
Similar Errors:
- Illegal string offset 'option 1'
add a comment |
Warning: open_basedir restriction in effect
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called open_basedir
.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
- open_basedir restriction in effect. File(/) is not within the allowed path(s):
- All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow
1
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
add a comment |
Parse error: syntax error, unexpected T_VARIABLE
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
What I am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the .
operator. The interpreter stops running your program when it encounters a parse error.
In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.
What you should do is check carefully at the lines around where the error is for any simple mistakes.
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE
. That T_VARIABLE
thing is called a token
. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE
token in the interpreter's list.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE
in your php.ini
. Parse errors should not exist in production scripts.
I always recommended to add the following statement, while coding:
error_reporting(E_ALL);
PHP error reporting
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
add a comment |
Parse error: syntax error, unexpected '['
This error comes in two variatians:
Variation 1
$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.
Variation 2
$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.
add a comment |
Notice: Trying to get property of non-object error
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
In this case, $users
is an array (so not an object) and it does not have any properties.
This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.
As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
The problem is accessing the nodeValue
property (field) of the first item while it has not been checked if it exists or not in the $result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if ($div) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
- Notice: Undefined Index
- Fatal error: Call to a member function ... on a non-object
json_decode
now returns an instance ofstdclass
by default, so the example code would actually work.
– Hugo Zink
Jan 21 '16 at 12:25
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "json_decode
now returns an instance ofstdclass
by default" ? I can't find that in the changelog.
– hakre
Jan 22 '16 at 5:47
According to the PHP manual's page on json_decode, by default, theassoc
parameter is set to false. This parameter decides whether the function returns astdclass
instead of an associative array.
– Hugo Zink
Jan 22 '16 at 8:16
add a comment |
Warning: [function] expects parameter 1 to be resource, boolean given
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The cURL extension defines another two resource types:
... a cURL handle and a cURL multi handle.
When var_dump
ed, the values look like this:
$resource = curl_init();
var_dump($resource);
resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)
) of a certain type ((curl)
).
You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false
instead. For instance, the fopen
function has this description:
Return Values
Returns a file pointer resource on success, or
FALSE
on error.
So in this code, $fp
will either be a resource(x) of type (stream)
or false
:
$fp = fopen(...);
If you do not check whether the fopen
operation succeed or failed and hence whether $fp
is a valid resource or false
and pass $fp
to another function which expects a resource, you may get the above error:
$fp = fopen(...);
$data = fread($fp, 1024);
Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:
$fp = fopen(...);
if (!$fp) {
trigger_error('Failed to allocate resource');
exit;
}
$data = fread($fp, 1024);
Related Errors:
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
add a comment |
Warning: Illegal string offset 'XXX'
This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.
Example:
$var = "test";
echo $var["a_key"];
If you think the variable should be an array, see where it comes from and fix the problem there.
add a comment |
Code doesn't run/what looks like parts of my PHP code are output
If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?>
tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.
To actually run your PHP scripts, you need:
- a web server which executes your script
- to set the file extension to .php, otherwise the web server won't interpret it as such*
- to access your .php file via the web server
* Unless you reconfigure it, everything can be configured.
This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:
file://C:/path/to/my/file.php
This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:
http://localhost/my/file.php
You may also want to check whether you're using short open tags <?
instead of <?php
and your PHP configuration has turned short open tags off.
Also see PHP code is not being executed, instead code shows on the page
add a comment |
Warning: mysql_connect(): Access denied for user 'name'@'host'
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on
mysql_connect("localhost", "user", "pw")
for examples.
Check that you actually used a
$username
and$password
.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
(using password: NO)
. Only the local test server usually allows to connect with username
root
, no password, and thetest
database name.You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like
$
, escape them, or put the password in single quotes.Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be
"localhost"
, which normally utilizes a local named socket when available. Othertimes you can try"127.0.0.1"
as fallback.Should your MySQL/MariaDB server listen on a different port, then use
"servername:3306"
.If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g.
DB_USER
orDB_PASSWORD
, check that they're actually defined.
If you get a
"Warning: Access defined for 'DB_USER'@'host'"
and a"Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.Verify that your e.g.
xy/db-config.php
was actually included and whatelse.
Check for correctly set
GRANT
permissions.
It's not sufficient to have a
username
+password
pair.Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for
mysql_query
calls, if you don't have permissions toSELECT
from a specific table, orINSERT
/UPDATE
, and more commonlyDELETE
anything.You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with
Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.
Check that
mysql.default_user=
andmysql.default_password=
have meaningful values.Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
- Serverfault: mysql access denied for 'root'@'name of the computer'
- Warning: mysql_connect(): Access denied
- Warning: mysql_select_db() Access denied for user ''@'localhost' (using password: NO)
- Access denied for user 'root'@'localhost' with PHPMyAdmin
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
1
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
add a comment |
Notice: Array to string conversion
This simply happens if you try to treat an array as a string:
$arr = array('foo', 'bar');
echo $arr; // Notice: Array to string conversion
$str = 'Something, ' . $arr; // Notice: Array to string conversion
An array cannot simply be echo
'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:
echo $arr[0]; // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar
Or loop the array:
foreach($arr as $key => $value) {
echo "array $key = $value";
// displays first: array 0 = foo
// displays next: array 1 = bar
}
If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.
add a comment |
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
$value = @(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you should not divide, or change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
- warning: division by zero
- Warning: Division By Zero Working on PHP and MySQL
- Division by zero error in WordPress Theme
- How to suppress the “Division by zero” error
- How to catch a division by zero?
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
For this example, if$var1
does == 0 then you can just set$var3
to$var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside theif
– James
Jun 17 '18 at 0:58
add a comment |
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT
flag in your error_reporting()
settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br()
or $html::br()
You can actually avoid this error by not adding E_STRICT
to error_reporting()
, eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT
is included in E_ALL
[ref]. But that is not adviceable. The solution is to define your intended static function as actual static
:
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
- How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?
add a comment |
Fatal error: [TraitA] and [TraitB] define the same property ([$x]) in the composition of [ClassC]
Occurs when a class attempts to use
multiple Traits, where two or more of those Traits have defined a property by the same name, and with the property having differing initial values.
Example:
<?php
trait TraitA
{
public $x = 'a';
}
trait TraitB
{
public $x = 'b';
}
class ClassC
{
use TraitA, TraitB;
}
Problematic: While it's possible to resolve conflicts between competing methods, there is currently no syntax that would resolve a conflict between two competing properties. The only solution at this time is to refactor; i.e., avoid a conflict between property names that produces a fatal error.
Related Questions:
- PHP Traits: How to resolve a property name conflict?
- Traits - property conflict with parent class
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
add a comment |
1 2
next
protected by Samuel Liew♦ Oct 5 '15 at 8:59
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
32 Answers
32
active
oldest
votes
32 Answers
32
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING
and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start()
function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html>
element to the output stream. You'd have to move the session_start()
to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>
. It is considered a standard practice to omit ?>
when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php
has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one <?php ... ?>
code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
- Headers already sent by PHP
- All PHP "Headers already sent" Questions on Stackoverflow
- Byte Order Mark
- What PHP Functions Create Output?
1
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
1
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of<?php ?>
and so "more than one block" would be<?php ?> <?php ?>
?
– Andrew Fox
Jan 30 '14 at 8:40
1
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
add a comment |
Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING
and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start()
function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html>
element to the output stream. You'd have to move the session_start()
to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>
. It is considered a standard practice to omit ?>
when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php
has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one <?php ... ?>
code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
- Headers already sent by PHP
- All PHP "Headers already sent" Questions on Stackoverflow
- Byte Order Mark
- What PHP Functions Create Output?
1
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
1
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of<?php ?>
and so "more than one block" would be<?php ?> <?php ?>
?
– Andrew Fox
Jan 30 '14 at 8:40
1
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
add a comment |
Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING
and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start()
function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html>
element to the output stream. You'd have to move the session_start()
to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>
. It is considered a standard practice to omit ?>
when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php
has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one <?php ... ?>
code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
- Headers already sent by PHP
- All PHP "Headers already sent" Questions on Stackoverflow
- Byte Order Mark
- What PHP Functions Create Output?
Warning: Cannot modify header information - headers already sent
Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING
and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start()
function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html>
element to the output stream. You'd have to move the session_start()
to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>
. It is considered a standard practice to omit ?>
when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php
has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one <?php ... ?>
code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related Questions:
- Headers already sent by PHP
- All PHP "Headers already sent" Questions on Stackoverflow
- Byte Order Mark
- What PHP Functions Create Output?
edited Dec 5 '18 at 10:14
community wiki
16 revs, 9 users 68%
Gordon
1
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
1
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of<?php ?>
and so "more than one block" would be<?php ?> <?php ?>
?
– Andrew Fox
Jan 30 '14 at 8:40
1
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
add a comment |
1
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
1
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of<?php ?>
and so "more than one block" would be<?php ?> <?php ?>
?
– Andrew Fox
Jan 30 '14 at 8:40
1
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
1
1
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between.
– Roy Leban
Mar 31 '13 at 8:41
1
1
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of
<?php ?>
and so "more than one block" would be <?php ?> <?php ?>
?– Andrew Fox
Jan 30 '14 at 8:40
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of
<?php ?>
and so "more than one block" would be <?php ?> <?php ?>
?– Andrew Fox
Jan 30 '14 at 8:40
1
1
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
Please turn on 'output buffering' feature in PHP.ini configuration file if possible.It is used for sloving this issue.It sends the html file is saved in the output buffer and sent to the client only after the script stops, so if two headers are issued at different location then the old header will be replaced new header.
– Nidhin David
May 13 '14 at 17:15
add a comment |
Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
can not be called.
This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
is a "non-object" because the value is a boolean.
Figure out why your function returned a boolean instead of an object. For example, check the $pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.
If even the ->prepare
is failing then your $pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.
Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
- Call to a member function on a non-object
- List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow
add a comment |
Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
can not be called.
This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
is a "non-object" because the value is a boolean.
Figure out why your function returned a boolean instead of an object. For example, check the $pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.
If even the ->prepare
is failing then your $pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.
Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
- Call to a member function on a non-object
- List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow
add a comment |
Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
can not be called.
This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
is a "non-object" because the value is a boolean.
Figure out why your function returned a boolean instead of an object. For example, check the $pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.
If even the ->prepare
is failing then your $pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.
Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
- Call to a member function on a non-object
- List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow
Fatal error: Call to a member function ... on a non-object
Happens with code similar to xyz->method()
where xyz
is not an object and therefore that method
can not be called.
This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).
Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.
A typical example would be
// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);
In the example above, the query cannot be prepared and prepare()
will assign false
to $statement
. Trying to call the execute()
method will then result in the Fatal Error because false
is a "non-object" because the value is a boolean.
Figure out why your function returned a boolean instead of an object. For example, check the $pdo
object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.
If even the ->prepare
is failing then your $pdo
database handle object didn't get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.
Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example
if ($someCondition) {
$myObj = new MyObj();
}
// ...
$myObj->someMethod();
By attempting to execute the method outside the conditional block, your object may not be defined.
Related Questions:
- Call to a member function on a non-object
- List all PHP "Fatal error: Call to a member function ... on a non-object" Questions on Stackoverflow
edited Apr 16 '18 at 4:16
community wiki
17 revs, 9 users 50%
hakre
add a comment |
add a comment |
Nothing is seen. The page is empty and white.
Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.
If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g. /var/log/apache2
on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).
Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.
This can be easily done by adding at the top of the script the following PHP code:
ini_set('display_errors', 1); error_reporting(~0);
The code will turn on the display of errors and set reporting to the highest level.
Since the ini_set()
is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the display_startup_errors
directive to true
. Do this either in the php.ini
or in a .htaccess
or by any other method that affects the configuration before runtime.
You can use the same methods to set the log_errors and error_log directives to choose your own log file location.
Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.
Related questions:
- PHP's white screen of death
- White screen of death!
- PHP Does Not Display Error Messages
- PHP emitting 500 on errors - where is this documented?
- How to get useful error messages in PHP?
- All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
- Parse error: syntax error, unexpected T_XXX
- Fatal error: Call to a member function ... on a non-object
- Code doesn't run/what looks like parts of my PHP code are output
2
error_reporting(~0);
why not-1
? That is what~0
evaluates to, and is much less cryptic.
– Fabrício Matté
Mar 31 '13 at 2:43
2
I think both are similarly cryptic.~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary1111'1111'1111'1111
(for 32 bits).
– nalply
Mar 31 '13 at 12:04
1
Oops,1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.
– nalply
Mar 31 '13 at 13:38
1
There is E_ALL constant forerror_reporting
.
– Ivan Solntsev
May 12 '14 at 11:30
2
@IvanSolntsev, sorry no, for versions before 5.4,E_STRICT
is not included inE_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down toE_STRICT
.
– nalply
May 12 '14 at 20:07
add a comment |
Nothing is seen. The page is empty and white.
Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.
If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g. /var/log/apache2
on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).
Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.
This can be easily done by adding at the top of the script the following PHP code:
ini_set('display_errors', 1); error_reporting(~0);
The code will turn on the display of errors and set reporting to the highest level.
Since the ini_set()
is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the display_startup_errors
directive to true
. Do this either in the php.ini
or in a .htaccess
or by any other method that affects the configuration before runtime.
You can use the same methods to set the log_errors and error_log directives to choose your own log file location.
Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.
Related questions:
- PHP's white screen of death
- White screen of death!
- PHP Does Not Display Error Messages
- PHP emitting 500 on errors - where is this documented?
- How to get useful error messages in PHP?
- All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
- Parse error: syntax error, unexpected T_XXX
- Fatal error: Call to a member function ... on a non-object
- Code doesn't run/what looks like parts of my PHP code are output
2
error_reporting(~0);
why not-1
? That is what~0
evaluates to, and is much less cryptic.
– Fabrício Matté
Mar 31 '13 at 2:43
2
I think both are similarly cryptic.~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary1111'1111'1111'1111
(for 32 bits).
– nalply
Mar 31 '13 at 12:04
1
Oops,1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.
– nalply
Mar 31 '13 at 13:38
1
There is E_ALL constant forerror_reporting
.
– Ivan Solntsev
May 12 '14 at 11:30
2
@IvanSolntsev, sorry no, for versions before 5.4,E_STRICT
is not included inE_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down toE_STRICT
.
– nalply
May 12 '14 at 20:07
add a comment |
Nothing is seen. The page is empty and white.
Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.
If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g. /var/log/apache2
on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).
Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.
This can be easily done by adding at the top of the script the following PHP code:
ini_set('display_errors', 1); error_reporting(~0);
The code will turn on the display of errors and set reporting to the highest level.
Since the ini_set()
is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the display_startup_errors
directive to true
. Do this either in the php.ini
or in a .htaccess
or by any other method that affects the configuration before runtime.
You can use the same methods to set the log_errors and error_log directives to choose your own log file location.
Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.
Related questions:
- PHP's white screen of death
- White screen of death!
- PHP Does Not Display Error Messages
- PHP emitting 500 on errors - where is this documented?
- How to get useful error messages in PHP?
- All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
- Parse error: syntax error, unexpected T_XXX
- Fatal error: Call to a member function ... on a non-object
- Code doesn't run/what looks like parts of my PHP code are output
Nothing is seen. The page is empty and white.
Also known as the White Page Of Death or White Screen Of Death. This happens when error reporting is turned off and a fatal error (often syntax error) occurred.
If you have error logging enabled, you will find the concrete error message in your error log. This will usually be in a file called "php_errors.log", either in a central location (e.g. /var/log/apache2
on many Linux environments) or in the directory of the script itself (sometimes used in a shared hosting environment).
Sometimes it might be more straightforward to temporarily enable the display of errors. The white page will then display the error message. Take care because these errors are visible to everybody visiting the website.
This can be easily done by adding at the top of the script the following PHP code:
ini_set('display_errors', 1); error_reporting(~0);
The code will turn on the display of errors and set reporting to the highest level.
Since the ini_set()
is executed at runtime it has no effects on parsing/syntax errors. Those errors will appear in the log. If you want to display them in the output as well (e.g. in a browser) you have to set the display_startup_errors
directive to true
. Do this either in the php.ini
or in a .htaccess
or by any other method that affects the configuration before runtime.
You can use the same methods to set the log_errors and error_log directives to choose your own log file location.
Looking in the log or using the display, you will get a much better error message and the line of code where your script comes to halt.
Related questions:
- PHP's white screen of death
- White screen of death!
- PHP Does Not Display Error Messages
- PHP emitting 500 on errors - where is this documented?
- How to get useful error messages in PHP?
- All PHP "White Page of Death" Questions on Stackoverflow
Related errors:
- Parse error: syntax error, unexpected T_XXX
- Fatal error: Call to a member function ... on a non-object
- Code doesn't run/what looks like parts of my PHP code are output
edited May 23 '17 at 12:26
community wiki
20 revs, 7 users 40%
nalply
2
error_reporting(~0);
why not-1
? That is what~0
evaluates to, and is much less cryptic.
– Fabrício Matté
Mar 31 '13 at 2:43
2
I think both are similarly cryptic.~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary1111'1111'1111'1111
(for 32 bits).
– nalply
Mar 31 '13 at 12:04
1
Oops,1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.
– nalply
Mar 31 '13 at 13:38
1
There is E_ALL constant forerror_reporting
.
– Ivan Solntsev
May 12 '14 at 11:30
2
@IvanSolntsev, sorry no, for versions before 5.4,E_STRICT
is not included inE_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down toE_STRICT
.
– nalply
May 12 '14 at 20:07
add a comment |
2
error_reporting(~0);
why not-1
? That is what~0
evaluates to, and is much less cryptic.
– Fabrício Matté
Mar 31 '13 at 2:43
2
I think both are similarly cryptic.~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary1111'1111'1111'1111
(for 32 bits).
– nalply
Mar 31 '13 at 12:04
1
Oops,1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.
– nalply
Mar 31 '13 at 13:38
1
There is E_ALL constant forerror_reporting
.
– Ivan Solntsev
May 12 '14 at 11:30
2
@IvanSolntsev, sorry no, for versions before 5.4,E_STRICT
is not included inE_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down toE_STRICT
.
– nalply
May 12 '14 at 20:07
2
2
error_reporting(~0);
why not -1
? That is what ~0
evaluates to, and is much less cryptic.– Fabrício Matté
Mar 31 '13 at 2:43
error_reporting(~0);
why not -1
? That is what ~0
evaluates to, and is much less cryptic.– Fabrício Matté
Mar 31 '13 at 2:43
2
2
I think both are similarly cryptic.
~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary 1111'1111'1111'1111
(for 32 bits).– nalply
Mar 31 '13 at 12:04
I think both are similarly cryptic.
~0
is more explicit IMO: negate the empty bit set, i. e. enable all flags. -1 is not meant to stand for «not found» like in strpos() in C, but as a bitset with all flags set, because -1 is binary 1111'1111'1111'1111
(for 32 bits).– nalply
Mar 31 '13 at 12:04
1
1
Oops,
1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.– nalply
Mar 31 '13 at 13:38
Oops,
1111'1111'1111'1111
is really 16 bits, but I hope you understand what I mean.– nalply
Mar 31 '13 at 13:38
1
1
There is E_ALL constant for
error_reporting
.– Ivan Solntsev
May 12 '14 at 11:30
There is E_ALL constant for
error_reporting
.– Ivan Solntsev
May 12 '14 at 11:30
2
2
@IvanSolntsev, sorry no, for versions before 5.4,
E_STRICT
is not included in E_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down to E_STRICT
.– nalply
May 12 '14 at 20:07
@IvanSolntsev, sorry no, for versions before 5.4,
E_STRICT
is not included in E_ALL
. php.net/manual/en/errorfunc.constants.php and scroll down to E_STRICT
.– nalply
May 12 '14 at 20:07
add a comment |
Notice: Undefined Index
Happens when you try to access an array by a key that does not exist in the array.
A typical example of an Undefined Index
notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach
and 1
do not exist in the array, causing an E_NOTICE
to be triggered.
The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists
or isset
:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
echo $data['spinach'];
}
else {
echo 'No key spinach in the array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
<input type="text" name="message">
...
then $_POST['message']
will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST) .. // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') .. // page was requested with POST
Related Questions:
- Reference: “Notice: Undefined variable” and “Notice: Undefined index”
- All PHP "Notice: Undefined Index" Questions on Stackoverflow
- http://php.net/arrays
add a comment |
Notice: Undefined Index
Happens when you try to access an array by a key that does not exist in the array.
A typical example of an Undefined Index
notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach
and 1
do not exist in the array, causing an E_NOTICE
to be triggered.
The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists
or isset
:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
echo $data['spinach'];
}
else {
echo 'No key spinach in the array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
<input type="text" name="message">
...
then $_POST['message']
will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST) .. // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') .. // page was requested with POST
Related Questions:
- Reference: “Notice: Undefined variable” and “Notice: Undefined index”
- All PHP "Notice: Undefined Index" Questions on Stackoverflow
- http://php.net/arrays
add a comment |
Notice: Undefined Index
Happens when you try to access an array by a key that does not exist in the array.
A typical example of an Undefined Index
notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach
and 1
do not exist in the array, causing an E_NOTICE
to be triggered.
The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists
or isset
:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
echo $data['spinach'];
}
else {
echo 'No key spinach in the array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
<input type="text" name="message">
...
then $_POST['message']
will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST) .. // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') .. // page was requested with POST
Related Questions:
- Reference: “Notice: Undefined variable” and “Notice: Undefined index”
- All PHP "Notice: Undefined Index" Questions on Stackoverflow
- http://php.net/arrays
Notice: Undefined Index
Happens when you try to access an array by a key that does not exist in the array.
A typical example of an Undefined Index
notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach
and 1
do not exist in the array, causing an E_NOTICE
to be triggered.
The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists
or isset
:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
echo $data['spinach'];
}
else {
echo 'No key spinach in the array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
<input type="text" name="message">
...
then $_POST['message']
will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST) .. // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') .. // page was requested with POST
Related Questions:
- Reference: “Notice: Undefined variable” and “Notice: Undefined index”
- All PHP "Notice: Undefined Index" Questions on Stackoverflow
- http://php.net/arrays
edited Dec 5 '18 at 10:15
community wiki
11 revs, 7 users 57%
Gordon
add a comment |
add a comment |
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This happens when you try to fetch data from the result of mysql_query
but the query failed.
This is a warning and won't stop the script, but will make your program wrong.
You need to check the result returned by mysql_query
by
$res = mysql_query($sql);
if (!$res) {
die(mysql_error());
}
// after checking, do the fetch
Related Questions:
- mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
- All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
- Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql*
functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.
3
Just a note. Ifmysql_query
isn't bad enough, addingor die
on top of it is adding insult to injury.
– Madara Uchiha♦
Oct 7 '12 at 22:16
The problem I encounter is$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result ofmysql_query
tomysql_fetch_array()
the notice shows.
– mboy
Nov 27 '16 at 16:09
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this errormysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?
– mboy
Nov 28 '16 at 4:26
1
@mboymysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).
– xdazz
Nov 28 '16 at 4:35
|
show 1 more comment
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This happens when you try to fetch data from the result of mysql_query
but the query failed.
This is a warning and won't stop the script, but will make your program wrong.
You need to check the result returned by mysql_query
by
$res = mysql_query($sql);
if (!$res) {
die(mysql_error());
}
// after checking, do the fetch
Related Questions:
- mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
- All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
- Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql*
functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.
3
Just a note. Ifmysql_query
isn't bad enough, addingor die
on top of it is adding insult to injury.
– Madara Uchiha♦
Oct 7 '12 at 22:16
The problem I encounter is$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result ofmysql_query
tomysql_fetch_array()
the notice shows.
– mboy
Nov 27 '16 at 16:09
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this errormysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?
– mboy
Nov 28 '16 at 4:26
1
@mboymysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).
– xdazz
Nov 28 '16 at 4:35
|
show 1 more comment
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This happens when you try to fetch data from the result of mysql_query
but the query failed.
This is a warning and won't stop the script, but will make your program wrong.
You need to check the result returned by mysql_query
by
$res = mysql_query($sql);
if (!$res) {
die(mysql_error());
}
// after checking, do the fetch
Related Questions:
- mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
- All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
- Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql*
functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
First and foremost:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This happens when you try to fetch data from the result of mysql_query
but the query failed.
This is a warning and won't stop the script, but will make your program wrong.
You need to check the result returned by mysql_query
by
$res = mysql_query($sql);
if (!$res) {
die(mysql_error());
}
// after checking, do the fetch
Related Questions:
- mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
- All "mysql_fetch_array() expects parameter 1 to be resource, boolean given" Questions on Stackoverflow
Related Errors:
- Warning: [function] expects parameter 1 to be resource, boolean given
Other mysql*
functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.
edited Dec 5 '18 at 10:16
community wiki
14 revs, 8 users 41%
xdazz
3
Just a note. Ifmysql_query
isn't bad enough, addingor die
on top of it is adding insult to injury.
– Madara Uchiha♦
Oct 7 '12 at 22:16
The problem I encounter is$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result ofmysql_query
tomysql_fetch_array()
the notice shows.
– mboy
Nov 27 '16 at 16:09
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this errormysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?
– mboy
Nov 28 '16 at 4:26
1
@mboymysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).
– xdazz
Nov 28 '16 at 4:35
|
show 1 more comment
3
Just a note. Ifmysql_query
isn't bad enough, addingor die
on top of it is adding insult to injury.
– Madara Uchiha♦
Oct 7 '12 at 22:16
The problem I encounter is$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result ofmysql_query
tomysql_fetch_array()
the notice shows.
– mboy
Nov 27 '16 at 16:09
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this errormysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?
– mboy
Nov 28 '16 at 4:26
1
@mboymysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).
– xdazz
Nov 28 '16 at 4:35
3
3
Just a note. If
mysql_query
isn't bad enough, adding or die
on top of it is adding insult to injury.– Madara Uchiha♦
Oct 7 '12 at 22:16
Just a note. If
mysql_query
isn't bad enough, adding or die
on top of it is adding insult to injury.– Madara Uchiha♦
Oct 7 '12 at 22:16
The problem I encounter is
$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result of mysql_query
to mysql_fetch_array()
the notice shows.– mboy
Nov 27 '16 at 16:09
The problem I encounter is
$res = mysql_query($query)
returns 1 if query is successful so it is considered true. Therefore when passing the result of mysql_query
to mysql_fetch_array()
the notice shows.– mboy
Nov 27 '16 at 16:09
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@mboy For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
– xdazz
Nov 28 '16 at 0:47
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this error
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?– mboy
Nov 28 '16 at 4:26
@xdazz That is the problem I am facing, Insert update returns TRUE so I cannot get rid of this error
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
please see - gist.github.com/romelemperado/93af4cdbd44ebf3a07cbfa0e3fc539d7 Any suggestion to git rid of this error?– mboy
Nov 28 '16 at 4:26
1
1
@mboy
mysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).– xdazz
Nov 28 '16 at 4:35
@mboy
mysql_fetch_array()
is for select query, for insert and update, you don't need to fetch the result set (and there is no result set let you fetch).– xdazz
Nov 28 '16 at 4:35
|
show 1 more comment
Fatal error: Using $this when not in object context
$this
is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again,
$this
can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Useself::$static_property
to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the
$this
special variable.
How to fix: Review the code and replace$this
with a different substitution variable.
Related Questions:
- Call non-static method as static: PHP Fatal error: Using $this when not in object context
- Copy over code: Fatal error: Using $this when not in object context
- All "Using $this when not in object context" Questions on Stackoverflow
1
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
1
@hakre I was talking about a static call inside a Closure. Like$closure = function() { self::method(); }
.
– Kendall Hopkins
Oct 9 '12 at 16:55
1
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" :$closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
add a comment |
Fatal error: Using $this when not in object context
$this
is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again,
$this
can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Useself::$static_property
to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the
$this
special variable.
How to fix: Review the code and replace$this
with a different substitution variable.
Related Questions:
- Call non-static method as static: PHP Fatal error: Using $this when not in object context
- Copy over code: Fatal error: Using $this when not in object context
- All "Using $this when not in object context" Questions on Stackoverflow
1
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
1
@hakre I was talking about a static call inside a Closure. Like$closure = function() { self::method(); }
.
– Kendall Hopkins
Oct 9 '12 at 16:55
1
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" :$closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
add a comment |
Fatal error: Using $this when not in object context
$this
is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again,
$this
can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Useself::$static_property
to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the
$this
special variable.
How to fix: Review the code and replace$this
with a different substitution variable.
Related Questions:
- Call non-static method as static: PHP Fatal error: Using $this when not in object context
- Copy over code: Fatal error: Using $this when not in object context
- All "Using $this when not in object context" Questions on Stackoverflow
Fatal error: Using $this when not in object context
$this
is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
If a non-static method is called statically. Example:
class Foo {
protected $var;
public function __construct($var) {
$this->var = $var;
}
public static function bar () {
// ^^^^^^
echo $this->var;
// ^^^^^
}
}
Foo::bar();
How to fix: review your code again,
$this
can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Useself::$static_property
to access the static property.
If code from a class method has been copied over into a normal function or just the global scope and keeping the
$this
special variable.
How to fix: Review the code and replace$this
with a different substitution variable.
Related Questions:
- Call non-static method as static: PHP Fatal error: Using $this when not in object context
- Copy over code: Fatal error: Using $this when not in object context
- All "Using $this when not in object context" Questions on Stackoverflow
edited Dec 5 '18 at 10:16
community wiki
11 revs, 7 users 56%
xdazz
1
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
1
@hakre I was talking about a static call inside a Closure. Like$closure = function() { self::method(); }
.
– Kendall Hopkins
Oct 9 '12 at 16:55
1
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" :$closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
add a comment |
1
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
1
@hakre I was talking about a static call inside a Closure. Like$closure = function() { self::method(); }
.
– Kendall Hopkins
Oct 9 '12 at 16:55
1
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" :$closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
1
1
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
You might also want to mention how this works w/ closures (even in non-static methods) and how it's "fixed" in 5.4.
– Kendall Hopkins
Oct 7 '12 at 18:12
1
1
@hakre I was talking about a static call inside a Closure. Like
$closure = function() { self::method(); }
.– Kendall Hopkins
Oct 9 '12 at 16:55
@hakre I was talking about a static call inside a Closure. Like
$closure = function() { self::method(); }
.– Kendall Hopkins
Oct 9 '12 at 16:55
1
1
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with
$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" : $closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
@KendallHopkins: That is a different error: "Fatal error: Cannot access self:: when no class scope is active" However with
$this
you can trigger the bespoken "Fatal error: Using $this when not in object context" : $closure = function() { $this->method(); };
– hakre
Oct 9 '12 at 17:02
add a comment |
Fatal error: Call to undefined function XXX
Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.
Example 1 - Conditional Function Declaration
$someCondition = false;
if ($someCondition === true) {
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn()
will never be declared because $someCondition
is not true.
Example 2 - Function in Function Declaration
function createFn()
{
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn
will only be declared once createFn()
gets called. Note that subsequent calls to createFn()
will trigger an error about Redeclaration of an Existing function.
You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.
In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt
in Debian or Ubuntu, yum
in Red Hat or CentOS), or a control panel in a shared hosting environment.
If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.
In case of missing includes, make sure to include the file declaring the function before calling the function.
In case of typos, fix the typo.
Related Questions:
- https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function
add a comment |
Fatal error: Call to undefined function XXX
Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.
Example 1 - Conditional Function Declaration
$someCondition = false;
if ($someCondition === true) {
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn()
will never be declared because $someCondition
is not true.
Example 2 - Function in Function Declaration
function createFn()
{
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn
will only be declared once createFn()
gets called. Note that subsequent calls to createFn()
will trigger an error about Redeclaration of an Existing function.
You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.
In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt
in Debian or Ubuntu, yum
in Red Hat or CentOS), or a control panel in a shared hosting environment.
If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.
In case of missing includes, make sure to include the file declaring the function before calling the function.
In case of typos, fix the typo.
Related Questions:
- https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function
add a comment |
Fatal error: Call to undefined function XXX
Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.
Example 1 - Conditional Function Declaration
$someCondition = false;
if ($someCondition === true) {
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn()
will never be declared because $someCondition
is not true.
Example 2 - Function in Function Declaration
function createFn()
{
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn
will only be declared once createFn()
gets called. Note that subsequent calls to createFn()
will trigger an error about Redeclaration of an Existing function.
You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.
In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt
in Debian or Ubuntu, yum
in Red Hat or CentOS), or a control panel in a shared hosting environment.
If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.
In case of missing includes, make sure to include the file declaring the function before calling the function.
In case of typos, fix the typo.
Related Questions:
- https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function
Fatal error: Call to undefined function XXX
Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.
Example 1 - Conditional Function Declaration
$someCondition = false;
if ($someCondition === true) {
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn()
will never be declared because $someCondition
is not true.
Example 2 - Function in Function Declaration
function createFn()
{
function fn() {
return 1;
}
}
echo fn(); // triggers error
In this case, fn
will only be declared once createFn()
gets called. Note that subsequent calls to createFn()
will trigger an error about Redeclaration of an Existing function.
You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what "extension" (PHP module) it belongs to, and what versions of PHP support it.
In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt
in Debian or Ubuntu, yum
in Red Hat or CentOS), or a control panel in a shared hosting environment.
If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.
In case of missing includes, make sure to include the file declaring the function before calling the function.
In case of typos, fix the typo.
Related Questions:
- https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function
edited Dec 5 '18 at 10:16
community wiki
8 revs, 5 users 88%
Gordon
add a comment |
add a comment |
Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- Parse Error: syntax error: unexpected '{'
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error: syntax error, unexpected '<' in - Fix?
- Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.
add a comment |
Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- Parse Error: syntax error: unexpected '{'
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error: syntax error, unexpected '<' in - Fix?
- Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.
add a comment |
Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- Parse Error: syntax error: unexpected '{'
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error: syntax error, unexpected '<' in - Fix?
- Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.
Parse error: syntax error, unexpected T_XXX
Happens when you have T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- Parse Error: syntax error: unexpected '{'
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error: syntax error, unexpected '<' in - Fix?
- Parse error: syntax error, unexpected '?'
For further help see:
http://phpcodechecker.com/ - Which does provide some more helpful explanations on your syntax woes.
edited May 23 '17 at 12:34
community wiki
6 revs, 3 users 68%
LeleDumbo
add a comment |
add a comment |
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false
. Expressions (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
- Fatal error: Can't use function the return value
add a comment |
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false
. Expressions (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
- Fatal error: Can't use function the return value
add a comment |
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false
. Expressions (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
- Fatal error: Can't use function the return value
Fatal error: Can't use function return value in write context
This usually happens when using a function directly with empty
.
Example:
if (empty(is_null(null))) {
echo 'empty';
}
This is because empty
is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty()
must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.
empty
, despite its name, does not actually check if a variable is "empty". Instead, it checks if a variable doesn't exist, or == false
. Expressions (like is_null(null)
in the example) will always be deemed to exist, so here empty
is only checking if it is equal to false. You could replace empty()
here with !
, e.g. if (!is_null(null))
, or explicitly compare to false, e.g. if (is_null(null) == false)
.
Related Questions:
- Fatal error: Can't use function the return value
edited Dec 5 '18 at 10:17
community wiki
6 revs, 5 users 80%
xdazz
add a comment |
add a comment |
MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes? $query
will end up with:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!
Documentation:
- How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
- How does the SQL injection from the "Bobby Tables" XKCD comic work?
- SQL injection that gets around mysql_real_escape_string()
2
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
1
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
1
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
add a comment |
MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes? $query
will end up with:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!
Documentation:
- How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
- How does the SQL injection from the "Bobby Tables" XKCD comic work?
- SQL injection that gets around mysql_real_escape_string()
2
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
1
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
1
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
add a comment |
MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes? $query
will end up with:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!
Documentation:
- How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
- How does the SQL injection from the "Bobby Tables" XKCD comic work?
- SQL injection that gets around mysql_real_escape_string()
MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes? $query
will end up with:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!
Documentation:
- How can I prevent SQL injection in PHP?
mysql_real_escape_string()
mysqli_real_escape_string()
- How does the SQL injection from the "Bobby Tables" XKCD comic work?
- SQL injection that gets around mysql_real_escape_string()
edited May 23 '17 at 12:18
community wiki
8 revs, 3 users 79%
Jocelyn
2
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
1
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
1
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
add a comment |
2
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
1
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
1
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
2
2
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
In addition, if you don't your site will be hacked by bots automatically
– apscience
Oct 7 '12 at 22:32
1
1
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
@gladoscc Click "edit" and modify the answer. I am aware it can be improved.
– Jocelyn
Oct 8 '12 at 0:50
1
1
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
Or use a prepared sql query.
– code ninja
Sep 4 '13 at 7:17
add a comment |
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the php.ini
file or by using ini_set('memory_limit', '128 M');
in the script (which will overwrite the value defined in php.ini
). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.
The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.
If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The memory_get_usage
function is your friend.
Related Questions:
- All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow
add a comment |
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the php.ini
file or by using ini_set('memory_limit', '128 M');
in the script (which will overwrite the value defined in php.ini
). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.
The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.
If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The memory_get_usage
function is your friend.
Related Questions:
- All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow
add a comment |
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the php.ini
file or by using ini_set('memory_limit', '128 M');
in the script (which will overwrite the value defined in php.ini
). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.
The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.
If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The memory_get_usage
function is your friend.
Related Questions:
- All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow
Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the php.ini
file or by using ini_set('memory_limit', '128 M');
in the script (which will overwrite the value defined in php.ini
). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.
The first thing to do is to minimise the amount of memory your script needs. For instance, if you're reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what's going on behind the scenes and when data is stored in memory vs. elsewhere.
If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The memory_get_usage
function is your friend.
Related Questions:
- All "Fatal error: Allowed memory size of XXX bytes exhausted" Questions on Stackoverflow
edited May 23 '17 at 12:34
community wiki
8 revs, 5 users 55%
xdazz
add a comment |
add a comment |
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}
.
The error case:
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE
. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
add a comment |
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}
.
The error case:
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE
. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
add a comment |
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}
.
The error case:
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE
. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}
.
The error case:
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
Possible fixes:
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE
. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
edited Dec 5 '18 at 10:18
community wiki
3 revs, 3 users 93%
Michael Berkowski
add a comment |
add a comment |
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים. which means "double colon" or "double dot twice".
This error typically happens if you inadvertently put ::
in your code.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- What do two colons mean in PHP?
- What's the difference between :: (double colon) and -> (arrow) in PHP?
- Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
- Scope Resolution Operator (::)
The easiest way to trigger this error is runninga()::b;
or$a=::;
.
– Ismael Miguel
Apr 13 '15 at 13:39
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
add a comment |
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים. which means "double colon" or "double dot twice".
This error typically happens if you inadvertently put ::
in your code.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- What do two colons mean in PHP?
- What's the difference between :: (double colon) and -> (arrow) in PHP?
- Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
- Scope Resolution Operator (::)
The easiest way to trigger this error is runninga()::b;
or$a=::;
.
– Ismael Miguel
Apr 13 '15 at 13:39
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
add a comment |
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים. which means "double colon" or "double dot twice".
This error typically happens if you inadvertently put ::
in your code.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- What do two colons mean in PHP?
- What's the difference between :: (double colon) and -> (arrow) in PHP?
- Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
- Scope Resolution Operator (::)
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew פעמיים נקודתיים. which means "double colon" or "double dot twice".
This error typically happens if you inadvertently put ::
in your code.
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
- What do two colons mean in PHP?
- What's the difference between :: (double colon) and -> (arrow) in PHP?
- Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
Documentation:
- Scope Resolution Operator (::)
edited May 23 '17 at 11:55
community wiki
6 revs, 4 users 75%
Rich Bradshaw
The easiest way to trigger this error is runninga()::b;
or$a=::;
.
– Ismael Miguel
Apr 13 '15 at 13:39
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
add a comment |
The easiest way to trigger this error is runninga()::b;
or$a=::;
.
– Ismael Miguel
Apr 13 '15 at 13:39
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
The easiest way to trigger this error is running
a()::b;
or $a=::;
.– Ismael Miguel
Apr 13 '15 at 13:39
The easiest way to trigger this error is running
a()::b;
or $a=::;
.– Ismael Miguel
Apr 13 '15 at 13:39
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
Aah, the beauty of T_PAAMAYIM_NEKUDOTAYIM...
– Roberto Maldonado
Aug 31 '18 at 5:53
add a comment |
Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
This means you're either using the same function/class name twice and need to rename one of them, or it is because you have used require
or include
where you should be using require_once
or include_once
.
When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.
Consider the following code:
class.php
<?php
class MyClass
{
public function doSomething()
{
// do stuff here
}
}
index.php
<?php
function do_stuff()
{
require 'class.php';
$obj = new MyClass;
$obj->doSomething();
}
do_stuff();
do_stuff();
The second call to do_stuff()
will produce the error above. By changing require
to require_once
, we can be certain that the file that contains the definition of MyClass
will only be loaded once, and the error will be avoided.
2
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
add a comment |
Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
This means you're either using the same function/class name twice and need to rename one of them, or it is because you have used require
or include
where you should be using require_once
or include_once
.
When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.
Consider the following code:
class.php
<?php
class MyClass
{
public function doSomething()
{
// do stuff here
}
}
index.php
<?php
function do_stuff()
{
require 'class.php';
$obj = new MyClass;
$obj->doSomething();
}
do_stuff();
do_stuff();
The second call to do_stuff()
will produce the error above. By changing require
to require_once
, we can be certain that the file that contains the definition of MyClass
will only be loaded once, and the error will be avoided.
2
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
add a comment |
Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
This means you're either using the same function/class name twice and need to rename one of them, or it is because you have used require
or include
where you should be using require_once
or include_once
.
When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.
Consider the following code:
class.php
<?php
class MyClass
{
public function doSomething()
{
// do stuff here
}
}
index.php
<?php
function do_stuff()
{
require 'class.php';
$obj = new MyClass;
$obj->doSomething();
}
do_stuff();
do_stuff();
The second call to do_stuff()
will produce the error above. By changing require
to require_once
, we can be certain that the file that contains the definition of MyClass
will only be loaded once, and the error will be avoided.
Fatal error: Cannot redeclare class [class name]
Fatal error: Cannot redeclare [function name]
This means you're either using the same function/class name twice and need to rename one of them, or it is because you have used require
or include
where you should be using require_once
or include_once
.
When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.
Consider the following code:
class.php
<?php
class MyClass
{
public function doSomething()
{
// do stuff here
}
}
index.php
<?php
function do_stuff()
{
require 'class.php';
$obj = new MyClass;
$obj->doSomething();
}
do_stuff();
do_stuff();
The second call to do_stuff()
will produce the error above. By changing require
to require_once
, we can be certain that the file that contains the definition of MyClass
will only be loaded once, and the error will be avoided.
edited May 15 '14 at 11:55
community wiki
4 revs, 3 users 96%
DaveRandom
2
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
add a comment |
2
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
2
2
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
Is it worth mentioning using autoloading, and standards such as PSR-4 or even the now deprecated PSR-0 pretty much get rid of this by saving you from needing to use require/include yourself (bar a few bizarre edge cases).
– DanielM
Jun 1 '15 at 16:35
add a comment |
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include
, require
or fopen
and PHP couldn't find the file or have not enough permission to load the file.
This can happen for a variety of reasons :
- the file path is wrong
- the file path is relative
- include path is wrong
- permissions are too restrictive
- SELinux is in force
- and many more ...
One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__
or dirname(__FILE__)
:
include __DIR__ . '/inc/globals.inc.php';
or:
require dirname(__FILE__) . '/inc/globals.inc.php';
Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.
The best way to solve this problem quickly is to follow the troubleshooting checklist below.
Related Questions:
- Troubleshooting checklist: Failed to open stream
Related Errors:
- Warning: open_basedir restriction in effect
add a comment |
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include
, require
or fopen
and PHP couldn't find the file or have not enough permission to load the file.
This can happen for a variety of reasons :
- the file path is wrong
- the file path is relative
- include path is wrong
- permissions are too restrictive
- SELinux is in force
- and many more ...
One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__
or dirname(__FILE__)
:
include __DIR__ . '/inc/globals.inc.php';
or:
require dirname(__FILE__) . '/inc/globals.inc.php';
Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.
The best way to solve this problem quickly is to follow the troubleshooting checklist below.
Related Questions:
- Troubleshooting checklist: Failed to open stream
Related Errors:
- Warning: open_basedir restriction in effect
add a comment |
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include
, require
or fopen
and PHP couldn't find the file or have not enough permission to load the file.
This can happen for a variety of reasons :
- the file path is wrong
- the file path is relative
- include path is wrong
- permissions are too restrictive
- SELinux is in force
- and many more ...
One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__
or dirname(__FILE__)
:
include __DIR__ . '/inc/globals.inc.php';
or:
require dirname(__FILE__) . '/inc/globals.inc.php';
Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.
The best way to solve this problem quickly is to follow the troubleshooting checklist below.
Related Questions:
- Troubleshooting checklist: Failed to open stream
Related Errors:
- Warning: open_basedir restriction in effect
Warning: [function]: failed to open stream: [reason]
It happens when you call a file usually by include
, require
or fopen
and PHP couldn't find the file or have not enough permission to load the file.
This can happen for a variety of reasons :
- the file path is wrong
- the file path is relative
- include path is wrong
- permissions are too restrictive
- SELinux is in force
- and many more ...
One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__
or dirname(__FILE__)
:
include __DIR__ . '/inc/globals.inc.php';
or:
require dirname(__FILE__) . '/inc/globals.inc.php';
Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.
The best way to solve this problem quickly is to follow the troubleshooting checklist below.
Related Questions:
- Troubleshooting checklist: Failed to open stream
Related Errors:
- Warning: open_basedir restriction in effect
edited Dec 5 '18 at 10:19
community wiki
7 revs, 4 users 48%
Mahdi
add a comment |
add a comment |
Notice: Use of undefined constant XXX - assumed 'XXX'
or, in PHP 7.2 or later:
Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)
This notice occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
- What does the PHP error message “Notice: Use of undefined constant” mean?
2
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
add a comment |
Notice: Use of undefined constant XXX - assumed 'XXX'
or, in PHP 7.2 or later:
Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)
This notice occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
- What does the PHP error message “Notice: Use of undefined constant” mean?
2
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
add a comment |
Notice: Use of undefined constant XXX - assumed 'XXX'
or, in PHP 7.2 or later:
Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)
This notice occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
- What does the PHP error message “Notice: Use of undefined constant” mean?
Notice: Use of undefined constant XXX - assumed 'XXX'
or, in PHP 7.2 or later:
Warning: Use of undefined constant XXX - assumed 'XXX' (this will throw an Error in a future version of PHP)
This notice occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.
One of the most common causes of this notice is a failure to quote a string used as an associative array key.
For example:
// Wrong
echo $array[key];
// Right
echo $array['key'];
Another common cause is a missing $
(dollar) sign in front of a variable name:
// Wrong
echo varName;
// Right
echo $varName;
Or perhaps you have misspelled some other constant or keyword:
// Wrong
$foo = fasle;
// Right
$foo = false;
It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.
Related Questions:
- What does the PHP error message “Notice: Use of undefined constant” mean?
edited Dec 5 '18 at 10:19
community wiki
12 revs, 7 users 72%
DaveRandom
2
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
add a comment |
2
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
2
2
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
I would say the most common cause is forgetting $ in front of a variable, not arrays.
– Overv
Oct 10 '12 at 8:22
add a comment |
Notice: Undefined variable
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
foreach ($items as $item) {
// do something with item
$counter++;
}
If you didn't define $counter
before, the code above will trigger the notice.
The correct way would be to set the variable before using it, even if it's just an empty string like
$counter = 0;
foreach ($items as $item) {
// do something with item
$counter++;
}
Related Questions:
- All PHP "Notice: Undefined Variable" Questions on Stackoverflow
- PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
- Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
add a comment |
Notice: Undefined variable
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
foreach ($items as $item) {
// do something with item
$counter++;
}
If you didn't define $counter
before, the code above will trigger the notice.
The correct way would be to set the variable before using it, even if it's just an empty string like
$counter = 0;
foreach ($items as $item) {
// do something with item
$counter++;
}
Related Questions:
- All PHP "Notice: Undefined Variable" Questions on Stackoverflow
- PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
- Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
add a comment |
Notice: Undefined variable
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
foreach ($items as $item) {
// do something with item
$counter++;
}
If you didn't define $counter
before, the code above will trigger the notice.
The correct way would be to set the variable before using it, even if it's just an empty string like
$counter = 0;
foreach ($items as $item) {
// do something with item
$counter++;
}
Related Questions:
- All PHP "Notice: Undefined Variable" Questions on Stackoverflow
- PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
- Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
Notice: Undefined variable
Happens when you try to use a variable that wasn't previously defined.
A typical example would be
foreach ($items as $item) {
// do something with item
$counter++;
}
If you didn't define $counter
before, the code above will trigger the notice.
The correct way would be to set the variable before using it, even if it's just an empty string like
$counter = 0;
foreach ($items as $item) {
// do something with item
$counter++;
}
Related Questions:
- All PHP "Notice: Undefined Variable" Questions on Stackoverflow
- PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
- Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
edited May 23 '17 at 12:02
community wiki
7 revs, 6 users 62%
aleation
add a comment |
add a comment |
Notice: Uninitialized string offset: *
As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.
Consider you, are trying to show every letter from $string
$string = 'ABCD';
for ($i=0, $len = strlen($string); $i <= $len; $i++){
echo "$string[$i] n";
}
The above example will generate (online demo):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D
you'll get the error, because inside the for()
loop, you have told PHP to show you the from first to fifth string character from 'ABCD'
Which, exists, but since the loop starts to count from 0
and echoes D
by the time it reaches to 4
, it will throw an offset error.
Similar Errors:
- Illegal string offset 'option 1'
add a comment |
Notice: Uninitialized string offset: *
As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.
Consider you, are trying to show every letter from $string
$string = 'ABCD';
for ($i=0, $len = strlen($string); $i <= $len; $i++){
echo "$string[$i] n";
}
The above example will generate (online demo):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D
you'll get the error, because inside the for()
loop, you have told PHP to show you the from first to fifth string character from 'ABCD'
Which, exists, but since the loop starts to count from 0
and echoes D
by the time it reaches to 4
, it will throw an offset error.
Similar Errors:
- Illegal string offset 'option 1'
add a comment |
Notice: Uninitialized string offset: *
As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.
Consider you, are trying to show every letter from $string
$string = 'ABCD';
for ($i=0, $len = strlen($string); $i <= $len; $i++){
echo "$string[$i] n";
}
The above example will generate (online demo):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D
you'll get the error, because inside the for()
loop, you have told PHP to show you the from first to fifth string character from 'ABCD'
Which, exists, but since the loop starts to count from 0
and echoes D
by the time it reaches to 4
, it will throw an offset error.
Similar Errors:
- Illegal string offset 'option 1'
Notice: Uninitialized string offset: *
As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.
Consider you, are trying to show every letter from $string
$string = 'ABCD';
for ($i=0, $len = strlen($string); $i <= $len; $i++){
echo "$string[$i] n";
}
The above example will generate (online demo):
A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X
And, as soon as the script finishes echoing D
you'll get the error, because inside the for()
loop, you have told PHP to show you the from first to fifth string character from 'ABCD'
Which, exists, but since the loop starts to count from 0
and echoes D
by the time it reaches to 4
, it will throw an offset error.
Similar Errors:
- Illegal string offset 'option 1'
edited Dec 5 '18 at 10:20
community wiki
9 revs, 3 users 71%
samayo
add a comment |
add a comment |
Warning: open_basedir restriction in effect
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called open_basedir
.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
- open_basedir restriction in effect. File(/) is not within the allowed path(s):
- All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow
1
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
add a comment |
Warning: open_basedir restriction in effect
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called open_basedir
.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
- open_basedir restriction in effect. File(/) is not within the allowed path(s):
- All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow
1
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
add a comment |
Warning: open_basedir restriction in effect
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called open_basedir
.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
- open_basedir restriction in effect. File(/) is not within the allowed path(s):
- All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow
Warning: open_basedir restriction in effect
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called open_basedir
.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
- open_basedir restriction in effect. File(/) is not within the allowed path(s):
- All PHP "Warning: open_basedir restriction in effect" Querstions on Stackoverflow
edited May 23 '17 at 11:55
community wiki
6 revs
hakre
1
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
add a comment |
1
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
1
1
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
This occurs most often on a shared host, people don't usually lock themselves out of directories :-)
– uınbɐɥs
Oct 7 '12 at 20:37
add a comment |
Parse error: syntax error, unexpected T_VARIABLE
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
What I am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the .
operator. The interpreter stops running your program when it encounters a parse error.
In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.
What you should do is check carefully at the lines around where the error is for any simple mistakes.
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE
. That T_VARIABLE
thing is called a token
. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE
token in the interpreter's list.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE
in your php.ini
. Parse errors should not exist in production scripts.
I always recommended to add the following statement, while coding:
error_reporting(E_ALL);
PHP error reporting
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
add a comment |
Parse error: syntax error, unexpected T_VARIABLE
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
What I am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the .
operator. The interpreter stops running your program when it encounters a parse error.
In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.
What you should do is check carefully at the lines around where the error is for any simple mistakes.
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE
. That T_VARIABLE
thing is called a token
. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE
token in the interpreter's list.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE
in your php.ini
. Parse errors should not exist in production scripts.
I always recommended to add the following statement, while coding:
error_reporting(E_ALL);
PHP error reporting
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
add a comment |
Parse error: syntax error, unexpected T_VARIABLE
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
What I am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the .
operator. The interpreter stops running your program when it encounters a parse error.
In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.
What you should do is check carefully at the lines around where the error is for any simple mistakes.
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE
. That T_VARIABLE
thing is called a token
. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE
token in the interpreter's list.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE
in your php.ini
. Parse errors should not exist in production scripts.
I always recommended to add the following statement, while coding:
error_reporting(E_ALL);
PHP error reporting
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
Parse error: syntax error, unexpected T_VARIABLE
Possible scenario
I can't seem to find where my code has gone wrong. Here is my full error:
Parse error: syntax error, unexpected T_VARIABLE on line x
What I am trying
$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';
Answer
Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the .
operator. The interpreter stops running your program when it encounters a parse error.
In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.
What you should do is check carefully at the lines around where the error is for any simple mistakes.
That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE
. That T_VARIABLE
thing is called a token
. It's the PHP interpreter's way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you've written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE
token in the interpreter's list.
Good read: List of Parser Tokens
So make sure you enable at least E_PARSE
in your php.ini
. Parse errors should not exist in production scripts.
I always recommended to add the following statement, while coding:
error_reporting(E_ALL);
PHP error reporting
Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:
NetBeans (a fine piece of beauty, free software) (the best in my opinion)
PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
Eclipse (beauty and the beast, free software)
Related Questions:
- Reference: PHP Parse/Syntax Errors; and How to solve them?
edited Dec 5 '18 at 10:21
community wiki
13 revs, 5 users 64%
NullPoiиteя
add a comment |
add a comment |
Parse error: syntax error, unexpected '['
This error comes in two variatians:
Variation 1
$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.
Variation 2
$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.
add a comment |
Parse error: syntax error, unexpected '['
This error comes in two variatians:
Variation 1
$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.
Variation 2
$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.
add a comment |
Parse error: syntax error, unexpected '['
This error comes in two variatians:
Variation 1
$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.
Variation 2
$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.
Parse error: syntax error, unexpected '['
This error comes in two variatians:
Variation 1
$arr = [1, 2, 3];
This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:
$arr = array(1, 2, 3);
See also this example from the manual.
Variation 2
$suffix = explode(',', 'foo,bar')[1];
Array dereferencing function results was also introduced in PHP 5.4. If it's not possible to upgrade you need to use a (temporary) variable:
$parts = explode(',', 'foo,bar');
$suffix = $parts[1];
See also this example from the manual.
edited Oct 26 '14 at 10:49
community wiki
3 revs, 2 users 92%
Ja͢ck
add a comment |
add a comment |
Notice: Trying to get property of non-object error
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
In this case, $users
is an array (so not an object) and it does not have any properties.
This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.
As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
The problem is accessing the nodeValue
property (field) of the first item while it has not been checked if it exists or not in the $result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if ($div) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
- Notice: Undefined Index
- Fatal error: Call to a member function ... on a non-object
json_decode
now returns an instance ofstdclass
by default, so the example code would actually work.
– Hugo Zink
Jan 21 '16 at 12:25
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "json_decode
now returns an instance ofstdclass
by default" ? I can't find that in the changelog.
– hakre
Jan 22 '16 at 5:47
According to the PHP manual's page on json_decode, by default, theassoc
parameter is set to false. This parameter decides whether the function returns astdclass
instead of an associative array.
– Hugo Zink
Jan 22 '16 at 8:16
add a comment |
Notice: Trying to get property of non-object error
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
In this case, $users
is an array (so not an object) and it does not have any properties.
This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.
As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
The problem is accessing the nodeValue
property (field) of the first item while it has not been checked if it exists or not in the $result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if ($div) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
- Notice: Undefined Index
- Fatal error: Call to a member function ... on a non-object
json_decode
now returns an instance ofstdclass
by default, so the example code would actually work.
– Hugo Zink
Jan 21 '16 at 12:25
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "json_decode
now returns an instance ofstdclass
by default" ? I can't find that in the changelog.
– hakre
Jan 22 '16 at 5:47
According to the PHP manual's page on json_decode, by default, theassoc
parameter is set to false. This parameter decides whether the function returns astdclass
instead of an associative array.
– Hugo Zink
Jan 22 '16 at 8:16
add a comment |
Notice: Trying to get property of non-object error
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
In this case, $users
is an array (so not an object) and it does not have any properties.
This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.
As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
The problem is accessing the nodeValue
property (field) of the first item while it has not been checked if it exists or not in the $result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if ($div) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
- Notice: Undefined Index
- Fatal error: Call to a member function ... on a non-object
Notice: Trying to get property of non-object error
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
In this case, $users
is an array (so not an object) and it does not have any properties.
This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.
As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
The problem is accessing the nodeValue
property (field) of the first item while it has not been checked if it exists or not in the $result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if ($div) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
- Notice: Undefined Index
- Fatal error: Call to a member function ... on a non-object
edited May 23 '17 at 12:34
community wiki
3 revs
hakre
json_decode
now returns an instance ofstdclass
by default, so the example code would actually work.
– Hugo Zink
Jan 21 '16 at 12:25
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "json_decode
now returns an instance ofstdclass
by default" ? I can't find that in the changelog.
– hakre
Jan 22 '16 at 5:47
According to the PHP manual's page on json_decode, by default, theassoc
parameter is set to false. This parameter decides whether the function returns astdclass
instead of an associative array.
– Hugo Zink
Jan 22 '16 at 8:16
add a comment |
json_decode
now returns an instance ofstdclass
by default, so the example code would actually work.
– Hugo Zink
Jan 21 '16 at 12:25
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "json_decode
now returns an instance ofstdclass
by default" ? I can't find that in the changelog.
– hakre
Jan 22 '16 at 5:47
According to the PHP manual's page on json_decode, by default, theassoc
parameter is set to false. This parameter decides whether the function returns astdclass
instead of an associative array.
– Hugo Zink
Jan 22 '16 at 8:16
json_decode
now returns an instance of stdclass
by default, so the example code would actually work.– Hugo Zink
Jan 21 '16 at 12:25
json_decode
now returns an instance of stdclass
by default, so the example code would actually work.– Hugo Zink
Jan 21 '16 at 12:25
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "
json_decode
now returns an instance of stdclass
by default" ? I can't find that in the changelog.– hakre
Jan 22 '16 at 5:47
@HugoZink: It actually does (and always did) return an array for that example: 3v4l.org/SUDe0 - Also can you please provide reference for your writing that "
json_decode
now returns an instance of stdclass
by default" ? I can't find that in the changelog.– hakre
Jan 22 '16 at 5:47
According to the PHP manual's page on json_decode, by default, the
assoc
parameter is set to false. This parameter decides whether the function returns a stdclass
instead of an associative array.– Hugo Zink
Jan 22 '16 at 8:16
According to the PHP manual's page on json_decode, by default, the
assoc
parameter is set to false. This parameter decides whether the function returns a stdclass
instead of an associative array.– Hugo Zink
Jan 22 '16 at 8:16
add a comment |
Warning: [function] expects parameter 1 to be resource, boolean given
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The cURL extension defines another two resource types:
... a cURL handle and a cURL multi handle.
When var_dump
ed, the values look like this:
$resource = curl_init();
var_dump($resource);
resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)
) of a certain type ((curl)
).
You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false
instead. For instance, the fopen
function has this description:
Return Values
Returns a file pointer resource on success, or
FALSE
on error.
So in this code, $fp
will either be a resource(x) of type (stream)
or false
:
$fp = fopen(...);
If you do not check whether the fopen
operation succeed or failed and hence whether $fp
is a valid resource or false
and pass $fp
to another function which expects a resource, you may get the above error:
$fp = fopen(...);
$data = fread($fp, 1024);
Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:
$fp = fopen(...);
if (!$fp) {
trigger_error('Failed to allocate resource');
exit;
}
$data = fread($fp, 1024);
Related Errors:
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
add a comment |
Warning: [function] expects parameter 1 to be resource, boolean given
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The cURL extension defines another two resource types:
... a cURL handle and a cURL multi handle.
When var_dump
ed, the values look like this:
$resource = curl_init();
var_dump($resource);
resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)
) of a certain type ((curl)
).
You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false
instead. For instance, the fopen
function has this description:
Return Values
Returns a file pointer resource on success, or
FALSE
on error.
So in this code, $fp
will either be a resource(x) of type (stream)
or false
:
$fp = fopen(...);
If you do not check whether the fopen
operation succeed or failed and hence whether $fp
is a valid resource or false
and pass $fp
to another function which expects a resource, you may get the above error:
$fp = fopen(...);
$data = fread($fp, 1024);
Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:
$fp = fopen(...);
if (!$fp) {
trigger_error('Failed to allocate resource');
exit;
}
$data = fread($fp, 1024);
Related Errors:
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
add a comment |
Warning: [function] expects parameter 1 to be resource, boolean given
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The cURL extension defines another two resource types:
... a cURL handle and a cURL multi handle.
When var_dump
ed, the values look like this:
$resource = curl_init();
var_dump($resource);
resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)
) of a certain type ((curl)
).
You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false
instead. For instance, the fopen
function has this description:
Return Values
Returns a file pointer resource on success, or
FALSE
on error.
So in this code, $fp
will either be a resource(x) of type (stream)
or false
:
$fp = fopen(...);
If you do not check whether the fopen
operation succeed or failed and hence whether $fp
is a valid resource or false
and pass $fp
to another function which expects a resource, you may get the above error:
$fp = fopen(...);
$data = fread($fp, 1024);
Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:
$fp = fopen(...);
if (!$fp) {
trigger_error('Failed to allocate resource');
exit;
}
$data = fread($fp, 1024);
Related Errors:
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
Warning: [function] expects parameter 1 to be resource, boolean given
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The cURL extension defines another two resource types:
... a cURL handle and a cURL multi handle.
When var_dump
ed, the values look like this:
$resource = curl_init();
var_dump($resource);
resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)
) of a certain type ((curl)
).
You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false
instead. For instance, the fopen
function has this description:
Return Values
Returns a file pointer resource on success, or
FALSE
on error.
So in this code, $fp
will either be a resource(x) of type (stream)
or false
:
$fp = fopen(...);
If you do not check whether the fopen
operation succeed or failed and hence whether $fp
is a valid resource or false
and pass $fp
to another function which expects a resource, you may get the above error:
$fp = fopen(...);
$data = fread($fp, 1024);
Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:
$fp = fopen(...);
if (!$fp) {
trigger_error('Failed to allocate resource');
exit;
}
$data = fread($fp, 1024);
Related Errors:
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
edited May 23 '17 at 12:26
community wiki
5 revs, 2 users 94%
deceze
add a comment |
add a comment |
Warning: Illegal string offset 'XXX'
This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.
Example:
$var = "test";
echo $var["a_key"];
If you think the variable should be an array, see where it comes from and fix the problem there.
add a comment |
Warning: Illegal string offset 'XXX'
This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.
Example:
$var = "test";
echo $var["a_key"];
If you think the variable should be an array, see where it comes from and fix the problem there.
add a comment |
Warning: Illegal string offset 'XXX'
This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.
Example:
$var = "test";
echo $var["a_key"];
If you think the variable should be an array, see where it comes from and fix the problem there.
Warning: Illegal string offset 'XXX'
This happens when you try to access an array element with the square bracket syntax, but you're doing this on a string, and not on an array, so the operation clearly doesn't make sense.
Example:
$var = "test";
echo $var["a_key"];
If you think the variable should be an array, see where it comes from and fix the problem there.
edited Dec 28 '14 at 16:46
community wiki
2 revs
Karoly Horvath
add a comment |
add a comment |
Code doesn't run/what looks like parts of my PHP code are output
If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?>
tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.
To actually run your PHP scripts, you need:
- a web server which executes your script
- to set the file extension to .php, otherwise the web server won't interpret it as such*
- to access your .php file via the web server
* Unless you reconfigure it, everything can be configured.
This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:
file://C:/path/to/my/file.php
This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:
http://localhost/my/file.php
You may also want to check whether you're using short open tags <?
instead of <?php
and your PHP configuration has turned short open tags off.
Also see PHP code is not being executed, instead code shows on the page
add a comment |
Code doesn't run/what looks like parts of my PHP code are output
If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?>
tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.
To actually run your PHP scripts, you need:
- a web server which executes your script
- to set the file extension to .php, otherwise the web server won't interpret it as such*
- to access your .php file via the web server
* Unless you reconfigure it, everything can be configured.
This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:
file://C:/path/to/my/file.php
This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:
http://localhost/my/file.php
You may also want to check whether you're using short open tags <?
instead of <?php
and your PHP configuration has turned short open tags off.
Also see PHP code is not being executed, instead code shows on the page
add a comment |
Code doesn't run/what looks like parts of my PHP code are output
If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?>
tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.
To actually run your PHP scripts, you need:
- a web server which executes your script
- to set the file extension to .php, otherwise the web server won't interpret it as such*
- to access your .php file via the web server
* Unless you reconfigure it, everything can be configured.
This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:
file://C:/path/to/my/file.php
This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:
http://localhost/my/file.php
You may also want to check whether you're using short open tags <?
instead of <?php
and your PHP configuration has turned short open tags off.
Also see PHP code is not being executed, instead code shows on the page
Code doesn't run/what looks like parts of my PHP code are output
If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?>
tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.
To actually run your PHP scripts, you need:
- a web server which executes your script
- to set the file extension to .php, otherwise the web server won't interpret it as such*
- to access your .php file via the web server
* Unless you reconfigure it, everything can be configured.
This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:
file://C:/path/to/my/file.php
This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:
http://localhost/my/file.php
You may also want to check whether you're using short open tags <?
instead of <?php
and your PHP configuration has turned short open tags off.
Also see PHP code is not being executed, instead code shows on the page
edited May 23 '17 at 11:47
community wiki
5 revs, 2 users 95%
deceze
add a comment |
add a comment |
Warning: mysql_connect(): Access denied for user 'name'@'host'
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on
mysql_connect("localhost", "user", "pw")
for examples.
Check that you actually used a
$username
and$password
.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
(using password: NO)
. Only the local test server usually allows to connect with username
root
, no password, and thetest
database name.You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like
$
, escape them, or put the password in single quotes.Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be
"localhost"
, which normally utilizes a local named socket when available. Othertimes you can try"127.0.0.1"
as fallback.Should your MySQL/MariaDB server listen on a different port, then use
"servername:3306"
.If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g.
DB_USER
orDB_PASSWORD
, check that they're actually defined.
If you get a
"Warning: Access defined for 'DB_USER'@'host'"
and a"Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.Verify that your e.g.
xy/db-config.php
was actually included and whatelse.
Check for correctly set
GRANT
permissions.
It's not sufficient to have a
username
+password
pair.Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for
mysql_query
calls, if you don't have permissions toSELECT
from a specific table, orINSERT
/UPDATE
, and more commonlyDELETE
anything.You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with
Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.
Check that
mysql.default_user=
andmysql.default_password=
have meaningful values.Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
- Serverfault: mysql access denied for 'root'@'name of the computer'
- Warning: mysql_connect(): Access denied
- Warning: mysql_select_db() Access denied for user ''@'localhost' (using password: NO)
- Access denied for user 'root'@'localhost' with PHPMyAdmin
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
1
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
add a comment |
Warning: mysql_connect(): Access denied for user 'name'@'host'
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on
mysql_connect("localhost", "user", "pw")
for examples.
Check that you actually used a
$username
and$password
.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
(using password: NO)
. Only the local test server usually allows to connect with username
root
, no password, and thetest
database name.You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like
$
, escape them, or put the password in single quotes.Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be
"localhost"
, which normally utilizes a local named socket when available. Othertimes you can try"127.0.0.1"
as fallback.Should your MySQL/MariaDB server listen on a different port, then use
"servername:3306"
.If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g.
DB_USER
orDB_PASSWORD
, check that they're actually defined.
If you get a
"Warning: Access defined for 'DB_USER'@'host'"
and a"Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.Verify that your e.g.
xy/db-config.php
was actually included and whatelse.
Check for correctly set
GRANT
permissions.
It's not sufficient to have a
username
+password
pair.Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for
mysql_query
calls, if you don't have permissions toSELECT
from a specific table, orINSERT
/UPDATE
, and more commonlyDELETE
anything.You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with
Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.
Check that
mysql.default_user=
andmysql.default_password=
have meaningful values.Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
- Serverfault: mysql access denied for 'root'@'name of the computer'
- Warning: mysql_connect(): Access denied
- Warning: mysql_select_db() Access denied for user ''@'localhost' (using password: NO)
- Access denied for user 'root'@'localhost' with PHPMyAdmin
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
1
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
add a comment |
Warning: mysql_connect(): Access denied for user 'name'@'host'
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on
mysql_connect("localhost", "user", "pw")
for examples.
Check that you actually used a
$username
and$password
.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
(using password: NO)
. Only the local test server usually allows to connect with username
root
, no password, and thetest
database name.You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like
$
, escape them, or put the password in single quotes.Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be
"localhost"
, which normally utilizes a local named socket when available. Othertimes you can try"127.0.0.1"
as fallback.Should your MySQL/MariaDB server listen on a different port, then use
"servername:3306"
.If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g.
DB_USER
orDB_PASSWORD
, check that they're actually defined.
If you get a
"Warning: Access defined for 'DB_USER'@'host'"
and a"Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.Verify that your e.g.
xy/db-config.php
was actually included and whatelse.
Check for correctly set
GRANT
permissions.
It's not sufficient to have a
username
+password
pair.Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for
mysql_query
calls, if you don't have permissions toSELECT
from a specific table, orINSERT
/UPDATE
, and more commonlyDELETE
anything.You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with
Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.
Check that
mysql.default_user=
andmysql.default_password=
have meaningful values.Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
- Serverfault: mysql access denied for 'root'@'name of the computer'
- Warning: mysql_connect(): Access denied
- Warning: mysql_select_db() Access denied for user ''@'localhost' (using password: NO)
- Access denied for user 'root'@'localhost' with PHPMyAdmin
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
Warning: mysql_connect(): Access denied for user 'name'@'host'
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on
mysql_connect("localhost", "user", "pw")
for examples.
Check that you actually used a
$username
and$password
.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
(using password: NO)
. Only the local test server usually allows to connect with username
root
, no password, and thetest
database name.You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like
$
, escape them, or put the password in single quotes.Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
- It's uncommon that you gain access using no password - which is what happened when the Warning: said
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be
"localhost"
, which normally utilizes a local named socket when available. Othertimes you can try"127.0.0.1"
as fallback.Should your MySQL/MariaDB server listen on a different port, then use
"servername:3306"
.If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g.
DB_USER
orDB_PASSWORD
, check that they're actually defined.
If you get a
"Warning: Access defined for 'DB_USER'@'host'"
and a"Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.Verify that your e.g.
xy/db-config.php
was actually included and whatelse.
Check for correctly set
GRANT
permissions.
It's not sufficient to have a
username
+password
pair.Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for
mysql_query
calls, if you don't have permissions toSELECT
from a specific table, orINSERT
/UPDATE
, and more commonlyDELETE
anything.You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with
Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.
Check that
mysql.default_user=
andmysql.default_password=
have meaningful values.Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
- Serverfault: mysql access denied for 'root'@'name of the computer'
- Warning: mysql_connect(): Access denied
- Warning: mysql_select_db() Access denied for user ''@'localhost' (using password: NO)
- Access denied for user 'root'@'localhost' with PHPMyAdmin
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
edited May 23 '17 at 12:26
community wiki
4 revs
mario
1
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
add a comment |
1
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
1
1
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
mysql allows auto-connect via php-ini settings, then the same error message is given with the different command prefixed, e.g. "Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in ..." - just noting.
– hakre
Sep 20 '15 at 16:50
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
Ha, totally forgot about that! (Probably last used that with PHP3 or so..)
– mario
Sep 20 '15 at 17:02
add a comment |
Notice: Array to string conversion
This simply happens if you try to treat an array as a string:
$arr = array('foo', 'bar');
echo $arr; // Notice: Array to string conversion
$str = 'Something, ' . $arr; // Notice: Array to string conversion
An array cannot simply be echo
'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:
echo $arr[0]; // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar
Or loop the array:
foreach($arr as $key => $value) {
echo "array $key = $value";
// displays first: array 0 = foo
// displays next: array 1 = bar
}
If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.
add a comment |
Notice: Array to string conversion
This simply happens if you try to treat an array as a string:
$arr = array('foo', 'bar');
echo $arr; // Notice: Array to string conversion
$str = 'Something, ' . $arr; // Notice: Array to string conversion
An array cannot simply be echo
'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:
echo $arr[0]; // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar
Or loop the array:
foreach($arr as $key => $value) {
echo "array $key = $value";
// displays first: array 0 = foo
// displays next: array 1 = bar
}
If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.
add a comment |
Notice: Array to string conversion
This simply happens if you try to treat an array as a string:
$arr = array('foo', 'bar');
echo $arr; // Notice: Array to string conversion
$str = 'Something, ' . $arr; // Notice: Array to string conversion
An array cannot simply be echo
'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:
echo $arr[0]; // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar
Or loop the array:
foreach($arr as $key => $value) {
echo "array $key = $value";
// displays first: array 0 = foo
// displays next: array 1 = bar
}
If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.
Notice: Array to string conversion
This simply happens if you try to treat an array as a string:
$arr = array('foo', 'bar');
echo $arr; // Notice: Array to string conversion
$str = 'Something, ' . $arr; // Notice: Array to string conversion
An array cannot simply be echo
'd or concatenated with a string, because the result is not well defined. PHP will use the string "Array" in place of the array, and trigger the notice to point out that that's probably not what was intended and that you should be checking your code here. You probably want something like this instead:
echo $arr[0]; // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar
Or loop the array:
foreach($arr as $key => $value) {
echo "array $key = $value";
// displays first: array 0 = foo
// displays next: array 1 = bar
}
If this notice appears somewhere you don't expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.
edited Apr 5 '18 at 15:29
community wiki
3 revs, 3 users 70%
deceze
add a comment |
add a comment |
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
$value = @(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you should not divide, or change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
- warning: division by zero
- Warning: Division By Zero Working on PHP and MySQL
- Division by zero error in WordPress Theme
- How to suppress the “Division by zero” error
- How to catch a division by zero?
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
For this example, if$var1
does == 0 then you can just set$var3
to$var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside theif
– James
Jun 17 '18 at 0:58
add a comment |
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
$value = @(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you should not divide, or change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
- warning: division by zero
- Warning: Division By Zero Working on PHP and MySQL
- Division by zero error in WordPress Theme
- How to suppress the “Division by zero” error
- How to catch a division by zero?
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
For this example, if$var1
does == 0 then you can just set$var3
to$var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside theif
– James
Jun 17 '18 at 0:58
add a comment |
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
$value = @(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you should not divide, or change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
- warning: division by zero
- Warning: Division By Zero Working on PHP and MySQL
- Division by zero error in WordPress Theme
- How to suppress the “Division by zero” error
- How to catch a division by zero?
Warning: Division by zero
The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
$value = @(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you should not divide, or change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
$var1 = 1; // var1 equaled zero so change var1 to equal one instead
$var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
$var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}
Related Questions:
- warning: division by zero
- Warning: Division By Zero Working on PHP and MySQL
- Division by zero error in WordPress Theme
- How to suppress the “Division by zero” error
- How to catch a division by zero?
edited May 23 '17 at 12:10
community wiki
4 revs, 2 users 89%
davidcondrey
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
For this example, if$var1
does == 0 then you can just set$var3
to$var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside theif
– James
Jun 17 '18 at 0:58
add a comment |
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
For this example, if$var1
does == 0 then you can just set$var3
to$var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside theif
– James
Jun 17 '18 at 0:58
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
Setting to 1 if it was 0 will stop the error but is this really any better than the suppression you said shouldn't be used (which I agree with)? I'd suggest most times it'd be likely some other message or value would be returned.
– James
Jun 17 '18 at 0:56
For this example, if
$var1
does == 0 then you can just set $var3
to $var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside the if
– James
Jun 17 '18 at 0:58
For this example, if
$var1
does == 0 then you can just set $var3
to $var2
. Even if not doing that, the else is not needed at all as the assignment is the same in both cases so no else and assign outside the if
– James
Jun 17 '18 at 0:58
add a comment |
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT
flag in your error_reporting()
settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br()
or $html::br()
You can actually avoid this error by not adding E_STRICT
to error_reporting()
, eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT
is included in E_ALL
[ref]. But that is not adviceable. The solution is to define your intended static function as actual static
:
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
- How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?
add a comment |
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT
flag in your error_reporting()
settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br()
or $html::br()
You can actually avoid this error by not adding E_STRICT
to error_reporting()
, eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT
is included in E_ALL
[ref]. But that is not adviceable. The solution is to define your intended static function as actual static
:
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
- How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?
add a comment |
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT
flag in your error_reporting()
settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br()
or $html::br()
You can actually avoid this error by not adding E_STRICT
to error_reporting()
, eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT
is included in E_ALL
[ref]. But that is not adviceable. The solution is to define your intended static function as actual static
:
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
- How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?
Strict Standards: Non-static method [<class>::<method>] should not be called statically
Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT
flag in your error_reporting()
settings.
Example :
class HTML {
public function br() {
echo '<br>';
}
}
HTML::br()
or $html::br()
You can actually avoid this error by not adding E_STRICT
to error_reporting()
, eg
error_reporting(E_ALL & ~E_STRICT);
since as for PHP 5.4.0 and above, E_STRICT
is included in E_ALL
[ref]. But that is not adviceable. The solution is to define your intended static function as actual static
:
public static function br() {
echo '<br>';
}
or call the function conventionally :
$html = new HTML();
$html->br();
Related questions :
- How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?
edited May 23 '17 at 12:10
community wiki
5 revs, 2 users 98%
davidkonrad
add a comment |
add a comment |
Fatal error: [TraitA] and [TraitB] define the same property ([$x]) in the composition of [ClassC]
Occurs when a class attempts to use
multiple Traits, where two or more of those Traits have defined a property by the same name, and with the property having differing initial values.
Example:
<?php
trait TraitA
{
public $x = 'a';
}
trait TraitB
{
public $x = 'b';
}
class ClassC
{
use TraitA, TraitB;
}
Problematic: While it's possible to resolve conflicts between competing methods, there is currently no syntax that would resolve a conflict between two competing properties. The only solution at this time is to refactor; i.e., avoid a conflict between property names that produces a fatal error.
Related Questions:
- PHP Traits: How to resolve a property name conflict?
- Traits - property conflict with parent class
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
add a comment |
Fatal error: [TraitA] and [TraitB] define the same property ([$x]) in the composition of [ClassC]
Occurs when a class attempts to use
multiple Traits, where two or more of those Traits have defined a property by the same name, and with the property having differing initial values.
Example:
<?php
trait TraitA
{
public $x = 'a';
}
trait TraitB
{
public $x = 'b';
}
class ClassC
{
use TraitA, TraitB;
}
Problematic: While it's possible to resolve conflicts between competing methods, there is currently no syntax that would resolve a conflict between two competing properties. The only solution at this time is to refactor; i.e., avoid a conflict between property names that produces a fatal error.
Related Questions:
- PHP Traits: How to resolve a property name conflict?
- Traits - property conflict with parent class
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
add a comment |
Fatal error: [TraitA] and [TraitB] define the same property ([$x]) in the composition of [ClassC]
Occurs when a class attempts to use
multiple Traits, where two or more of those Traits have defined a property by the same name, and with the property having differing initial values.
Example:
<?php
trait TraitA
{
public $x = 'a';
}
trait TraitB
{
public $x = 'b';
}
class ClassC
{
use TraitA, TraitB;
}
Problematic: While it's possible to resolve conflicts between competing methods, there is currently no syntax that would resolve a conflict between two competing properties. The only solution at this time is to refactor; i.e., avoid a conflict between property names that produces a fatal error.
Related Questions:
- PHP Traits: How to resolve a property name conflict?
- Traits - property conflict with parent class
Fatal error: [TraitA] and [TraitB] define the same property ([$x]) in the composition of [ClassC]
Occurs when a class attempts to use
multiple Traits, where two or more of those Traits have defined a property by the same name, and with the property having differing initial values.
Example:
<?php
trait TraitA
{
public $x = 'a';
}
trait TraitB
{
public $x = 'b';
}
class ClassC
{
use TraitA, TraitB;
}
Problematic: While it's possible to resolve conflicts between competing methods, there is currently no syntax that would resolve a conflict between two competing properties. The only solution at this time is to refactor; i.e., avoid a conflict between property names that produces a fatal error.
Related Questions:
- PHP Traits: How to resolve a property name conflict?
- Traits - property conflict with parent class
answered Nov 7 '17 at 14:27
community wiki
jaswrks
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
add a comment |
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
Note that this also happens when TraitA::$x and TraitB::$x are the same value(say 'a') but TraitA::$a is public and TraitB::$a is private or protected
– Jelmergu
Nov 7 '17 at 18:45
add a comment |
1 2
next
protected by Samuel Liew♦ Oct 5 '15 at 8:59
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
1
@PeterSmit: The php-errors tag has no wiki summary, can you help us create it?
– hakre
Oct 8 '12 at 12:44
7
Also, to move discussion out of comments, please go to this meta question
– Earlz
Oct 8 '12 at 13:56
2
X-Ref: PHP Parse/Syntax Errors; and How to solve them?; Elsewhere: Common PHP Errors and Solutions
– hakre
Aug 11 '13 at 21:47
1
see this coding.smashingmagazine.com/2011/11/30/… and this also mediawiki.org/wiki/Manual:Errors_and_symptoms
– krishna
Aug 27 '13 at 14:26
1
X-Ref: Fixing PHP Errors (May 2013; by Jason McCreary)
– hakre
Sep 3 '13 at 16:37