MySQL/Apache Error in PHP MySQL query - php

I am getting the following error:
Access denied for user 'apache'#'localhost' (using password: NO)
When using the following code:
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right">Delete</span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if.
I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.

And if it matters at all, apache#localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
If it is saying 'apache#localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.
If you do the connection right in your script, not in a called file, do you get the same error?

Change the include() to require(). If the "connect.php" file can't be require()d, the script will fail with a fatal error, whereas include() only generates a warning. If the username you're passing to mysql_connect() isn't "apache", an incorrect path to the connect script is the most common way to get this type of error.

Don't forget to check your database error logs. You should be able to see if you are even hitting the DB. If you aren't, you should check your firewall rules on the box. On a linux box you can run iptables -L to get the firewall list rules.
Otherwise it will be a pure access issue. Do a "select * from mysql.user" to see if the apache user is even set up in there. Further, I would recommend creating an account specifically for your app as opposed to using apache, since any other app you create will run as apache by default, and could get unauthorized access to your db.
Just look up "GRANT" in the documentation # dev.mysql.com to get more info. If you have more specific questiosn regarding db, just edit your question, and i will take a look.

Does the connect.php script actually make the connection or does it just define a function you need to call to create a connection? The error you're getting is symptomatic of not having a previously established connection at all.
ETA: Also change the include to a require. I suspect it's not actually including the file at all. But include can fail silently.

Dude the answer is a big DUH! which unfortunately it took me a while to figure out as well. You probably have a function like dbconnect() and you are using variables from an include file to make the connection. $conn = mysql_connect($dbhost, $dbuser, $dbpass).
Well since this is inside a function the variables from the include file need to be passed to the function or else the function will not know what $dbhost, $dbuser and $dbpass is. A way to fix this is to make those variables global so your functions can pick them up. Another solution which is not very secure would be to write out you host, user and pass in the mysql_connect function.
Hope this helps but I had the same problem.

Did you remember to do:
flush privileges;
If the user is not set up then it will give the 'apache'#'localhost' error.

Just to check, if you use just this part you get an error?
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
If so, do you still get an error if you copy and paste one of those Inserts into this page, I am trying to see if it's local to the page or that actual line.
Also, can you post a copy of the connection calls (minus passwords), unless the inserts use exactly the same syntax as this example.

Just to check, if you use just this part you get an error?
If so, do you still get an error if you copy and paste one of those Inserts into this >page, I am trying to see if it's local to the page or that actual line.
Also, can you post a copy of the connection calls (minus passwords), unless the inserts >use exactly the same syntax as this example.
Here is what is in the connection.php file. I linked to the file through an include in the same fashion as where I execute the INSERT queries elsewhere in the code.
$conn = mysql_connect("localhost", ******, ******) or die("Could not connect");
mysql_select_db("adbay_com_-_cms") or die("Could not select database");
I will try the working INSERT query in this area to check that out.
As to the others posting about the password access. I did, as stated in my first posting, check permissions. I used phpMyAdmin to verify that the permissions for the user account I was using were correct. And if it matters at all, apache#localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.

You can do one of the following:
Add the user "apache" and setup its privileges from phpmyadmin or using mysql on a shell
Tell php to run mysql_connect as another user, someone who already has the privileges needed (but maybe not root), look for mysql.default_user in your php.ini file.

Does the apache user require a password to connect to the database? If so, then the fact that it says "using password: NO" would lead me to believe that the code is trying to connect without a password.
If, however, the apache user doesn't require a password, a double-check of the permissions may be a good idea (which you mentioned you already checked). It may still be beneficial to try executing something like this at a mysql prompt:
GRANT ALL PRIVILEGES ON `*databasename*`.* to 'apache'#'localhost';
That syntax should be correct.
Other than that, I'm just as stumped as you are.

If indeed you are able to insert using the same connection calls, your problem most likely lies in the user "apache" not having SELECT permissions on the database. If you have phpMyAdmin installed you can look at the permissions for the user in the Privileges pane. phpMyAdmin also makes it very easy to modify the permissions.
If you only have access to the command line, you can check the permissions from the mysql database.
You'll probably need to do something like:
GRANT SELECT ON myDatabase.myTable TO 'apache'#'localhost';

Related

Database connection script works in PHP 5.3 but not in 5.5

I have developed a web based member management tool for my sailing club few years ago and used some free script (a class) that handles database connection and operations on database. The class (connection.php) is invoked by the following code in a required file "settings.php":
$db = new db ( DBUSER, DBPASS, DATABASE, HOSTNAME );
and then is used throughout the site for handling database related requests. It is working fine in PHP 5.3 but due to some security concerns the site has to be upgraded to min 5.4. Unfortunately the script in PHP 5.4 fails to connect to database. I will include the script below (for brevity I show only couple of functions in the class that should give the idea):
// ==================================================================
// The Main Class
class db {
// ==================================================================
// DB Constructor - connects to the server and selects a database
function db($dbuser, $dbpassword, $dbname, $dbhost)
{
$this->dbh = #mysql_connect($dbhost,$dbuser,$dbpassword);
if ( ! $this->dbh )
{
$this->print_error("<ol><b>Error establishing a database connection!</b><li>Are you sure you have the correct user/password?<li>Are you sure that you have typed the correct hostname?<li>Are you sure that the database server is running?</ol>");
}
$this->select($dbname);
}
// ==================================================================
// Select a DB (if another one needs to be selected)
function select($db)
{
if ( !#mysql_select_db($db,$this->dbh))
{
$this->print_error("<ol><b>Error selecting database <u>$db</u>!</b><li>Are you sure it exists?<li>Are you sure there is a valid database connection?</ol>");
}
}
When trying to display a page in PHP 5.4 I get the following output:
dbh = #mysql_connect($dbhost,$dbuser,$dbpassword); if ( ! $this->dbh ) { $this->print_error("
Error establishing a database connection!
Are you sure you have the correct user/password?
Are you sure that you have typed the correct hostname?
Are you sure that the database server is running?
"); } $this->select($dbname); } // ================================================================== // Select a DB (if another one needs to be selected) function select($db) { if ( !#mysql_select_db($db,$this->dbh)) { $this->print_error("
Error selecting database $db!
Are you sure it exists?he rest of the pages
Are you sure there is a valid database connection?
My aim is to rewrite the class db without touching the rest of the pages.
I was trying to use mysqli instead of mysql but that made no difference. I'm using mainly procedural php in my programming and am not to good with object oriented.
My question is: what approach should I take to solve my problem. Could you put me in some direction...
This function appears to be deprecated as of PHP 5.5
http://php.net/manual/en/function.mysql-connect.php
If you have access to the php.ini file after the upgrade to 5.4 I would check to make sure the extension you are trying to use is unchecked in the windows extensions settings. If you pay for hosting, their tech support may be able to help if you have a lot of patience.
Thanks everybody for your contributions.
I've identified a simple (but major) problem with file connection.php containing Class db. It was using short version of php identifier: <? rather than <?php, which was causing fatal error of not finding the Class.
With this out of the way I am back to my original issue of deprecated functions not working correctly in php 5.5 but need to do more research before (eventually) asking another question.
Thanks again.
#Qchmqs Jan 8 at 7:28
you should be using PDO anyway
No!
You should be using PDO OR MySQLi
Balance please! there are plenty of well learned folk who advocate MySQLi for some situations, its a matter of judgement etc.

If ldap_connect fails, variable assigned to it should be false?

I have a website that uses LDAP authentication. I have two active directory servers for redundancy. If the primary server is down, authentication should be handled by the back-up server. I tried using the following to achieve this:
$LDAP_SERVER = "10.100.10.1";
$LDAP_SERVER_BACKUP = "10.100.10.2";
$ldap_mycorp = ldap_connect($LDAP_SERVER);
if(!$ldap_mycorp){
$ldap_mycorp = ldap_connect($LDAP_SERVER_BACKUP);
}
But I noticed that if the connection to the primary server failed, 'ldap_connect($LDAP_SERVER)' returns a resource id instead of false, which means the if statement is never used.
I came up with a workaround for this by adding some additional code later in the script, but there must be a solution to handle the problem within the above context?
The host name parameter can be a space separated list of host names. This means that the LDAP code will talk to a backup server if the main server is not operational. There will be a delay while the code times out trying to talk to the main server but things will still work.
$LDAP_SERVERS = "10.100.10.1 10.100.10.2";
$ldap_mycorp = ldap_connect($LDAP_SERVERS);
Is this what you are looking for?
http://php.net/manual/en/function.ldap-error.php
I have no idea what it returns when there is no error, but it should give you a step in the right direction. With the answer given to connect automatically to multiple servers if the previous failed, you should still check if the connection didn't have any errors ;)

Source a MySQL file through PHP?

how do I source a .sql file, like the one below, through php?
CREATE DATABASE IF NOT EXISTS data_base;
USE data_base;
CREATE TABLE IF NOT EXISTS the_table(
package_name varchar(50) NOT NULL,
PRIMARY KEY (`package_name`)
)
I tried the following, but it doesn't work. I've tried to do some research and it seems I need to do something called LOAD DATA INFILE, but I don't understand it.
mysql_query("source C:/xampp/htdocs/Project1/mysql/source.sql;") or die(mysql_error());
How can I source an .sql file using PHP? Thanks.
You cannot just run an SQL script, even with mysqli::multi_query(). An SQL script can contain some commands that are recognized as builtin commands only by the mysql client, not by the MySQL server's SQL parser.
SOURCE is definitely a command that is preprocessed by the mysql client. The server does not understand that command. So you can't execute SOURCE on the server using the query API.
If you can restrict the content of your SQL script to exclude mysql client builtin commands, it might work to use mysqli::multi_query(). But it won't work for the full set of commands that are allowed in an SQL script.
See also my answer to Running MySQL *.sql files in PHP
LOAD DATA INFILE does not execute SQL statements to create tables, it just loads fields of a text file into an existing table.
You're mixing mysql command line statements with PHP functional calls. Do one or the other.
Utilize the mysql CLI (if available):
// executing mysql cli
exec("mysql < test.sql");
Or run the SQL with mysqli_multi_query():
// running the files contents in bulk
$sql= file_get_contents('test.sql');
mysqli_multi_query($sql);
Note: This is a potential security risk. Be advised.
Okay, this is a really old one I just stumbled across but I don't see anybody mention what I've always had work for me --NOTE I didn't look this up, just thought about it and it worked so I've used it for years, may not be the most secure way.
If the queries are already in a .sql file, I have always just read that in as a text file and passed it one line at a time with the fgets() function in php.
For example if this is in the .sql file.
CREATE DATABASE Testing123;
USE Testing123;
CREATE TABLE testData(name VARCHAR(32), age INT, town VARCHAR(32));
INSERT INTO testData(name, age, town) VALUES('Chris', 42, 'Clarksville');
Then uploading that from a webpage with this html form:
<form method="POST" action="import_sql_file.php" enctype="multipart/form-data">
<p><input type="file" name="data"/></p>
<p><input type="submit" value="Import"/></p>
</form>
The import_sql_file.php script I have always used to get it into the database looks like:
<?php
$file = $_FILES['data']['tmp_name'];
$db = new mysqli("localhost", "root", "");
$fromFile = fopen($file, "r");
while(!feof($fromFile)){
$query = fgets($fromFile);
$db->query($query);
}
$db->close();
?>
Using SOURCE $_FILES['data']['tmp_name'] failed on first thought I tried, then this thought worked on the second try so I never really looked into a more direct way to do it with SQL commands.

Problem with PHP mysql_real_escape_string

When I run mysql_real_escape_string , for example like this:
$test = mysql_real_escape_string($_POST['test']);
it's not working on local server, it gives me an error page!
my local server is "AppServ".
my operating systim is "windows XP".
Is this normal ? and just i have to run it on hosted site only !
You have to provide the function an active database connection. I think it's the second argument:
$test = mysql_real_escape_string($_POST['test'], $mysql_database_connection);
That might be your error, because if you don't provide an active connection explicitly, the function looks for the last one which was created. If you run this function before connecting to the database, it'll give you an error.
We'd need to know which error before we could help you any more, but the most common error that I get when using mysql_real_escape_string is when I forget that it takes a second parameter.
This tells the function which character set you need escaping. You just need to pass the database resource ID.

SQL debugging in large PHP app

I am using CodeCharge Studio to finish a large PHP application. This question isn't really CCS related, but a bit more general. I have a web form that is supposed to allow CRUD capabilities with a certain SQL Server table, but the Inserts keep failing without throwing any errors. What would be the best way to debug this?
When I'm having trouble with dynamically generated SQL queries, I typically echo out the query and try running that query on the console for the DB. Or alternatively, you could write a simple PHP function that writes out strings to a file, and that way you don't have to display the query directly on your page, but instead in a log file.
See what the actually query is and then try doing that query directly on the DB. Then you know whether it's a PHP issue or a DB issue.
Then go from there, depending on the outcome.
If the query looks OK, double check that the user running the query has insert rights to the database.
I've been caught out by that before.
You can monitor all sql queries in mysql as shown in this site, once you enable logging, run the query manually and see why its failing..this should be good starting point.
In addition to what's mentioned before, I can add my recent discovery:
trigger_error(print_r($your_var,1),E_USER_ERROR);
So you can output and debug your variable, even if it's a complex script with redirects, where simple echo would not help.
Dmitri.
You should try using FirePHP and log all the SQL to your Firebug:
An Example would be:
$sql = "SELECT * FROM table"
if (!mysql_query($sql)) {
// In un successfull log to FireBug
FB::error($data, "SQL error: ".mysql_error());
}
You can also implement the FB::error call from your own function, so you can later deactivate this behaviour modifying your function:
function log_error($data, $msg){
//dont forget to deactivate in case the application goes live!
FB::error($data, $msg);
}
if (!mysql_query($sql)) {
// In un successfull log to FireBug
log_error($data, "SQL error: ".mysql_error());
}
Most of the database connection classes in CodeCharge have a 'debug' flag which will automatically write all the page's database commands at the top of the page.
For example, in an old PHP project of mine, 'Common Files' the file 'db_mysql.php' (line 27):
public $Debug = 0; ## Set to 1 for debugging messages.
Change to '1' and publish that file. Load the web page. Change back and re-publish when done.
I've used this in CCS for PHP and ASP projects, and is likely in the other languages (not sure if or where to find in .NET projects).

Categories