What Am I Missing in this Connection? - php

I'm trying to establish a PHP (5.2.6)/MySQL connection via mysqli.
error_log( sprintf( 'Querying %s:%s (%s) as %s/%s', DBHOST, DBPORT, DBNAME, DBUSER, DBPASSWORD ) );
$mysqli = #new mysqli( DBHOST, DBUSER, DBPASSWORD, DBNAME, DBPORT );
if( !$mysqli ) {
error_log( 'Unable to establish a connection to ' . DBHOST . '.' . DBNAME . ': ' . mysqli_connect_error() );
exit( 'Unable to connect to the db.' );
}
else {
error_log( '--> mysqli connection established' );
}
... more stuff ...
The result of this code is that the initial write to error_log happens (which validates that the constants are defined properly), but nothing else. Nothing. Everything just stops as far as I can tell. No unable to connect message, no connection established message. Just nothing. I can connect to MySQL directly using the parameters defined by the constants (copied and pasted from the log print).
I've read about the bug in versions of PHP prior to 5.2.9 and I've tried various ways of detecting an error, but there are no changes. Everything just stops and I'm starting to lose my mind trying to figure out what else I can do.
Has anyone ever seen this? MySQLi does seem to be installed--validated by its presence in the output of phpinfo() and by a test for function_exists( mysqli_connect ). Am I missing something obvious because I'm too focused on the details?
Any thoughts would be appreciated.
UPDATE
When I said, "I've tried various ways of detecting an error", I should have been more clear. No other variant included silencing output with the "#". Please don't focus on that. That was only included in my last attempt based on something read in the PHP docs.

So first, an apology. I'm working in an unfamiliar environment and didn't know that error logging was turned off. I turned that on via ini_set( 'log_errors', true ) and started getting the information that I need. I leave this just in case anyone else has a need to search the same problem.

Related

PHP mysqli acting really screwy

I am attempting to use PHP to connect to a database for the first time. I found an online tutorial that was teaching me how to use mysqli to do this. It talked about mysqli_connect($host, $name, $pass, $db) and that worked just fine. The problem was when the tutorial asked me to check for errors using the function mysqli_connect_errno() because apparently whatever version of PHP I am running doesn't recognize that function. But according to the internets, im the only weirdo who's copy of PHP is having this issue. Why can't my PHP recgonize mysqli_connect_errno()? (Note: I am running wampserver on a Windows 8.1 desktop and PHP version is 5.5.12) (UPDATE: the actual username is supossed to be "web")
Here is my PHP Code:
<?php
$sql = mysqli_connect("localhost", "sweb", "nsjk99", "Inventory");
if( mysqli_connect_errno() ) {
die("Database connection failed: " . mysqli_connect_error() . "( " . mysqli_connect_errorno() . ")");
} else {
echo "<p>Your connection was a success</p>";
}
?>
Result:
The function is called mysqli_connect_errno() and not mysqli_connect_errorno(), as you have on line 4.
Edit
You don't need to pass the connection link as a parameter as stated in the manual.
The function catches the error number from the last call to mysqli_connect().
Thanks to David Rosa for the warning.

PHP - Error handling while querying mysql

I am new to web development, so probably there is something I am doing it wrong.
I am using webmatrix for development and playing around with StarterSite sample that webmatrix provides.
In one of the php file (header.php) there is a query to mysql using mysqli extension. I have changed the tablename to some non existent table to simulate error condition. The problem is, after below statement -
$statement->execute();
the script stops.
I inserted a echo statement after execute and that echo string is not displaying on webpage. However when I correct the table name, the echo string after execute is displayed on webpage. So I think the script stops executing after execute when the table name is wrong. I have two questions. How do I stop script from stop executing like this? Secondly How to know for sure that script has stopped executing at some particular statement?
For second part of question, I checked the log file and tracelog file in IISExpress folder. There is no mention of any error, probably because error happened in MYSQL. However, in my MYSQL folder there is no log file, so not sure how to check mysql log.
If I have missed anything, please let me know.
Regards,
Tushar
You should read about mysqli error handling.
Basic error handling example OOP:
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Procedural:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
It depends on what you're logging. In the error log you can define what's being logged. I think you can control the strict mode of the error in the php.ini which will automatically throw error into the access_log or error_log or apache log file.
The trick is to use $mysqli->error in every step of the mysqli querying and db connects to ensure you're getting proper error messages in detail whether to debug, improve the code or to do it correctly.
Here is an example of using $mysqli->error in querying the database.
$result = $mysqli->query($query);
if (!$result and $mysqliDebug) {
// the query failed and debugging is enabled
echo "<p>There was an error in query: $query</p>";
echo $mysqli->error; //additional error
}
You can also use a method where you define mysql error to be true in db conn
// define a variable to switch on/off error messages
$mysqliDebug = true;
// connect to your database
// if you use a single database, passing it will simplify your queries
$mysqli = #new mysqli('localhost', 'myuser', 'mypassword', 'mydatabase');
// mysqli->connect_errno will return zero if successful
if ($mysqli->connect_errno) {
echo '<p>There was an error connecting to the database!</p>';
if ($mysqliDebug) {
// mysqli->connect_error returns the latest error message,
// hopefully clarifying the problem
// NOTE: supported as of PHP 5.2.9
echo $mysqli->connect_error;
}
// since there is no database connection your queries will fail,
// quit processing
die();
}
#ref: https://www.daniweb.com/web-development/php/code/434480/using-phpmysqli-with-error-checking

PHP PDO: Unable to connect, Invalid catalog name

I am trying to set up a new site on my hosting (Host route if it matters) but i keep getting this error when i try using PDO (first PDO site im trying):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /home/kennyi81/public_html/gamersite/login.php:36 Stack trace: #0 /home/kennyi81/public_html/gamersite/login.php(36): PDOStatement->execute() #1 {main} thrown in /home/kennyi81/public_html/gamersite/login.php on line 36
When i use these settings:
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
....
$stmt = $dbh->prepare('SELECT * FROM USERS WHERE ID = :id LIMIT 1');
How the database is laid out:
I am able to use mysqli connect fine on my other sub domains / main site, but i just cannot get PDO to work.
I've tried this, which i have seen around:
$stmt = $dbh->prepare('SELECT * FROM gamersite.USERS WHERE ID = :id LIMIT 1');
but it retuns a syntax error.
Anyone have any idea what may be causing this?
This is all working on my local server, nothing changed on upload apart from connect line.
Instead of:
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
Try:
$dbh = new PDO("mysql:host=91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
(add host=)
And it most likely works on your local server, because you have mysql:localhost... or mysql:127.0.0.1... there and it's ignored (cause it's missing host= aswell) and by default it's localhost.
From the PDO manual page, you can see that you need to wrap the connection in a try/catch block. This way if something goes wrong with the connection, it will tell you. Something like this:
try {
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
// Then actually do something about the error
logError($e->getMessage(), __FILE__, __LINE__);
emailErrorToAdmin($e->getMessage(), __FILE__, __LINE__);
// etc.
die(); // Comment this out if you want the script to continue execution
}
The reason you are getting this error is because there is an error with your connection, but since you don't tell your script to stop, it doesn't. Look at the error message produced, and how to fix it should be made obvious. It appears that Michael Prajsnar's answer is correct in that you aren't setting a "host".
Edit:
As it turns out, PDO doesn't complain if you leave out your host or dbname in the PDO connection DSN part (at least on Unix). I tested it and leaving it blank will default it to "localhost" and I was therefore able to connect perfectly fine leaving this out completely for localhost connections, which would explain why it worked on your local server but not on your production server. In fact, it is completely possible to connect supplying absolutely nothing in the DSN except for the database engine like this:
$dbh = new PDO("mysql:", "kennyi81_gamer", "***************");
The only problem is that it won't be using a database, so to USE a database, just do:
if ($dbh->query("USE kennyi81_gamersite") === false)) {
// Handle the error
}
However with that said, I have my doubts that you actually tried connecting using a try/catch block (as you mention in your comments) unless you somehow provided valid database credentials. The ONLY way that doing it this way did not produce any sort of error is if you actually connected correctly and selected the database kennyi81_gamersite. If not, you would have seen a message like this:
Unable to connect to database. "mysql" said: SQLSTATE[28000] [1045]
Access denied for user 'kennyi81_gamer'#'localhost' (using password: YES)
In summary, always wrap your connection in a try/catch block if you want to find errors during connection. Just make sure not to re-throw (and not catch) the PDOException's getMessage() or you could expose your login credentials.

The mysqli_connect not working

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

Call to undefined function query() - using PDO in PHP

I have a written a script in PHP that reads from data from a MySQL database. I am new to PHP and I have been using the PDO library. I have been developing on a Windows machine using the WAMP Server 2 and all has been working well. However, when I uploaded my script to the LINUX server where it will be used I get the following error when I run my script.
Fatal error: Call to undefined function query()
This is the line where the error is occuring ...
foreach($dbconn->query($sql) as $row)
The variable $dbconn is first defined in my dblogin.php include file which I am listing below.
<?php
// Login info for the database
$db_hostname = 'localhost';
$db_database = 'MY_DATABASE_NAME';
$db_username = 'MY_DATABASE_USER';
$db_password = 'MY_DATABASE_PASSWORD';
$dsn = 'mysql:host=' . $db_hostname . ';dbname=' . $db_database . ';';
try
{
$dbconn = new PDO($dsn, $db_username, $db_password);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Error connecting to database: ' . $e->getMessage();
}
?>
Inside the function where the error occurs I have the database connection defined as a superglobal as such ...
global $dbconn;
I am a bit confused as to what is happening since all worked well on my development machine. I was wondering if the PDO library was installed but from what I thought it was installed by default as part of PHP v5.
The script is running on an Ubuntu (5.0.51a-3ubuntu5.4) machine and the PHP version is 5.2.4. Thank you for any suggestions. I am really lost on this.
Always, but always, develop on the same platform as your production platform. Try your best to mirror the versions of server software (PHP, MySQL, etc). There will always be differences between installs, and especially in the way different OS platforms handle things. Use the old 'phpinfo()' script on each server to compare the differences, if any.
At any rate, even if both the Win and Linux platforms here have the exact same versions of everything, have you checked your configuration? In other words, is the MySQL host name in your DSN a local MySQL host (linked to your Win development platform), or the actual host the Ubuntu server uses? Or are they both "localhost" in either case? Double check this. Also, have you mirrored all data on both servers?
Do you know for a fact that the Ubuntu server has PDO? You essentially said you assume they are the same. Don't assume, verify.
As sobedai mentioned, look at the output of var_dump($dbconn), check that it is actually a PDO object, and go from there.
This is a typical PDO deployment for me:
// 'logger' is a custom error logging function with email alerts
try {
$dbh= new PDO(dsn);
if ( is_a($dbh, "PDO") ) {
$sql= 'SELECT field FROM table';
$stmt= $dbh->query($sql);
if ( is_a($stmt, "PDOStatement") ) {
// handle resultset
}
else {
// weirdness, log it
logger("Error with statement: {$sql}" .$dbh->errorCode());
}
}
else {
// some weirdness, log it
logger('Error making connection: '. $dbh->errorCode());
}
}
catch (PDOException $e) {
logger('PDOException caught in '.__FILE__.' : '. $e->getMessage());
}
catch (Exception $e) {
logger('General Exception caught in '.__FILE__.' : '. $e->getMessage());
}
Note I'm using PDO::errorCode in there, referencing the SQL-92 state codes.
Also, refer to the manual as much as possible.
Generally when this happens, the object you're trying to reference is not actually an instance of a class.
Since you've been developing on WAMP and testing on LAMP, include paths immediately come to mind.
Check the php includes path is correct on your LAMP stack.
Check that all the necessary libs are installed (just do a quick phpinfo() page or you can use php -i from the command line).
And last but not least - do:
echo var_dump($dbconn);
confirm that it is indeed the object you think it is.

Categories