PHP Include another php that queries MySQL - php

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>

#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);

First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

Related

Why are html and php files not properly exchanging information?

I am creating a website where a user logs in, enters information that is submitted to a database, and then can call information from the database that will be inserted into an html text element. I have separate html files for each website page, and multiple php files. They are all contained and linked properly on the same server, under the same FTP account. EDIT: THIS WAS MY PROBLEM. I HAD SEPARATE PHP AND HTML FILES. ONCE I COMBINED THEM, I NO LONGER NEEDED THE JAVASCRIPT AND EVERYTHING WORKED FINE. My code has been checked by multiple sources, and I can have the user correctly input information into the database. When it comes to retrieving the information to be displayed on client-side, however, the php will not change the html via javascript.
I am currently using 000webhost.com, but I tried plugging the files into dreamweaver and the files still aren't communicating properly. I'm wondering whether this is a software limitation (aka something is going wrong with 000webhost.com) or if there is a key piece of info I am missing, such as a command that will link the files together.
Here is the example php and html for one of the retrieve information functions:
$servername = "localhost";
$username = "-";
$password = "-";
$database = "-";
$link = mysqli_connect($servername, $username, $password, $database);
if (!$link) {
die(mysqli_error());
}
$sql = "SELECT UserClassName FROM UserInfo1 WHERE UserEmail = '". mysqli_real_escape_string($link, $_SESSION['useremail']) . "'";
if (!$sql) {
die(mysqli_error());
}
$result = mysqli_query($link, $sql);
if (!$result) {
die(mysqli_error());
}
?>
<script>
function getclassname() {
return document.getElementById("UserClassName").innerHTML = "<?php echo
$result ?>";
}
</script>
<html>
<body onload="getclassname(); getcurrentlevel();">
<h1 class="text-center" id="UserClassName" name="UserClassName"><b>Welcome Enviroquest Research Team!</b></h1>
</body>
</html>
I think the only problem is that you put the javascript code outside the html. It should be placed before the closing body tag.
This is what your html should look like :
<?php // your php code here ?>
<html>
<body onload="getclassname(); getcurrentlevel();">
<h1 class="text-center" id="UserClassName" name="UserClassName"><b>Welcome Enviroquest Research Team!</b></h1>
<script>
function getclassname() {
document.getElementById("UserClassName").innerHTML = "<?php echo $result; ?>";
}
function getcurrentlevel() {
// this function should be remove if not used
}
</script>
</body>
</html>

Broken PHP web app (w/ Bluemix) - MySQLi stops script

I'm building a simple PHP webservice/webapp that when queried from an external application will return JSON formatted/encoded data from a MySQL database.
The PHP webapp and MySQL database are on Bluemix (and MUST to stay there).
Here is my current code for a typical PHP page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = new mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>
I have put in the <p>1 Inside of PHP<p> stuff in there so I could see where the script stopped and therefore figure out why.
The last thing that gets echo'd to the screen is <p>1 Inside of php</p> so therefore we can assume it's the MySQLi functions not working.
After some googling, I found that the main reason for this was that the MySQLi extension hasn't been included in the installation/build of the PHP webapp.
I am using this buildpack:
https://github.com/cloudfoundry/php-buildpack.git
which allows for use of a .bp-config/options.json file to include any extensions not included in the build pack.
As MySQLi is not included in the buildpack. My .bp-config/options.json file shows as follows:
{
"PHP_EXTENSIONS": ["mysqli"]
}
Now that MySQLi is included, I threw a phpinfo(); in my PHP before the MySQLi function, just to double check, and it displayed all the PHP information WITH a section titled: MySQLi.
Just to point out, the MySQLi section wasn't there before I wrote the .bp-config/options.json file.
However, the script STILL stops at the first MySQLi function and won't display anything after that. I'm stumped. Is it Bluemix's fault? Is it my PHP? Do I need to do something else before MySQLi is properly installed? I don't know, Help?
Your PHP is a little wrong on the line with mysqli_connect.
It should be $mysqli = mysqli_connect($server, $username, $password, $database);. Notice the reference to new is not used.
mysqli_connect is a function, not a class. What you want is either:
$mysqli = mysqli_connect(...);
or
$mysqli = new mysqli(...);
Both are equivalent.
Additionally the use of MYSQL_ASSOC should be MYSQLI_ASSOC.
Here is a full replacement of your code below.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>

Page source reveals part of my page isn't displaying

I'm working on a friend's project and I'm in charge of designing a simple website to interface with his databases. I have written the following code for one of his pages:
<!DOCTYPE html>
<html>
<head>
<title>Narcissus-OTS</title>
<meta charset="utf-8" />
<!--<meta http-equiv="refresh" content="3;url=./account.php" />-->
</head>
<body>
<?php include("./common/database.php"); ?>
<?php
//Grabs user-submitted credentials from previous page
$accountid = mysql_escape_string($_POST["acc"]);
$password = mysql_escape_string($_POST["pass"]);
$confirmation = mysql_escape_string($_POST["passtwo"]);
//Insures there is no duplicate database entry for accountid
$querycheck = $db->query("
SELECT *
FROM accounts a
WHERE a.name = $accountid
");
$checkifone = $querycheck->rowCount();
//If no duplicate entry...
if ($checkifone == 1) {
echo "There is already an account with that name; please choose a different account number.";
} else {
//Confirms if passwords match
if ($password == $confirmation) {
$passhash = sha1($password);
$database = $db->query("
INSERT INTO accounts
VALUES (NULL , '$accountid', '$passhash', '65535', '0', '', '1', '0', '0', '1');
");
echo "Your account has been successfully created.";
//If passwords do not match
} else {
echo "Your passwords did not match, please try again.";
}
}
?>
</body>
</html>
When I load the page and view page source, it doesn't seem to show terminating </body> or terminating </html> tags. I've traced my code and can't see any missing semi-colons or parentheses. For the life of me I can't figure this one out. It displays the terminating tags properly only when the passwords do not match (the bottom-most nested else statement).
edit; and before anyone says it, I know mysql_escape_string is deprecated.
edit2; database.php looks like...
<?php
$SERVER = "localhost";
$USERNAME = "redacted";
$PASSWORD = "redacted";
$DATABASE = "redacted";
$db = new PDO("mysql:dbname={$DATABASE}; host={$SERVER}", $USERNAME, $PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
?>
Your best bet to solve this problem and any other occurrences like this in the future is to tail your server log and determine what exactly the issue is.
For apache2:
tail -f /var/log/apache2/error.log
For nginx:
tail -f /var/log/nginx/error.log

PHP code included in HTML won't update

I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.

PHP seems to be refusing to connect to MySQL

<?php
function redirect_to_index_with_error(){
echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
function go_to_home(){
echo '<meta http-equiv="refresh" content="0;url=home.php">';
}
$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";
mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing
mysql_select_db("mcp") or die(mysql_error());
$results = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($results) == 0){
redirect_to_index_with_error();
exit();
}
$userID = null;
$name = null;
$school = null;
$mod = null;
while($user = mysql_fetch_array($results)){
$userID = $user['ID'];
$name = $user['Name'];
$school = $user['School'];
if($user['Mod'] == '1')
$mod = true;
else
$mod = false;
}
if(!isset($_SESSION))
session_start();
//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;
go_to_home();
exit();
?>
PHP echos everything up until "connected". It's not even showing a mysql error. I've had this code work flawlessly on Windows with WAMP, but not on Mac with MAMP. I've verified that the servers are running, so I can't tell what the problem is. I'm using PHP 5.3.6.
Your connection needs to be established before you call mysql_real_escape_string()
So move mysql_connect("localhost","root","") or die(mysql_error()); to the top.
Move the mysql_connect() statement above everything else.
// put this at the TOP
mysql_connect("localhost:3306","root","") or die(mysql_error());
Just as everyone else mentioned, see this note:
http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes
Also, you should see errors, in development, at least.
See: error_reporting()
you have to call mysql_real_escape_string() after connect.
otherwise this function returns an empty string and your query fails.
though it raises an error but it seems you haven't seen that.
So, you ought to either turn displaying errors on or peek error logs - it's impossible to program without ability to see error messages
Also, you have to improve your formal logic.
To make a statement like "PHP seems to be refusing to connect to MySQL" youi have to verify it first. Connect is just a single line and returns a value.
You can verify this value and make a certain conclusion.
But running whole code of several dozens of lines and making statements about just one makes no sense.

Categories