How to properly connect and retrieve data from MySQL database on Linux - php

These days I'm switching from a Windows system to Linux. I installed the LAMP stack, and apparently there seems to be no malfunctions.
To be sure I wrote a trite script that connects to the database and performs a simple select query.
phpconnect.php:
<html>
<head>
<title>Test PHP Connection Script</title>
</head>
<body>
<h3>PHP Connect Test</h3>
<?php
$dbname = 'test';
$dbuser = 'my_user';
$dbpass = 'my_password';
$dbhost = 'localhost';
// connection to db
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// check connection
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
exit();
}
$sql = "SELECT * FROM user";
$result = $conn->query($sql);
$row = $result->fetch_array();
printf("%s %s (%s)\n", $row["firstname"], $row["lastname"], $row["age"]);
output:
I checked log file in /var/log/apache2/error.log and this is the error that comes up:
PHP Fatal error: Uncaught Error: Call to a member function fetch_array() on bool in /var/www/html/phpconnect.php:28\nStack trace:\n#0 {main}\n thrown in /var/www/html/phpconnect.php

I answer my question in case someone with the same problem is looking for the solution. Thanks to #ADyson for his help finding a solution, read his comments for details.
The problem arose from the fact that the new user created in mysql did not have the required privileges to access the database tables.
For this reason, when the statement that launched the query was reached, it returned a boolean value, that is false.
It was enough to modify the user's privileges in relation to the database to be queried.
You can do this by running the following command:
mysql> GRANT ALL ON database.table TO 'username'#'localhost';
Where:
database is the database name; you can write * to refer to all databases (not recommended)
table is the table name; you can also write * to refer to all tables in the selected database
After that, running the command FLUSH PRIVILEGES; will reload the grant tables in the mysql database enabling the changes to take effect without reloading or restarting mysql service.
mysql> FLUSH PRIVILEGES;

Related

Warning: mysqli_connect(): (HY000/1044): Access denied for user ''#'localhost' to database 'dbtest' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
When i try to connect to my sql server, it gives me the error:
Warning: mysqli_connect(): (HY000/1044): Access denied for user ''#'localhost' to database 'dbtest'.
I just created the user and gave it all permissions, but i still dosent work. Before i used another account, but i couldn't change the database perssions for it. Anybody who have a potential fix?
Here is the connect code.
<?php
// this will avoid mysql_connect() deprecation error.
error_reporting( ~E_DEPRECATED & ~E_NOTICE);
// but I strongly suggest you to use PDO or MySQLi.
$DBHOST= "localhost";
$DBUSER= "testadmin";
$DBPASS= "";
$DBNAME= 'dbtest';
$conn = mysqli_connect(localhost, testadmin, $DBPASS, dbtest);
// $dbcon = mysql_select_db($DBNAME);
if ( !$conn ) {
die("Connection failed : " . mysql_error());
}
?>
I know this thread is old, but Ahmad Sharif is correct. The best way to quickly resolve this issue, especially if you're with a new hosting company, is to just create a new database using the "MySQL Database Wizard" in cPanel, then grant ALL privileges to everyone to ensure the remote access will work. Just make sure that ALL check boxes are checked while creating the new database from the "MySQL Database Wizard".
In my case grant all privileges to 'my_user' solved the problem
GRANT ALL PRIVILEGES ON *.* TO 'my_user'#'%' ;
You can check the following link for further information
https://mariadb.com/kb/en/grant/
There is no host, no user and no db-name in your mysqli_connect call. Do:
$conn = mysqli_connect($DBHOST, $DBUSER, $DBPASS, $DBNAME);
or
$conn = mysqli_connect('localhost', 'testadmin', $DBPASS, 'dbtest');
And if you wouldn't suppress E_NOTICEs, you'd see that php is looking for undefined constants.
Please check that you check all grant privileges. If you do not then delete the previous DB and create a new Db from Mysql Database Wizard (I guess it is shared hosting). In the last step, you can check all the privileges.
I have got the same error and I could solve my problem by grant all privileges.
I don't know if anyone had a solution to this I have just been trying to create a separate table for a list of emails with a same key column. I got exactly the same error message but solved it by writing a php file which i can run on the server.... The php file creates the table ! And it had permissions to let me write to it as well !
Here is the file i used to let the server make the table i needed. And let me access it from my other php files. I will call it here "LetServerMakeTable.php" ha! When i uploaded it to my 'ricky' heliohost server i ran it on the browser thus:
http://virowiz.heliohost.org/LetServerMakeTable.php
Result:... I had a php file which collecter email addresses and a used ID code and the wrote it successfully to my new Emails table within my database.
<html>
<head>
<?php
$conn = mysqli_connect("localhost", "virowiz_Kevin", "password", "virowiz_Covid3a");
// Check connection
if (!$conn) //<---- ! conn = NOT conn
{
echo "Failed";
die("Connection failed: " . mysqli_connect_error());
}
else
{
echo "Connected successfully";
}
//---------------------------------- Create the table.
$sql = "CREATE TABLE Emails
(
CVTRn BIGINT(12),
Email char(254),
Mobile char(13)
)";
//----------------------------------
mysqli_error($conn);
if (mysqli_query($conn, $sql))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
</head>
</body>
</html>

Database is created but return error as unknown database

I already have created my database, and already have the pages in PHP ready to be connected to the database. My code of connection is the follow :
<?php
$host = "localhost";
$db = "clients";
$user = "root";
$pass = "";
$con = mysqli_connect($host,$user,$pass,$db) or die('Could not connect to MySQL: ' .mysqli_connect_error());
?>
When I try to execute the page with WAMP, it returns me the message :
Warning: mysqli_connect(): (HY000/1049): Unknown database 'clients'
Even the database being already created and the queries executed, it still gives me this error, as if the database was with the wrong name in the PHP or something.
Maybe is the error from not having some password from the user root or using localhost ? How can I fix this ?
I came across this error sometime ago while using MySQL database with node.js, I just deleted the database and created it again. It's funny though, but that was how I solved the error. Try creating the database again with another database name.

PHP/MYSQLI: mysqli_query fails in PHP

First off, I'm a total noob in mysql(i) language and know a little more than the basics of PHP.
Note: I do not manage or own / have access to the server on which the webpage currently is hosted. I can however access the phpMyAdmin page.
That said, I've got a webpage on which I am trying out some stuff. Right now I'm trying to make a log-in page linked to a database.
Now, behold the code:
$mysql_host = "localhost";
$mysql_user = "my_user";
$mysql_database = "my_database";
$mysql_password = "my_password";
$table = "my_tablename";
// Create connection
$con=mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// sending query
$result = mysqli_query("SELECT * FROM my_tablename");
if (!$result) {
echo "Query to show fields from table failed! :-(";
}
Now, here comes the actual problem. As soon as I launch the page it will give me my "Query to show fields from table failed!" error message. But when I enter the same query on the phpMyAdmin 'SQL' tab, I get the wanted results. How come the webpage gives me an error, while the phpMyAdmin gives me the results, and, how do I solve it?
Use correct syntax:
$result = mysqli_query($con, "SELECT * FROM my_tablename");
You forgot to link current mysqli connection. First parameter is link - which mysqli connection you want to use (good for multiple conns) and then the second is your query.

MySQL table doesn't exist when it does exist

I have this query:
mysql_select_db('scanner');
$query = "SELECT * FROM scanner.proxy ORDER BY RAND() LIMIT 20";
$result = mysql_query($query) or die(mysql_error());
it tells me:'scanner.proxy ' doesnt exist.. even though I do have it the table with the database. It is weird, cause my other queries work..but this one doesnt.
UPADTE:
Event when I put this:
$user='root';
$user='root'
$password='<removed_password>';
$dbname = 'scanner';
$host = 'localhost';
$link = mysql_connect($host, $user, $password) or die (mysql_error());
mysql_select_db($dbname, $link) or die (mysql_error());
it gives me this...
Unknown database 'scanner'
But I can see the scanner database in the phpmyadmin
Even when I type in phpmyadmin the sql statement
SHOW TABLES FROM 'scanner'
it says it cant find scanner
We solved this problem which occurred when connecting to multiple remote MySQL databases within the same script by adding a re-connect method before every mysql_query statement. The re-connect method invoked both mysql_connect and mysql_select_db functions. We had previously tried setting the new link parameter to true in the connect statement(s) but We still got database errors and all kinds of funny behavior.
make sure the user you use to connect has enough rights to query that table. Perhaps that table was created by another user.
EDIT: Perhaps you need to grant access to scanner from a remote location. Running this sholud help on that.
GRANT ALL ON scanner.* TO your_user#'IP_ofServer_where_PHP_runs' IDENTIFIED BY 'PASSWORD';
You have set the $dbname = 'aws_backlinks', but you are trying to connect to a different database within your query. Change your connection string to include this db instead or just connect to the server and set your database at the time of the query.
$db_host = 'localhost:Port';
Specify port for localhost.
I was facing the same problem and specifying the port solved the problem.
You're missing the argument that specifies the connection (result of mysql_connect()) in your mysql_select_db() call:
$db_host = 'localhost';
$db_username = 'root';
$db_password = 'whatever';
$db_name = 'scanner';
$link = mysql_connect($db_host, $db_username, $db_password);
mysql_select_db($db_name, $link);

How can I grant MySQL permissions from inside PHP?

what is the syntax to execute this statement in php page-
grant file on *.* to kentest#localhost identified by 'kentest1';
Check your [MySQL?] database vendors documentation - because that's a DBMS statement, not PHP. I'd start here: http://php.net/manual/en/function.mysql-connect.php
EDIT: To clarify, assuming you get your connection working, it would be as simple as wrapping your query in a call to mysql_query(). Example:
mysql_connect(...);
mysql_select_db(...);
mysql_query("grant file on *.* to kentest#localhost identified by 'kentest1';");
Check out the GRANT command! http://dev.mysql.com/doc/refman/5.1/en/grant.html
Check out the CREATE USER command! http://dev.mysql.com/doc/refman/5.1/en/account-management-sql.html
Ultimately check out the all section about account management in MySQL: http://dev.mysql.com/doc/refman/5.1/en/account-management-sql.html
firstly,you check the user of mysql_connect,is a root? this user must have the right to grant.
Here's some basic code that will work for many MySQL queries, including GRANT so long as the user is permissioned to do so:
// Credential variables, separated so we can reuse them later
$host = "localhost";
$user = "user";
$pass = "123456notsecure";
$db = "database_to_use";
// Set up the query we're going to run
$query_to_run = "QUERY TO RUN";
// Make the MySQL connection
$mysql_connection = mysql_connect($host, $user, $pass);
// Select the database to use
mysql_select_db($db) or die(mysql_error());
// Run the query
$result_of_query = mysql_query($query_to_run) or die('Running the query failed: ' . mysql_error());
// Close the MySQL connection
mysql_close($mysql_connection);

Categories