Warnings from mysql_connect() not populating mysql_error() - php

Environment - PHP5.2.17, MySQL5.0.92
I am implementing an error logging framework in my application and I am trying to log errors and warnings to a database.
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log(mysql_error());
}
...continue code
I wanted to test the logging and passed the wrong host to the mysql_connect function. As expected I got the warning on screen
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'host' (1) in /path/to/my/php/file.php on line 4
And my log function was called but mysql_error() is null. According to the php manual (http://php.net/manual/en/function.mysql-connect.php), mysql_error() should return the last mysql error. In the manual they even have an example of how to echo the error to the screen using mysql_error().
I tried using mysql_error($db), but it returns an error stating that $db is not defined.
I tried replacing my function with echo mysql_error(); and I doesn't show anything.
I tried using mysql_errno(); and I get null also.
I know the script is catching the warning because it is outputting it to the screen.
One way to resolve my problem is to store the warning in a variable.
I appreciate any help anyone can provide. Thank you.
UPDATE - 2 SOLUTIONS:
SOLUTION 1: (thank you to Mario for suggesting this in one of his comments to this post)
Use PHP function error_get_last() - reference (http://php.net/manual/en/function.error-get-last.php).
New working code with this solution:
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
$error = error_get_last();
log($error['type'] . ": " . $error['message'] . " in file " . $error['file'] . " on line " . $error['line']);
}
...continue code
SOLUTION 2: (thank you to PauPRO for suggesting this in answer 1 below)
Before using $php_errormsg, we need to set track_errors to 1 in the php.ini file. Just include the following line in your php.ini file
track_errors = 1
Alternatively you can set track_errors to 1 inside the script see below the code with this alternative:
ini_set('track_errors', 1);
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log(mysql_error());
}
...continue code
Both solutions work!!!

Make sure you turn on track_errors before using $php_errormsg:
// Preferably do this in your php.ini file, instead of in code.
ini_set('track_errors', 1);
$db = mysql_connect('host', 'database', 'password');
if (!$db)
{
log($php_errormsg);
}

Related

PHP Warning: Error while sending INIT_DB packet. PID=3629

My automation code encountered a subject-like problem when calling a particular function.
It occurs randomly during execution, not immediately after execution, and after the problem occurs, the error "mysql_num_rows() expect parameters 1 to be resource, boolean given in" occurs and normal behavior is not performed.
The OS is Ubuntu 18.04.
PHP version is 5.6.40.
Mysql version is 5.7.38.
The problematic function code.
$conn = mysql_connect("127.0.0.1","ID","PW");
if($conn ==NULL)
{
echo "<script> alert(\" Error : DB 연결 에러입니다. 불편을 드려 죄송합니다. 관리자에게 문의 하십시요\"); </script>";
return $conn;
}
mysql_select_db("mysql");
mysql_query("set session character_set_connection=utf8;");
mysql_query("set session character_set_results=utf8;");
mysql_query("set session character_set_client=utf8;");
$dbname = "test_table";
$str = "select * from $dbname where 1";
$leak_result = mysql_query($str);
$leak_num1 = mysql_num_rows($leak_result);
Please give me a solution.
This error is appearing because of the maximum number of database connection requests have made.
Your Ubuntu 18 with PHP server it's making a lot of requests.
The "PID=3629" you read it's the Process Id that generates the error.
The method you are using mysql_query it's old and deprecated.
Now PHP uses mysqli method like this
$connect = mysqli_connect( $host, $user, $pass, $DBname );
$query = 'SELECT .... '; //here your query
$result = mysqli_query($connect,$query);
Like said in comments, if there's an error mysqli_query gives back a false result
PHP OFFICIAL SITE
If you want a more complete answer on the error use the mysqli_error() function.
Good luck

My php file is not working either in localhost or on my webhost, is something wrong with my mysql_connect?

My php file is not working either in localhost or on my webhost, is something wrong with my mysql_connect?
still not fixed, this is what I did base on your reply:
<?php
error_reporting(E_ALL);
//first get the post variables on the page
$region=$_POST['region'];
$province_of_provider=$_POST['province_of_provider'];
$con=mysqli_connect('localhost','gengon4_tesda','gengon4_tesda','gengon4_tesda');
if(!$con)
{
die('Could not connect:'.mysql_error());
}
//mysql_select_db('gengon4_tesda',$con);
$query="INSERT INTO `details` (`id`, `date_of_entry`, `region`, `province_of_provider`) VALUES (NULL, 'CURRENT_TIMESTAMP(6).000000', '$region', '$province_of_provider')";
if(!mysql_query($query,$con))
{
die('Error in inserting records'.mysql_error);
}else
{
echo "Data Inserted";
}
echo mysql_errno($con) . ": " . mysql_error($con) . "\n";
?>
I did not find any info about the error. Any idea how to address this problem?
Firstly Enable the display_errors in your php.ini as display_errors = On or set it in your php file as ini_set("display_errors", 1);
By this way you should know what's wrong in your code.
Modifications in code:
$con=mysqli_connect('localhost','gengon4_tesda','gengon4_tesda','gengon4_tesda');
you used mysqli_connect to connecting database and here in 'if(!mysql_query($query,$con))' mysql_query to running query.
Please make sure to use same methods either mysqli or mysql all over in your code.
Dont use mysql_* functions. Always use mysqli_* functions.
enable show errors by command: error_reporting(E_ALL); (first line of your source code)
then show errors by: echo mysql_errno($con) . ": " . mysql_error($con) . "\n"; (mysqli_*)
then you will se whats wrong

MySQLi warning with php7

I'm getting the following errors from php7 on a new Ubuntu server:
Notice: Trying to get property of non-object in ~/tLogServ.php on line 14
Warning: mysqli::query(): Couldn't fetch mysqli in ~/tLogServ.php on line 17
Fatal error: Uncaught Error: Call to a member function fetch_assoc() on null in ~/tLogServ.php:18
Stack trace:
0 {main}thrown in ~/tLogServ.php on line 18
Here's the tLogServ.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$request = json_decode( file_get_contents('php://input') );
$variable = $request->data;
// echo($variable);
$result = $conn->query("SELECT password FROM login where userID LIKE 'technician'");
$rows = $result->fetch_assoc();
$passHashed = $rows['password'];
if(password_verify($variable, $passHashed)){
$loginMess = "success";
}else{
$loginMess = "fail";
}
echo json_encode($loginMess);
$conn->close();
?>
and my connection script
<?php
DEFINE ('user', '$%^*(');
DEFINE ('pass', '^*&%*');
DEFINE ('host', '1*&^*&^');
DEFINE ('DB', '^*%*(&%^');
$conn = new mysqli(host, user, pass, DB) OR die('Fail Whale ' . mysqli_connect_error());
?>
The notice will go away with input, but I'm unsure about and the warning and the fatal error it causes.
This code works without issue on Ubuntu 14 with PHP5. I've uncommented
extension=php_mysqli.dll
in php.ini. This is obviously a compatibility issue, but I'm unsure if I need to re-write my code or if it's a matter of a simple setting that I can't find.
The issue was two stupid mistakes.
1)The user I referenced in my connection was not given proper rights.
and
2) 'Host' was defined as the IP of the localhost. For whatever reason this worked on Cat connection, but not on WiFI (both had static Ip's).
For others with the same/similar issue. Verify that your php.ini mysqli extension is enabled/uncommmented. As A.L was onto the issue was with mySQL settings not PHP/Ubuntu.

Echoing mysqli_connect_errno not working

Started learning PHP and after learning the basic stuff, which was easy because I learn C++ at school and most of the stuff is similar, I started with mysql. Everything works fine, but I can't get to work the connect_errno working.
Copied and pasted this http://php.net/manual/en/mysqli.connect-errno.php into my code with no success.
My few lines of code:
<?php
error_reporting(0);
$db = mysqli_connect('127.0.0.1' , 'root' , '' , 'mydb');
if ($db->connect_errno) {
die('Connect Error: ' . $db->connect_errno);
}
?>
I've also tried an example from a tutorial, no success.
EDIT: ANSWER IS BELOW!
You mixed the Object-oriented approach and the Procedural approach. Below is the example for the OO approach.
$db = new mysqli('127.0.0.1' , 'root' , '' , 'mydb');
if ( $db->connect_errno ) {
die('Connect Error: ' . $db->connect_errno);
}
error_reporting( 0 ); will suppress errors, so if you're in a debugging workflow and need to see those errors, you'll need to update the error reporting directive to error_reporting( E_ALL );.
Also, I updated the db name to mydb as reflected in the code (I switched that out on my local machine to experiment with connections/errors).
You're using a mix of OO and procedural code. mysql_connect does not return an object; it returns a db handle. You can get its error number using the following:
$db = mysqli_connect('127.0.0.1' , 'root' , '' , 'mydb');
$err = mysqli_connect_errno();

trouble logging into mysql using php

I am trying to connect to mysql via php using this line
# $db = new mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
I am not getting any response, no error message, nothing. I even added an echo'hi';
after the first line of code and it doesn't show up. When I added echo'hi'; before the first line hi prints out.
Any tips?
Get rid of the new instead do:
$db = mysqli_connect(...
or use new to create a mysqli object
$db = new mysqli(...
In the first case $db is assigned the return value of a function. The mysqli_connect function passes back the object created internal to the function. In the second case $db is being created through the new keyword as the result of the "new mysqli(..." expression.
First of all, remove the # before function calls. # is to suppress any errors from coming up.
Second, remove the new keyword. That's for instantiating a new class, not calling a function.
$db = #mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');
mysqli_connect is not an object it is function
EDIT:
remove #, make sure your error_reporting( E_ALL );
$db = mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');
"Call to undefined function mysqli_connect()" - do you have mysqli module on ? - Yes in php.ini file.

Categories