having issues with php mysql connection [duplicate] - php

I wrote a simple PHP code to connect to the MySQL server as below
<?php
$username = "root";
$password = "Kepwd";
$hostname = "localhost:81";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
but this generates the following errors. I found some topics regarding this issue in google and Stack Overflow. but those don't help me.
( ! ) Warning: mysqli_connect(): MySQL server has gone away in C:\wamp\www\SSDConsultingNew\inc\test.php on line 8
Call Stack
# Time Memory Function Location
1 0.0014 240936 {main}( ) ..\test.php:0
2 0.0014 241528 mysqli_connect ( ) ..\test.php:8
( ! ) Warning: mysqli_connect(): Error while reading greeting packet. PID=10612 in C:\wamp\www\SSDConsultingNew\inc\test.php on line 8
Call Stack
# Time Memory Function Location
1 0.0014 240936 {main}( ) ..\test.php:0
2 0.0014 241528 mysqli_connect ( ) ..\test.php:8
( ! ) Warning: mysqli_connect(): (HY000/2006): MySQL server has gone away in C:\wamp\www\SSDConsultingNew\inc\test.php on line 8
Call Stack
# Time Memory Function Location
1 0.0014 240936 {main}( ) ..\test.php:0
2 0.0014 241528 mysqli_connect ( ) ..\test.php:8
Unable to connect to MySQL

The error is here:
$hostname = "localhost:81";
You are not connecting to MySQL, but to Apache server. If you didn't change MySQL port just use
$hostname = "localhost";

you forget to specify the database name after entering database name try again. The syntax should be like this
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Related

mysql vs mysqli error when running php code in wamp stack

( mysql vs mysqli error (advait) )
Hi All, See code. This code runs on my localhost WAMP Win7 php ver 5.5.12 but it gives an error:
---
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\get_data02.php on line 9
Call Stack
# Time Memory Function Location
1 0.0010 135216 {main}( ) ..\get_data02.php:0
2 0.0010 135680 mysql_connect ( ) ..\get_data02.php:9
---
I tried replacing mysql with mysqli but that just gave more errors. How do I fix this? Thanks,
<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'iamdb_copy_04';
// 2. Create a database connection
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 3. Select a database to use
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$query = mysql_query("SELECT * FROM users WHERE city = 'city' ");
while ($rows = mysql_fetch_array($query)) {
$f_name = $rows['first_name'];
$address_01 = $rows['address_01'];
$city = $rows['city'];
echo "$f_name<br>$address_01<br>$city<br><br>";
}
?>
There are two options to get out from this error.
Set display_errors off in php file using ini_set("display_errors",0) after start of php <?php.
Replace mysql with mysqli in mysql_connect, mysql_select_db,mysql_query, mysql_fetch_array.
Let me know if you still face any problem and also comment your error.

WAMP PHP Error: Can not connect to MySQL

I need help with problem that appear on my website while I tried to connect to mysql.
so, this is the error:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\sites\mysite\core\connection.php on line 9
Call Stack
Time Memory Function Location
1 0.0007 163008 {main}( ) ..\index.php:0
2 0.0012 165376 include( 'C:\wamp\www\sites\mysite\core\connection.php') ..\index.php:1
3 0.0015 166400 mysql_connect ( ) ..\connection.php:9
( ! ) Warning: mysql_connect(): in C:\wamp\www\sites\mysite\core\connection.php on line 9
Call Stack
Time Memory Function Location
1 0.0007 163008 {main}( ) ..\index.php:0
2 0.0012 165376 include( 'C:\wamp\www\sites\mysite\core\connection.php') ..\index.php:1
3 0.0015 166400 mysql_connect ( ) ..\connection.php:9
MySQL Error: Accטs refusי pour l'utilisateur: 'root'#'#localhost' (mot de passe: OUI)
the php code to connect that I wrote, is:
<?php
session_start();
$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "root";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
cause you are using deprecated extension so
Use mysqli or PDO (The mysql extension is deprecated)
try
mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
By default, your MySQL credentials for WAMP are:
username: root
and no password.
$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "";
And as other users mentioned, try to use mysqli or pdo as mysql is deprecated, but it's not your issue here.
Good luck!
If your using the default user of phpmyadmin and didn't set a new password than the password would be an empty string (no password), unless you set your password to root.
Your code is correct, although you should look into mysqli when you feel like you can handle it.
mysql_connect — Open a connection to a MySQL Server.
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_connect()
PDO::__construct()

Warning: mysqli_connect(): MySQL server has gone away

I wrote a simple PHP code to connect to the MySQL server as below
<?php
$username = "root";
$password = "Kepwd";
$hostname = "localhost:81";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
but this generates the following errors. I found some topics regarding this issue in google and Stack Overflow. but those don't help me.
( ! ) Warning: mysqli_connect(): MySQL server has gone away in C:\wamp\www\SSDConsultingNew\inc\test.php on line 8
Call Stack
# Time Memory Function Location
1 0.0014 240936 {main}( ) ..\test.php:0
2 0.0014 241528 mysqli_connect ( ) ..\test.php:8
( ! ) Warning: mysqli_connect(): Error while reading greeting packet. PID=10612 in C:\wamp\www\SSDConsultingNew\inc\test.php on line 8
Call Stack
# Time Memory Function Location
1 0.0014 240936 {main}( ) ..\test.php:0
2 0.0014 241528 mysqli_connect ( ) ..\test.php:8
( ! ) Warning: mysqli_connect(): (HY000/2006): MySQL server has gone away in C:\wamp\www\SSDConsultingNew\inc\test.php on line 8
Call Stack
# Time Memory Function Location
1 0.0014 240936 {main}( ) ..\test.php:0
2 0.0014 241528 mysqli_connect ( ) ..\test.php:8
Unable to connect to MySQL
The error is here:
$hostname = "localhost:81";
You are not connecting to MySQL, but to Apache server. If you didn't change MySQL port just use
$hostname = "localhost";
you forget to specify the database name after entering database name try again. The syntax should be like this
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Undefined variable in class… but I define it

I'm trying to create a class for my database: class structure as below
<?php
require_once("config.php"); // include(Username, passowrd, server and databaseName)
class MySQLDatabase{
private $connection;
function __construct(){
$this->openConnection();
}
public function openConnection(){
$this->$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PWD, DB_NAME);
if(!$connection){
die("Database connection failed: ".mysql_error);
}
}
}
$database = new MySQLDatabase();
$db =&$database;
?>
then my first step was check this weather work or not. so I code index.php file as below
<?php
require("../includes/database.php"); if(isset($database)){
echo "true";
}else{
echo "false";
}
?>
after that I run the program and I got errors as below. I can not understand the reason. I google it and there are no clear solution for this. is there are anyone can help me to understand why this happen and how to solve this?
( ! ) Notice: Undefined variable: connection in C:\wamp\www\waytoits\includes\database.php
on line 9
Call Stack
# Time Memory Function Location
1 0.0005 240792 {main}( ) ..\index.php:0
2 0.0008 249872 require( 'C:\wamp\www\waytoits\includes\database.php' ) ..\index.php:3
3 0.0013 250528 MySQLDatabase->__construct( ) ..\database.php:55
4 0.0013 250592 MySQLDatabase->openConnection( ) ..\database.php:15
( ! ) Fatal error: Cannot access empty property in C:\wamp\www\waytoits\includes\database.php on line 9
Call Stack
# Time Memory Function Location
1 0.0005 240792 {main}( ) ..\index.php:0
2 0.0008 249872 require( 'C:\wamp\www\waytoits\includes\database.php' ) ..\index.php:3
3 0.0013 250528 MySQLDatabase->__construct( ) ..\database.php:55
4 0.0013 250592 MySQLDatabase->openConnection( ) ..\database.php:15
You are using $this->$connection instead of $this->connection . Remove the $ sign in connection and try again.
$this::$connection (with the $ preserved) would refer to a static variable. Because you have a class variable you should access it via $this->connection
Also you need to use the same instructions in your if-statement.

mysql connection fails

I am using this code for mysql connection
$con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
mysql_select_db("ManagersDatabase", $con);
mysql database are to be found in /var/lib/mysql/ManagersDatabase.
and my php pages are to be found in /var/www/html/.
It dosen't print anything. What is the wrong in my code?
This is how you should be connecting, by using PDO: and utilizing prepared query's when querying.
<?php
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=your_database','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
?>
Or mysqli and utilizing prepared query's when querying.
<?php
$con = new mysqli("127.0.0.1", "user", "password", "your_database");
if ($con->connect_errno) {
die("Failed to connect to MySQL: (".$con->connect_errno.") ".$con->connect_error);
}
print_r($con);
?>
Edit (Reply to comment):
If you add print_r($con); you should see the mysqli connection object like:
/*
mysqli Object
(
[affected_rows] => 0
[client_info] => mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
[client_version] => 50010
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)
[field_count] => 0
[host_info] => 127.0.0.1 via TCP/IP
[info] =>
[insert_id] => 0
[server_info] => 5.5.25a
[server_version] => 50525
[stat] => Uptime: 10 Threads: 1 Questions: 1 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.100
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 1
[warning_count] => 0
)
*/
Other methods are outdated and soon tobe (thankfully) deprecated.
you should connect to your database in else block;
$con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else // if connection is made, then select the DB
{
mysql_select_db("ManagersDatabase", $con);
}
Quote from your question:
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
... you do notice it doesn't make much sense? it is saying if (something) { //could not connect } else { //connection failed } so your code thinks it is always failing.
What you should have is something like
$con = mysql_connect("localhost", "username" , "password");
if ($con === false)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ManagersDatabase", $con);
So it would actually print out anything.
Also, you should have either display_errors enabled to get the errors on screen or error_log in use so you would get the errors logged to somewhere.
In addition, please check you actually have the mysql extension enabled and in use, and mysql_connect() function available. phpinfo(); will tell what extensions you have, and function_exists() can tell you have the function available.
So, things to do:
Fix your code logic like listed above
Enable error printing or logging
Check that you have the mysql extension enabled
Check that mysql_connect() function actually is callable
Edit. as the missing mysql extension seems to be the problem ('call to undefined function mysql_connect'):
First of all, you need to have access to your PHP configuration. If this is your local installation or server, you should have that - if you are using someone elses hosting, they are the people who should change these things.
Given some assumptions, such as
you are using your local apache server
you are not using XAMPP or any other *AMP products, but vanilla installations
this is what you should do:
Find your php.ini configuration file or create one based on example files in the PHP folder if you don't have one
Find the lines below (.dll for windows, .so for linux, don't know about others)
;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll
Strip out the comment (the first ';') from the one you want to use. You are using the first one in your example, the others are for using other abstractions described in some of the other postings here, so if you want to go with the code you have, you'd uncomment the first one.
Enable "display_startup_errors" also if you want to see any configuration problems immediately
Check that "extension_dir" setting is correct, and is pointing to the folder where you have the above .dll extensions
Restart your apache server
This is Template file for your project connect.php. You can use it.
<?php
// Connecting, selecting database
$link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
//echo 'Connected successfully';
mysql_select_db('procost') or die('Could not select database');
?>

Categories