Ohk, I just started to learn PHP and MySQL. Everything was going fine untill this thing boiled up my mind.
Here is the problem.
I have two php files in the same directory.
mysql.php--->
<?php
require("connect.php")or die(mysql_error());
?>
connect.php--->
<?php
error_reporting(0);
$connect=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("phpacademy")or die(mysql_error());
echo"Connected!";
?>
The problem is that whenever I am running the connect.php script directly, its working fine.
But when I run mysql.php to connect to the other script it gives the following error:
Warning: require(1): failed to open stream: No such file or directory in C:\xampp\htdocs\stckovrflw1\mysql.php on line 3
Fatal error: require(): Failed opening required '1' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\stckovrflw1\mysql.php on line 3
Its not getting the file even though it exists and the spelling is obviously not incorrect.
And the most amazing part is that, as soon as I remove the or die() everything works like a charm.
As I am a beginner I have no idea whats going on. I supposed that or die() is just for developer's or user's help to see the exact error, but in this case it is causing the error itself.
Do help!!!
Thanks in advance...:)
P.S.: I am running on localhost as mentioned in code also.
or has a higher precedence than require/require_once. Therefore php evaluates
('connect.php') or die("blah blah")
before passing the result to require. Or takes two boolean operands. ('connect.php') evaluates to true therefore the whole expression is true and
require true;
is invoked.
require takes string as parameter, so true casts to 1 by php.
so it became require 1 in your case
that generate failed to open error
A bug reported on bugs.php.net https://bugs.php.net/bug.php?id=15438 says:
"Because include() is a special language costruct, parentheses are not
needed around its argument. Take care when comparing return value.
<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}
// works
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
It is mysql_select_db and not mysql_selectdb
and by the way if you have begun learning php and mysql, better get yourself trained using mysqli and not mysql
You don't have to use die() in the require line, if the file is not present PHP will automatically throw error
FYI:
die() method comes in handy for debugging yes!! thts true when you want to stop the execution of some loop or code flow when you want to analyse what are the variables that you get as output and the ones that you dont
<?php
require("connect.php")or die(mysql_error());
?>
Does not work. PHP at first evaluates the expression
("connect.php") or die(mysql_error())
And this expression is always true. The result ist:
require true
This doesn't work. You even don't need to check the connection because you checked this in your connect.php. But double checking is not wrong and it's better for future compatibility (for example you can change your implementation and remove the check in connect.php). So you can use this instead:
<?php
require("connect.php");
if(!$connect)
die(mysql_error());
?>
error_reporting(0);
$connect=mysql_connect("localhost","root","") or die(mysql_error());
mysql_selectdb("phpacademy",$connect)or die(mysql_error());
echo"Connected!";
You need to set you PHP.INI
It is clear that your include path is set to default, which is (include_path='.;C:\xampp\php\PEAR')
You PHP-config is looking for file in 'C:\xampp\php\PEAR', which is not there.
Try set_include_path() (reference: www.php.net/set_include_path)
<?php
set_include_path('C:\xampp\htdocs\stckovrflw1\');
require("connect.php")or die(mysql_error());
?>
mysql_selectdb("phpacademy",$connect)or die(mysql_error());
Related
There is something strange on one of my PHP servers. Other servers show different behaviour. But I don't think this is caused by an environment setting.
I'm starting to believe this is a bug. Has anyone heard of this?
is_readable() will only return true if you call it at least once before you start the session.
If you start the session first, all is_readable() calls return false. Though you can still read the file with readfile() anyway.
<?php
// do session_start() to here and you will get BadBad
error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
ob_start();
// or do session_start() here and you will also get BadBad
echo is_readable("foo.bar") ? "Good" : "Bad";
// But do session_start() here and you get GoodGood
echo is_readable("foo.bar") ? "Good" : "Bad";
// or even do it here and you will still get GoodGood
echo #++$_SESSION['counter']; // incrementing number always follow GoodGood or BadBad
readfile("foo.bar"); // the contents also always follow GoodGood or BadBad
?>
The incrementing number always shows, so sessions are working fine.
Also the file contents always shows, so the file is readable.
I'm running 32 bit PHP Version 5.3.26 on Windows Server 2012 64 bit with IIS 7.5.
What could it be?
i tried the following code to import two files
<?php echo "php";
require('../globalvasr.php') or die("error");
require('../newcosn.php') or die("error2");
$config = new GlobalConfigs();
?>
It does not shows error and it just simply displays a blank page.Also i am unable to use the variable defined in those two files.
Like $config->DBNAME.
I dont know whats wrong in this.
Please help me find it.
Thank you.
require, in contrast to include, automatically dies and does not have a return value.
This means the or die() is bad. Better:
<?php echo "php";
require('./globalvasr.php');
require('./newcosn.php');
$config = new GlobalConfigs();
?>
Require generates a fatal error when require fails, causing the script execution to stop immediatly.
As you seem to be running in a web env, your output (all echo or print statements) is buffered until the end of the script.
So here the require fails, causing a fatal error (that should be available in the error log) before the output buffer is emptied, preventing your first "echo" to be sent to the browser. that's why you get a blank page.
Try replacing the require with an include, you will get a warning instead of the fatal error.
if you have blank page, set error_reporting: E_ALL and Display_errors: On in php.ini or put on start of your script these lines
error_reporting(E_ALL);
ini_set('Display_errors','On');
then you will see errors
I'm trying to offload the process of connecting to a database to a DBConfig.php file, as suggested pretty much everywhere, because I'll need to reuse the code in several files.
The suggestion is always framed as (edited to reflect my actual code):
-------DBConfig.php-------
<?php
$link = mysql_connect('localhost','user','pass');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db_name : ' . mysql_error());
}
?>
-------Parent.php-------
<!DOCTYPE html>
<?php
require_once 'DBConfig.php';
$something = mysql_query("SELECT * FROM `table` LIMIT 0, 30 ");
// This query works fine if the mysql_connect() and
// mysql_select_db() stuff is in this script in place
// of the require_once.
$listofthings = array();
while($temp = mysql_fetch_array($something)){
$listofthings[] = $temp;
}
// Do other things too
?>
But when I try to do mysql_fetch_array($something), it fails with the warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given.
Keeping in mind that everything works beautifully if I simply drop the contents of DBConfig.php into the parent script instead of require 'DBConfig.php';...
And also noting that print(require 'DBConfig.php'); //- 1 (PHP is returning a 1 to indicate that it is successfully locating and including the file. See example 5)...
What is going on, and how do I fix it? I am using the default configuration for WAMPServer (Apache 2.4.2, PHP 5.4.3), running on Windows 7 x64.
If this
require 'DBConfig.php';
is literally what you are doing, there is absolutely no way the script can be executed in some other scope. If you were using a http:// URL, it would be the cause but not if you use a relative path like you do.
You are not doing any error checking after connecting to your database, nor after the mysql_query() call, so it's more likely it's simply the query breaking. Add proper error checking to your queries and you will know more.
Another possibility is if you call DBConfig.php inside a function. Functions will mess with your include's scope. But there's none in your example, so I'm assuming that is not the issue.
Probably your query has some mistake. Try
mysql_query($query) or die( mysql_error() );
mysql_query() returns FALSE (boolean) on error.
If this is exact code that You are using, please change the:
require 'DBConfig.php';
to:
require('DBConfig.php');
Need to know what are you giving in variable $pretend_this_var_is_a_querystring.
This error is usually generated if the query fails. We need to know what string you are passing in mysql_query() function.
Please do check your query string.
Also in your DBConfig.php. It should be
$db_selected = mysql_select_db('db_name', $link);
I think that you include the wrong file. (with the same name, but in different location).
If the DBConfig.php file that you want is in the same directory of your Parent.php try to do
require_once dirname(__FILE__).'/DBConfig.php';
When you include your DBConfig.php file, the effect MUST be the same (in your case) if you copy and paste the code of DBConfig in your parent.php file.
If this not happens, it's because:
The file that you include is not that you think. (some set_include_path in other folder)
The content of the file that you include is not that you think.
There's no other way.
Ok, so a little while back I had some help writing some PHP voting code, it worked just fine after I upgraded my server to use the latest version of PHP. However now I have switched servers, and the PHP isn't as up to date as the other one. Anyways here's my code:
<?php
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}
if($_GET['click'] == 'up1'){
file_put_contents('vote/1u.txt', ((int) file_get_contents('vote/1u.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
Execute and display:
<img src="images/thumbsup.jpg" width="40px"border="0"> <br>Votes: <?php echo file_get_contents('vote/up1.txt'); ?>
Now when on my other server (PHP version 5.2.5) this code worked great! However on my new server the PHP version is 5.2.11, and because of this the code won't work. My question is, is there any way to make this more compatible with an earlier version of PHP, or to write completely new code that will work just like this one? Or is there a way to tell my servers to use PHP 5.2.5+? I'm using cPanel X admin panel.
I have set the text file permissions to 777 and still nothing!
you are checking for variable "click" but executing the code only if it equals "up1".
But your link tells click to equals "yes" so that part of the code is never true, hence never executed.
Change your executor to this:
<img src="images/thumbsup.jpg" width="40px"border="0"> <br>Votes: <?php echo file_get_contents('counteru.txt'); ?>
But more logically, your processing code should be rationalized a bit to this:
if the link is clicked :
First, if the data file (lu.txt) does not exist, create it and write '+1' inside of it, else, add 1 to its existing value.
Then, redirects to the initial page.
if($_GET['click'] == 'up1'){
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}else{
$content = file_get_contents('vote/1u.txt');
if(!$content){
die("Error! file_get_content failed !");
}
file_put_contents('vote/1u.txt', ((int)$content) + 1);
}
header('Location: ' . $_SERVER['SCRIPT_NAME']);
}
exit;
Not a bad idea to add a trim() around file_get_contents(). Or to check if $_GET['click'] isset() prior to checking if it's equal to 'up1'.
It's conventional to exit() instead of die() after a header redirect--well, from what I've seen at least.
Basically, during development, turn on error reporting and set your error flag to E_ALL to see everything, including warnings and notices--neither of which halt your code, but should still be known and addressed.
You might discover the reason your code produces different outcomes under different minor versions of PHP by turning on full error reporting.
file1.php and file2.php with die(); function.
include.php:
<? include 'file1.php';
include 'file2.php' ?>
file1.php
<? echo 'included'; die(); ?>
file2.php
<? echo 'not included'; die(); ?>
How can I include both files with die(); function?
Non-English Speakers:
You can provide your question in your native language as well, and somebody here may be able to translate it for you. Just make your best effort to ask in English, and add your native tongue below.
If you would like to test whether the includes happened successfully, you can test the return value of the include function itself:
// http://us3.php.net/manual/en/function.include.php Example #4
if ((include 'file1.php') != 'OK') {
die();
}
You may also consider require() instead of include() depending on your needs:
require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
If I understand correctly what you are trying to do then unfortunately it isn't possible.
die(); will stop the script from executing at the point from where it is called.
Here is how to include a file, or die with a message if the include fails code sample.
(include('file.php')) || die('Failed to include file!');
if (!condition){
include_once('./inc/header.inc.php');
echo "Errormessage";
include_once('./inc/footer.inc.php');
die();
}
I hope this is what you wanted.
Just a minor improvement to LorenzoP's method:
(#include("file.php")) or die("Failed to include!");
// notice the # sign!
This way, you save yourself 2 ugly lines of php warning when inclusion fails. Otherwise I think this is truly the best way to handle failed includes. (Also, his answer should be the accepted one.)
If the execution of your included file is not dependent on the current file (no shared variables, functions, etc.), then use
file_get_contents('link_to_file.php');
instead of an include method. When you force the file to execute independently it will not make a effect in the script execution.
die() is just an exit with an error, you can't include files with it and I don't really understand why you want to. Could you provide more details as to what you're trying to accomplish?