php database connection error for changing port number - php

I am facing database connection problem while trying to connect a .php file through wamp server
the error message is something like- "Access denied for the user " # ' localhost' " for database 'aschool'. 'aschool' is my database name.
Mentioning that I've changed my port number of wamp server, I am worried that is it really
for changing port number or anything else.Here is my code.
$con = mysql_connect();
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("aschool", $con);
After this line the error message comes. I've tried parameters "localhost" inside the mysql_connect()
function or more parameters but the result is same.
Thanks in advance anyone gives me any solution

That's because you are using mysql_connectwrong for your use case.
If you check the documentation page it says that you can also a server-path,
something like mysql_connect('localhost:1234', 'username', 'password').
But you shouldn't use mysql_connect.
Use PDO so that you can use parameterized queries.
In code it would go like this:
try
{
$pdo = new \PDO('mysql:dbname=aschool;host=127.0.0.1', 'myUser', 'myPassword');
} catch (PDOException $exception)
{
// Do something with your exception.
// Echo it, dump it, log it, die it.
// Just don't ignore the exceptions!
}

Related

How to connect to mysql database with php?

I'm using Jetbrains and Mysql to work on this practical project, but when I connect to the mysql
database it gives me the following error:
C:\wamp64\bin\php\php5.6.40\php.exe C:\wamp64\www\Social_Network\Includes\connection.php
Connection failed: SQLSTATE[HY000] [1049] Unknown database 'social_network'
Process finished with exit code 0
I made sure several times that the database name is the same name and there are
no spelling errors at all (I copy pasted it from the database)
Here's my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=social_network", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//?>
Welll, there's little that can be done about it. MySQL thinks that the database does not exist.
is the server the correct one?
is the case sensitivity set correctly? "Social_Network" and "social_network" might be considered different.
can you access the database with those parameters using a different tool (e.g. HeidiSQL, SQLYog, SQLterm, in a pinch even phpMyAdmin)?
Actually, JetBrains PHPStorm has a SQL terminal utility that can diagnose the connection. You may want to use it (once it knows what database you're connecting to, it will also warn you of several possible errors such as using the wrong table name or column name).

I can't connect my Website to Database in PHP

I have recently deployed my new website, I use GoDaddy Unlimited Hosting and I'am unable to connect to the database for some reason.
Here's my code for connecting my website to the database:
<?php
ob_start();
session_start();
// db properties
define('DBHOST','some.example.ip.Address');
define('DBUSER','username');
define('DBPASS','password');
define('DBNAME','database-name');
$conn = #mysql_connect (DBHOST, DBUSER, DBPASS);
$conn = #mysql_select_db (DBNAME);
if(!$conn) {
die('Some Error Message');
}
define('included', 1);
?>
And Instead of connecting my website to the database and showing the content It shows the die() error message I have used above, And I tried adding if (! $conn) { mysql_error() or die('some message'); } I can see my website but can't see the db content and when I submit any form It shows this message Query failed. Access denied for user 'root'#'localhost' (using password: NO)
Thank you for your time.
Look into using PDO. mysql_connect is deprecated and generally not considered secure. However, it should still work.
Here's a simple PDO connection:
TRY {
$handler = new PDO('mysql:host=localhost;dbname=NameofDB','username','password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
CATCH(PDOEXCEPTION $e) {
echo $e->getMessage() . "<br>";
die ('sorry for your luck!');
}
There are lots of tutorials around the web for PDO implementation, and it's generally considered he way to go.

How to prevent site failure when mysql is down

I'm having an issue yesterday and today with my host (godaddy) who apparently is having trouble with a particular mysql server... in that it's completely out of commission for a few hours at a time.
Right now this causes my site to not load at all - showing this error:
[phpBB Debug] PHP Warning: in file /home/content/index.php on line 53: mysqli::mysqli() [mysqli.mysqli]: (HY000/2003): Can't connect to MySQL server on 'dbserver.com' (110)
Connect failed: Can't connect to MySQL server on 'dbserver.com' (110)
I'm guessing it's showing that because of this code I have:
// PREPARE DB CONNECTION
$mysqli = new mysqli("dbserver.com", "username", "password", "dbname");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Which tells the php to stop altogether if mysql is down. So I suppose all I need to do is remove the "exit" function and I'm good to go?
I guess theoretically speaking, why is exit there by default in so many tutorials of how to connect to mysql? It kills the web site if the database is unavailable.
Just looking for thoughts from those who know much more than I please, thank you!
Just bin this:
printf("Connect failed: %s\n", mysqli_connect_error());
And replace it with a placeholder page instead to inform people that s**t happened and you'll be back later.
header('Location: error_db.php');
Displaying good and pretty error-messages to the user is often neglected by most programmers. This is because it can be a real pain in the ass to do the right way.
As Jassica commented, if your entire site function without the database-connection, you can just remove the exit() in your function and the site is good to go.
However, I guess the chances for a 100 % functional site without the database-connection are very small. What most sites to is to redirect the user to a 500-errorpage where they inform the user that something went wrong. Often provided contact-information so the right people can be notified too. Twitter does this, so does Facebook, Reddit and many more.
You can just do:
$mysqli = new mysqli("dbserver.com", "username", "password", "table");
if (mysqli_connect_errno()) {
header("Location: error500.html");
exit();
}
Or something like that.
This should do the trick.
function connect($u,$p,$db,$host) {
try {
$mysqli = new mysqli($host,$u,$p,$db);
$connected = true;
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
try {
connect('username','password','database','host');
} catch (Exception $e) {
echo $e->errorMessage();
}

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

The mysqli_connect not working

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

Categories