MySQLi warning with php7 - php

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.

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

Query doesn't work on my Raspberry Pi 2B

I'm trying to get my raspberry working like a webserver.
It all works, except the queries of my mysql database. The values are correct, the query is correct and my database works fine.
But when I want to get information from my database with PHP it gives an empty result.
The code:
<?php
$dbCon = new mysqli($servername, $username, $password, $database);
$Query = "SELECT * FROM `machineuptime`";
if($stmt = $dbCon->prepare($Query))
{
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$ArrayData2[] = $row;
}
}
echo "this is de first row of the array: " . $ArrayData2[0]['ID'] . ". Thats nice!";
?>
the result:
this is de first row of the array: . Thats nice!
Even when I use the query in phpmyadmin, it gives the values back, so the Query isn't wrong.
So how can I solve this issue?
Edit:
The error that I get is.
Fatal error: Call to undefined method mysqli_stmt::get_result() in /var/www/html/Stramit/index.php on line 59
you don't close the query at:
$Query = "SELECT * FROM `machineuptime`;
change it to:
$Query = "SELECT * FROM `machineuptime`";
also for the error
Fatal error: Call to undefined method mysqli_stmt::get_result() in /var/www/html/Stramit/index.php on line 59
look at this answer.
Look at the user notes for http://php.net/manual/en/mysqli-stmt.get-result.php
It requires mysqlnd driver.Make sure you have that driver installed. If you do not have them installed use BIND_RESULT & FETCH
uncommented the extension=php_mysqli_mysqlnd.dll in php.ini; and restarted Apache2.2 and MySQL services. says it in the comment of the answer.
Here is the link to the driver: http://php.net/manual/en/book.mysqlnd.php
after you have installed it you should be able to use $stmt->get_result(); ofcourse reboot your raspberry pi.
Note: your php version must be above php 5.3.0

PHP - include_once/include not working

I'm working on a very simple CMS system for a school project, and I'm having a bit of trouble.
Right now, my webpage is set up as so:
Every webpage that I create that a user can access - at the top and bottom, I have an include_once(header.php) and include_once(footer.php) respectively. These contain the top and bottom of what should be any page that gets loaded.
In my header.php I have this, along with other miscellaneous HTML:
<?php
require_once('php/constants.php');
require_once("php/functions.php");
?>
For constants.php - Contains every defined constant I can think of since I'd rather change the one constant here than search in my code to find the however many instances I could have elsewhere.
For Functions.php - Contains every function I'm creating for usage on this CMS. Contains everything from my emailing functions using PHPMailer, to Registering and Logging in using MeekroDB for Database interaction.
Here lies the problem.
On a page I have for account registration, have something along the lines of this
//get the username, password, first/last name, and send it to register function.
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$password = $_POST['password'];
$email_address = $_POST['email_address'];
//register the user. where register() is in functions.php
if(register($email_address, $password, $firstName, $lastName))
{
echo "REGISTRATION SUCCESSFUL";
}
else
{
echo "REGISTRATION UNSUCCESSFUL";
}
In my functions.php file, I declare my database information using the DB::QUERY assignment that MeekroDB mentions I use.
//MeekroDB - Used for database CRUDding
require_once("php/meekrodb.php");
DB::$user = 'root'; //yes i'll change this later
DB::$password = ''; //this too
DB::$dbName ="testDB";
In the actual register function I have this:
function register($email, $password, $firstName, $lastName)
{
//check to see if the user already exists
//poll the DB to see if the email is already in there.
$results = DB::QUERY("SELECT email FROM users WHERE email = %s", $email);
//if there is a row in the DB with this email...
if(DB::count() >= 1)
{
return false;
}
else
{
//lets prepare the user for insertion into the database.
$username = $firstName . '_' . $lastName;
//generate a salt for database insertion and password hashing
$salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password . $salt);
//create the insert statement array for insertion.
$insertionArray =
array(
'username' => $username,
'password' => $password,
'email' => $email,
'salt' => $salt,
'isAdmin' => 0
);
//insert the new user into the database.
DB::INSERT('users', $insertionArray);
//Send a registration email to the new user.
//Send an email to the user stating they've registered.
$mailer = createMailer();
//set the contents of the email
$mailer->MsgHTML(generateEmail_Registration($username));
//set the destination address
$mailer->AddAddress($email, $firstName . ' ' . $lastName);
if($mailer->Send())
{
return true;
}
else
{
return false;
}
}
}
To me, this should work.
HOWEVER:
WHenever I try running the register() function, I end up getting tons of errors involving MeekroDB and I'm not 100% sure how to fix them (whether it's an INCLUDE issue, or maybe it's something with meekroDB?)
Here are the errors I'm getting.
Warning: mysqli::set_charset(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 186
Warning: MeekroDB::get(): Property access is not allowed yet in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 188
Warning: mysqli::real_escape_string(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 496
Warning: mysqli::query(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 628
Warning: MeekroDB::queryHelper(): Property access is not allowed yet in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 662
Warning: MeekroDB::queryHelper(): Property access is not allowed yet in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 663
Warning: mysqli::real_escape_string(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 496
Warning: mysqli::real_escape_string(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 496
Warning: mysqli::real_escape_string(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 496
Warning: mysqli::real_escape_string(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 496
Warning: mysqli::query(): invalid object or resource mysqli in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 628
Warning: MeekroDB::queryHelper(): Property access is not allowed yet in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 662
Warning: MeekroDB::queryHelper(): Property access is not allowed yet in D:\xampp\htdocs\finalproject\php\meekrodb.php on line 663
REGISTRATION UNSUCCESSFUL //of course.
I think it has something to do with the way I'm including my various PHP files, and that in return is buggering up my MeekroDB connection somehow.
If you guys need more information, let me know but I think I've pretty much gotten everything out on the table.
I don't post here often, so if I've missed out on some kind of ettiquette somewhere, I apologize in advance.
Thanks! :)
If you follow along in the meekrodb.php file, the first error is called on your $mysql object which has just attempted a connection (have a look at the meekrodb.php file to see what I'm talking about) so these errors probably have to do with the connection information being bad or some other issue connecting to the database, and so other functions are failing.
A simple way to see more informative errors would be to try using their $throw_exception_on_error function:
function register($email, $password, $firstName, $lastName)
{
//check to see if the user already exists
//poll the DB to see if the email is already in there.
DB::$error_handler = false; // since we're catching errors, don't need error handler
DB::$throw_exception_on_error = true;
try {
$results = DB::QUERY("SELECT email FROM users WHERE email = %s", $email);
} catch(MeekroDBException $e) {
echo "Error: " . $e->getMessage() . "<br>\n"; // this should be a better error...
echo "SQL Query: " . $e->getQuery() . "<br>\n"; // SELECT email FROM users...
}
...
If this was an issue with the include/include_once you would get completely different messages. I would firstly recommend using the latest version of the library which is 2.3, and most importantly, check what version of PHP you are using.
From what I can tell there is most likely an issue with the MySQLi connection and depending on your version of PHP the check to ensure that a connection hasn't failed has had issues as found on this page http://php.net/manual/en/mysqli.connect-error.php
Warning
The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.
As there is no connection this will cause the multiple warnings you are seen in this form.
Warning: mysqli::method_name(): invalid object or resource mysqli

having problems connecting to mysql db with php

I have a test db on godaddy, I have had a similar issue before but with the help of stackoverflow it was solved.. So I have actually used the same solution however now I am having a host of errors when I try to load my php file from the browser.
Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/97/8603797/html/countryQuery.php on line 14
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/content/97/8603797/html/countryQuery.php on line 14
Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /home/content/97/8603797/html/countryQuery.php on line 16
Warning: mysql_close(): no MySQL-Link resource supplied in /home/content/97/8603797/html/countryQuery.php on line 18
Database Output
I have read what the problem is and some of the things I have read suggest I am not connecting to the DB correctly.. but I am only doing what I have read/been told and dont really know what else I can do to solve the issue I am having...
this is my php code, if anyone has and suggestions or solutions I would greatly appreciate hearing from you.
<?
$hostname = 'mydatabasename.db.6666666.hostedresource.com';
$database = 'mydatabasename';
$username = 'myusername';
$password = 'secretsecret';
// establish a connection
$db = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$query="SELECT * FROM `Countries`";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
$i=0;
while ($i < $num) {
$country=mysql_result($result);
echo "<b>$country<br>";
$i++;
}
?>
the out put should just be a list of the country names I have in the countrys table of my database.. which has values in it.
You are mixing PDO and mysql_* functions.
Try something like this:
$db = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$db->setAttribute(PDO::ATTR_AUTOCOMMIT, true);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="SELECT * FROM `Countries`";
$numRows=$dbh->exec($sql);
echo "There were $numRows selected with:<b> $sql </b><br><br>";
$db=null;
unset($db);
When it comes to getting data from the PDO connection, I normally do something like this using the FETCH_INTO option:
$stmt = $db->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new userStructure);
// I do normally have a class matching the row I wan:
foreach($stmt as $userStructure)
{
$someObject->year=$userStructure->year;
$someObject->month=$userStructure->month;
unset($stmt);
}
Make sure that you include the port as well when using a PDO connection. This is looking like you are doing this in a hosted environment. Check the installation guide regarding the port used.

Warnings from mysql_connect() not populating mysql_error()

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);
}

Categories