I have quite some experience with PHP and MySQL, but I have always been working on already set up servers. Now I have my own server (it's actually just a webspace) but it still has all of the standard settings. I have following problems with those:
I set up a connection to my database.
$mysqli = new mysqli("mydatabase", "myuser", "mypw", "mydatabasename");
if ($mysqli->connect_error) {
echo "Error: " . mysqli_connect_error();
exit();
} else {
echo "succesfully connected";
}
Which gives me the output succesfully connected, as you would expect. If I want to do a simple query like this
if ($stmt = $mysqli -> prepare ("SELECT id FROM Users") {
$stmt -> execute();
$stmt -> bind_result($id);
while($stmt -> fetch) {
echo $id;
}
}
I get a blank HTTP ERROR 500. The SQL query works fine in PHPmyAdmin though.
What I did so far is:
Checking the Error log (did not contain any errors)
Trying to add error_reporting(E_ALL);
ini_set('display_errors', 'On'); in front of my script (did not change anything)
Trying to find my php.ini-file to modify (did not find it on the server)
If anyone could help me out and tell me how to get the mysql working, that would be great. Thanks a lot in advance.
Related
I have a PHP web app which has been working fine until today (it is sitting on an Windows/IIS server). When I attempt to access a page which connects to the MYSQL database, I get a blank page in firefox. In IE I get a 500 Internal Server Error. Normal PHP works fine, it is simply when I try to connect to the database. The mysqli connection is not giving any error messages.
The weird thing - I have phpmyadmin on the same server and it is working fine, I can see my database and interact with it.
I also have another database on the server which is working fine, the user attached to that database has read only access (as it is an archive database), but the PHP web app connecting to it works.
What have I tried?
Initially I thought it was a user issue, so I created a new user in phpmyadmin with full privileges and had the PHP app log on using it instead, same result.
I then thought that it was an issue with the database, so I copied the data and structure to a new database, same result.
The MYSQL.err log file has no errors and indicates that the server is accepting connections (which it is, as phpmyadmin is working).
I have even tried writing a test script:
<?php
//Debugging
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
include "settings.php";
echo $HOST . "<br>";
echo $DBNAME . "<br>";
echo $DBUSERNAME . "<br>";
echo $DBPASSWORD . "<br>";
$CON = new mysqli($HOST, $DBUSERNAME, $DBPASSWORD, $DBNAME);
//Check the connection and report error if it failed
if ($CON->connect_errnum > 0)
{
die('Unable to connect to database [' . $CON->connect_error . ']');
}
$result = $CON->query("select user() AS us");
if (!$result)
die("There was an error running the query [" .$CON->error ."]");
}
while($row = $result->fetch_assoc())
{
echo $row["us"] . "<br>";
}
?>
If I don't have he code from the $result = $CON->query("select user() AS us"); down, it displays the 4 values. Once I include it, I get the 500 Internal server error page.
I am at a loss to figure out what is happening or where to start looking.
One of my support classes had a syntax error in it, this caused the page to fail before it got to the database connection. Because my error reporting was turned off, I could not see this (even though I thought it was on). I had to go in to PHP.ini and set display_errors = off to display_errors = on. This then showed the error message.
I've had this problem before, but I can't remember how I got over it. Basically I have a code something like this:
$con = mysqli_connect("localhost", "user", "password", "database");
$grab = mysqli_query($con, "SELECT * FROM Tables;");
while($row = mysqli_fetch_array($grab)){
if($row['BasketId'] == $basketId){
$total = $row['Total'];
}
}
But I keep getting access denied for user # localhost. The problem is that immediately before this php there is another php file with the exact same code and it connects and works fine. Why would this php file be different.
I've checked all the privileges and they are fine. Plus like I said there is an identical piece of code previously that works fine. For some reason this mysql doesn't like this php file. What could be the reason. I'm guessing that mysql is just buggy crap.
Test that you connection attempt has succeeded and if not report the error message, then you will knwo what is wrong.
Its also a good idea to make sure that error reporting is set to show errors on the web page, during development, assuming you are using a live server where error reporting will probably be turned off
Ripped off for the strangest place The PHP Manual
<?php
php error_reporting(E_ALL);
ini_set('display_errors', 1);
$con = mysqli_connect("localhost", "user", "password", "database");
if (!$con ) {
echo 'Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error();
exit;
}
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
I am trying to use the mysqli to access a mysql database and a table called phptest, with the code below. I am trying to check if row is = 0 or something else but it does not echo anything. What is wrong with the code?
$mysqli = new mysqli("localhost", "root", "", "phptest");
if (!$mysqli) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$query = "SELECT `id` FROM `test` WHERE `email`='example#hotmail.com' AND `password`='5f4dcc3b5aa765d61d8327deb882cf99'";
$query_run = $mysqli->query($query);
$row_cnt = $query_run->num_rows;
if ($row_cnt==0) {
echo 'wrong..';
} else {
echo 'correct!';
}
EDIT: edited the variable in the if statement. I have runned the query directly in the mysql panel in the tabel. I get the right row count then. Why doesnt it work in php ?
Although you are checking for an undefined variable $row_count (which should be $row_cnt, that isn't your immediate problem (you should still fix this). You are getting a fatal error either because:
Your query is failing. Your query may be failing because of a missing field on the table or indeed you are missing the actual table in the database. The query will return FALSE if it fails, but you aren't checking for that, instead you try to access a property of the result. If the query fails, there is no result object, it is a boolean FALSE and will produce a fatal error something like Fatal Error: Trying to access a property of a none object.
You don't have the MySQLi library configured for your PHP installation
To further debug you should turn on error reporting as below, or consult your server's error log.
error_reporting(E_ALL);
ini_set('display_errors', '1');
One thing is that you defined $row_cnt and then checked for $row_count, but that's just a quick look at your program, so there might be something else wrong too.
I am looking for a way to test just the connection portion of a php / mysqli connection. I am migrating from a LAMP server build on Vista to the same on Ubuntu and am having fits getting mysqli to work. I know that all of the proper modules are installed, and PhpMyAdmin works flawlessly. I have migrated a site over and none of the mysqli connections are working. The error that I am getting is the "call to member function xxx() on non-object" that usually pops up when either the query itself is bad or the query is prepared from a bad connection. I know that the query itself is good because it works fine on the other server with the exact same database structure and data. That leaves me with the connection. I tried to write a very simple test connection and put it in a loop such as ..
if(***connection here ***) {
echo "connected";
}
else {
echo "not connected";
}
It echoes "connected", which is great. But just to check I changed the password in the connection so that I knew it would not be able to connect and it still echoed "connected". So, the if / else test is clearly not the way to go....
mysqli_connect() always returns a MySQLi object. To check for connection errors, use:
$mysqli_connection = new MySQLi('localhost', 'user', 'pass', 'db');
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
echo "Connected.";
}
For test php connection in you terminal execute:
$ php -r 'var_dump(mysqli_connect("localhost:/tmp/mysql.sock", "MYSQL_USER", "MYSQL_PASS",
"DBNAME));'
You need more error handling on the various database calls, then. Quick/dirty method is to simply do
$whatever = mysqli_somefunction(...) or die("MySQL error: ". mysqli_error());
All of the functions return boolean FALSE if an error occured, or an appropriate mysqli object with the results. Without the error checking, you'd be doing:
$result = $mysqli->query("blah blah will cause a syntax error");
$data = $result->fetchRow(); // $result is "FALSE", not a mysqli_object, hence the "call to member on non-object"