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
Related
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.
This is first post of a question. Tried to find an answer here, but all relevant posts seems dated or use deprecated mysql.
New to sqlite, so forgive what might appear stupid, but the query in the code below never works. Note: we are running sqlite3 and PDO on site with php 5.6.
A Program to create the db worked fine. And the app "Db Browser for SQL Lite" shows DB and tables and data just fine. But this:
<?php
//open the database
$myPDO = new PDO('sqlite:MySqlitedb1');
print "<p>db opened</p>";
$result = $myPDO->query('SELECT * FROM users');
//if the query works
if ($result !== FALSE) {
print "<p>query ran</p>";
foreach($result as $row){
print "<p>".$row."</p>";
}
} else {
// when the query fails
print "<p>query failed</p>";
} //end if
// close the database connection
$myPDO = NULL;
?>
Always results in a 'query failed'. Queries for specific records that ARE there also fails.
Also Tried some other testing in code above using fetch and fetchall, and they generated errors like:
mod_fcgid: stderr: PHP Fatal error: Call to a member function fetchAll()
on boolean in (path emoved)/testpdo2.php on line 27
Which I am sure was caused by the fact the query fails so $result is null/false
I am obviously missing something stupid here?
Joe C.
This is solved. The code should have worked (it does now). It was not
a directory issue
a permissions issue
a debug_kit.sqlite file in the tmp directory, or any files in the tmp dir.
a SCP or 'sync' directory issue
I altered the code and trapped an exception (1st with 'bad' DB then good one):
<?php
$myPDO = NULL; //close db just in case...
//open the database
$myPDO = new PDO('sqlite:newsqlite2.db');
//throw exceptions
$myPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($myPDO != null)
print "<p>db connected</p>";
else
print "<p>db did not connect</p>";
// result: db does open
//1st test
try
{
$result0=$myPDO->query('SELECT * from users');
print "<p>query ran</p>";
}
catch(PDOException $e)
{
echo "Statement failed: " . $e->getMessage();
return false;
}
// close the database connection
$myPDO = NULL;
?>
This threw an error with the original DB (MySqlitedb1) and an PDO exception:
SQLSTATE[HY000]: General error: 11 database disk image is malformed
Now, DESPITE analyse tools run on the database saying it was 'fine' and being able to work on the database with tools like "DB Browser for SQLite" without ANY issues, nor having issues creating other DB's, SOMETHING was amiss with the file. This caused the query's to fail and always return as a Boolean 'false', so the code failed.
We fixed the DB by dumping it to a sql file, then importing it (with "DB Browser for SQLite") to create a new database (newsqlite2.db), with the data. Using that DB, the code ran fine, extracted data etc.
As to why/how the database became "corrupt" or what the weird corruption was, I have not a clue. :)
Joe C.
In my website I am initializing DB connection using values read from config file, like this:
$this->mysqli = new mysqli($databaseInfo->MySQL_Host, $databaseInfo->MySQL_User, $databaseInfo->MySQL_Pass, $databaseInfo->MySQL_Db);
(for the record, values are being read from file properly and when everything is OK, db connection works just fine)
then I ask whether an error occurred during creating MySQLi object:
if (($this->mysqli!=null)&&($this->mysqli->errno == 0)) {
if no, then I want to set an error variable and handle it later in the code...I want this check only passes when no problem occurred...I thought "errno" variable provides sufficient check...
but apparently not, because regardless any error, I produce in config file, the code still jumps into "everything is fine" branch...obviously PHP produce a lot of warnings and finally it crashes on some fatal error related to the fact database doesn't work as expected
so my question is - how to set up this DB connection initial check properly to avoid such situation?
From PHP Manual, try this:
if (!$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}
If using PHP OOP
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
If using procedural style PHP
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
new here and really green to programming, so go easy..
I discovered I have an INSERT that is failing because of a duplicate record error. I figured it out by running the query in a MySQL console with literals, where err#1062 popped up.
What I want to understand is why mysql_error() or mysql_errno() didn't catch this error in my PHP script.
Below is a generic setup of what I've done. I have a form that submits to a php file that calls data_insert()
function data_insert($var1, $var2, $var3, $var4){
$db = db_connect();
$query = "INSERT INTO exampletable (id, id_2, id_3, id_4)
VALUES ('$var1', '$var2', '$var3', '$var4')";
$result = $db->query($query);
if (!$result)
{
echo ('Database Error:' . mysql_error());
}
else
{
echo "Data added to db";
}
}
The DB connection:
function db_connect()
{
$result = new MySQLi('localhost', 'root', 'root', 'dbname');
if (!$result)
throw new Exception('Could not connect to database server');
else
return $result;
}
Result I'm getting is:
Database Error:
PHP echos "Database Error:" because the INSERT fails, but no subsequent MySQL error info is echoed. Honestly, I'm not exactly sure what I'm supposed to see, but through reading some other SO questions, I've double-checked my php.ini file for error handling and E_ALL and display_errors is set appropriately (although not sure if it matters in this case).
Is there something in my logic that I'm not understanding, like the scope of the link resource mysql_error() takes?
Thanks for your help, I'm hoping this is something embarrassingly obvious.
I know the above is missing XSS and security precautions and uniform exception handling. Baby steps though. It's simplified here for discussion's sake.
You're using mysqli (note the i) for your DB operations, but are calling mysql_error (no i). They're two completely different interfaces, and do not share internal states at at all. DB handles/results from one are not usable in the other.
Try mysqli_error() instead (note the I).
As far as I can tell, you appear to be using the MySQLi class for connecting and queries, but you're trying to access MySQL error message. MySQLi and MySQL aren't the same, so errors in one will not show in the other. You should look up error handling for MySQLi, not MySQL.
You are confusing two seperate methods for connecting to a mySQL DB.
mysql_error() will only work on queries that are run through mysql_query().
As you are using mysqli, you must use mysqli_error()
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"