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.
Related
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
When having an error in SQL syntax in classic PHP mysql, the query will not take place without any other effect. But in mysqli, it will kill the PHP script with Fatal error
mysql_query("SELECT title, misspelled_column FROM posts");
$mysqli->query("SELECT title, misspelled_column FROM posts");
In the first case, it will show the other queries and php output; but the second case kills the script by
Fatal error: Call to a member function fetch_assoc() on a non-object
The problem is related to non-object returned by false query. I can skip this error by
if($result){$row = $result->fetch_assoc();}
but my question is that why I did not need this check in classic mysql? With a more advanced system, one expects new features not missing what we had.
An error generated by MySQL should not be stopping execution. In fact, you can have your script show you any SQL errors by using $mysqli->error (assuming $mysqli is your database connection, like in your example). However, what may be happening is that your mysqli error causes a particular object not to be created, and then calling a method on that object will create a fatal PHP error. For example:
$dbconn = new mysqli("localhost", $username, $password, $dbname);
$stmt = $dbconn->prepare("bluh"); // not a valid statement. fails to create a mysqli statement object in $stmt.
echo($dbconn->error); // your script is still running, and this will show your MySQL syntax error.
$stmt->execute();
This will die not because you made an SQL error, but because $stmt was null and didn't have the expected execute() method. So like everyone else has said, check your logs and see what the actual error is.
Using # to ignore errors is going to be hit-or-miss until you figure out which specific command is creating the error.
update: If you know that the error is in the query, then you could check to see whether the query succeeded before you try to do anything with it. One way is to check the error parameter; another is to check to make sure that it actually returned the kind of object you want.
Here are examples of both:
$result = $db->query("select firstname, lastname from people where firstname = 'egbert';");
if($db->error == '') {
// the query worked, so fetch results from $result and do stuff with them.
}
else {
// the query didn't work, so don't try to do anything with $result
}
// alternately:
if(gettype($result) == "object") {
// the query worked.
}
else {
// it didn't.
}
A SQL error doesn't kill mysqli in my experience. I suspect you actually have a PHP error in the relevant statement. Check your error log.
In PHP, you can use # to suppress errors. It's a bad idea to use it here. But if that's what you really want, it's documented at http://php.net/manual/en/language.operators.errorcontrol.php.
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 have been writing php and mySQL functions all day and as I was writing the simplest part of my project I have hit a wall.
The function should simply count how many entries are in the database and return that number (If there is a more simple way please let me know, this is my first php + mysql project)
Here is the code:
function quoteCount(){
global $db;
$totalQuoteNum = array();
$query = "SELECT * FROM Quotes";
$result_set = mysqli_query($db, $query)
or die ("Query $query failed ".mysqli_error($db)); //fails here
$totalQuoteNum = mysql_num_rows($result_set)
or die ('couldnt count rows'.mysqli_error($db));
echo 'COUNTED EVERYTHING!!!';
return $totalQuoteNum;
};
Now when the die statement prints I get the string but not the mysqli error.
Things I have tried and ruled out:
$db is correct
query works in mysql
I wasnt sure if the database was connected, so I added the connect inside this function and stil nothing.
Any ideas? From what I see it should work and its not giving me any error to work from. Please help!
Based on the comments, it seems as though $db is the database name.
Functions such as mysqli_query() expect a database link (resource), not simply the database name.
This resource is created by constructing a new mysqli object. Following your procedural style, use mysqli_connect().
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"