Mysql to PDO code conversion - php

I am fairly new to the PHP scene, and I am trying to solve a bug in a friend's website. However, I have encountered a basic problem when testing it on localhost.
Essentially, the website is old and uses deprecated mysql command. Although mysql queries are spread out through the entire code, I only need to modify a couple of files where the bug is located.
However, in the config.inc file which is used in all php files, the following lines are included :
define("ML",mysql_connect("localhost:/tmp/aaaaa.sock","dbocccccccc","pass"),true);
define ("DB",mysql_select_db("dbcccccccc"));
I am getting a fatal error ad PDOException when converting this to PDO :
define("ML", new PDO('mysql:host=localhost/tmp/aaaaa.sock;dbname = dbcccccccc', 'dbocccccccc','pass'), true);
I'm guessing my syntax is incorrect in some way or another, yet when I try a simple direct connect to the database (same as above, but without the define), I get the following error :
Error : SQLSTATE[HY000] [1045] Acces denied for user 'dbocccccccc'#'#localhost' (password: YES)
The double # is what bugs me here. The input is the same (changed password and database name for privacy, but that's all) as the one found in the website sources.
So, what is the issue ? What have I got wrong here ?

You could try specifying unix_socket=/tmp/aaaa.sock instead of host=.
The PDO documentation describes the options in more detail.

Per the Php ManPage...
new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'user', 'xxx', array( PDO::ATTR_PERSISTENT => false));

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.

PHP Syntax - Connecting to Database

I created a database through an online site and would like to connect to it from my android Activity. I believe that the core issue is my PHP file. I keep getting a syntax error from this line of code:
$con = mysqli_connect('h31.170.234.43', “markf”, “boston”, “a9208078_mydb”);
The name of my file is Register.php and the error is:
Parse error: syntax error, unexpected T_VARIABLE in /home/a9208078/public_html/Register.php on line 2
First, I'm curious if my parameters are correct, Host Name, the username that I used for that site, my password, and the database name?
Does anyone know why this error is occuring? Thanks so much!
PS: I changed the information around from my actual password and database name for obvious security reasons but the idea is the same
You're using funky quotes around three parameter values. That's what happens when you copy and paste your code from a blog post or tutorial.
$con = mysqli_connect('h31.170.234.43', 'markf', 'boston', 'a9208078_mydb');
FYI, your IP address is invalid and probably also a copy and paste error or typo.

PHP with SQLite in TItanium

Hi all am using Titanium studio for Desktop Development in PHP,
when i tried to connect with sqlite3 it shows an error msg as
uncaught exception with message unable to open databasefile
where the code supplied is
$db = new SQLite3('sample.db');
and another trouble is I was unable to acess $_GET, $_POST, and $_REQUEST in php Desktop Development using Titanium
I was pulling my hair with this. Seems like you can use PDO connections for mysql and also use SQLite3 for SQLite. (at least for SKD 1.2.0.RC4 , not sure on any other previous versions)
Check what the phpinfo(); function returns, try to find this string "sqlite3 SQLite3 support => enabled". If you phpinfo returns this, it means you can use the SQLite3 class.
If it does work, take a look here http://www.php.net/manual/en/sqlite3.open.php and let us know how it goes for you. For me this worked just fine and I can open, insert and select without problems. Try to use at first a full path for your db just for testing.
As for the $_GET, $_POST, and $_REQUEST, you are right, they are not available unless you load php pages with get params in the same string ("login.php?user=me&pass=secret"), in that case, the $_GET variable does become available. Not the best way to go but its an option. You can also create a data class and use it for holding and passing data among php pages, during your execution time.
You should use Titanium.Database.open to open db:
var db = Titanium.Database.open("Path to your db");

PHP Fatal error: Call to a member function num_rows() on a non-object

I am working with MySQL in conjunction with ExpressionEngine 2.2.1. This version of ExpressionEngine automatically comes with a Query Module, which I am using to filter and display entry results from a module called Freeform. I am using Freeform version 3.1.1. All of these elements are working well together and displaying the desired results on my local setup. However when I push my code to production, I am receiving this error:
Fatal error: Call to a member function num_rows() on a non-object in /var/www/vhosts/xxxxxxxxx.com/systemxxx/expressionengine/modules/query/mod.query.php on line 183
Here is this section of the code beginning on line 183 of mod.query.php (I did not code this php, nor have I ever coded php, this was already included with the site that I am working on.):
183 if ($query->num_rows() == 0)
184 {
185 return $this->return_data = $this->EE->TMPL->no_results();
186 }
Here is how I am using the Query Module in my HTML Template:
{exp:query sql="SELECT first_name, last_name, email, city FROM exp_freeform_entries WHERE city = 'New York'"}
<tr>
<td>{first_name}</td>
<td>{last_name}</td>
<td>{email}</td>
<td>{city}</td>
</tr>
{/exp:query}
Does anyone know why this error is occurring? Why would it be occurring on production but not locally?
Any help would be greatly appreciated!
Check to make sure the database in Production has the same structure as your Local environment.
Perform the following steps from phpMyAdmin or your favorite MySQL GUI client:
Select your ExpressionEngine database
Execute the following SQL Statements:
DESCRIBE exp_freeform_fields;
SELECT name FROM exp_freeform_fields;
Compare the results from your Local MySQL Database to your Production MySQL Database.
You probably got different database content on production and local systems so the statement fails on the production system producing an error.
You should try executing the statement in phpmyadmin or something like that to see if your sql statement is error-free and doesn't have any conflicts with naming.
Seems that your $query object has no valid connection. Control your username, password and database configuration.
Enable debugging in your config.php and database.php to see detailed error messages:
/system/expressionengine/config/config.php
$config['debug'] = '1';
/system/expressionengine/config/database.php
$db['expressionengine']['db_debug'] = TRUE;
It also wouldn't hurt to:
Verify your MySQL database credentials
Check Apache's and/or PHP's error_log
Hopefully, these steps will allow you to get more insight into your problem.

MySQL/Apache Error in PHP MySQL query

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';

Categories