I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.
Related
I am trying to do a simple connection with XAMPP and MySQL server, but whenever I try to enter data or connect to the database, I get this error.
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\register.php:22
Stack trace: #0 {main} thrown in C:\xampp\htdocs\register.php on line 22
Example of line 22:
$link = mysql_connect($mysql_hostname , $mysql_username);
mysql_* functions have been removed in PHP 7.
You probably have PHP 7 in XAMPP. You now have two alternatives: MySQLi and PDO.
You can use mysqli_connect($mysql_hostname , $mysql_username) instead of mysql_connect($mysql_hostname , $mysql_username).
mysql_* functions were removed as of PHP 7. You now have two alternatives: MySQLi and PDO.
It is recommended to use either the MySQLi or PDO extensions. It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7.
PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql, mysqli, and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "username" and the password "password". And a query is run to greet the user.
Example #1 Comparing the three MySQL APIs
<?php
// mysqli
$mysqli = new mysqli("example.com", "username", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'username', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);
// mysql
$c = mysql_connect("example.com", "username", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>
I suggest you try out both MySQLi and PDO and find out what API design you prefer.
Read Choosing an API and Why shouldn't I use mysql_* functions in PHP?
As other answers suggest... Some guy (for whatever reason) decided that your old code should not work when you upgrade your PHP, because he knows better than you and don't care about what your code does or how simple it is for you to upgrade.
Well, if you can't upgrade your project overnight you can
downgrade your version of PHP to whatever version that worked
or...
use a shim (kind of polyfill) such as https://github.com/dshafik/php7-mysql-shim or https://github.com/dotpointer/mysql-shim, and then find a place for include_once("choice_shim.php"); somewhere in your code
That will keep your old PHP code up and running until you are in a mood to update...
mysql_* functions have been removed in PHP 7.
You now have two alternatives: MySQLi and PDO.
The following is a before (-) and after (+) comparison of a migration to the MySQLi alternative, taken straight out of working code:
-if (!$dbLink = mysql_connect($dbHost, $dbUser, $dbPass))
+if (!$dbLink = mysqli_connect($dbHost, $dbUser, $dbPass))
-if (!mysql_select_db($dbName, $dbLink))
+if (!mysqli_select_db($dbLink, $dbName))
-if (!$result = mysql_query($query, $dbLink)) {
+if (!$result = mysqli_query($dbLink, $query)) {
-if (mysql_num_rows($result) > 0) {
+if (mysqli_num_rows($result) > 0) {
-while ($row = mysql_fetch_array( $result, MYSQL_ASSOC )) {
+while ($row = mysqli_fetch_array( $result, MYSQLI_ASSOC )) {
-mysql_close($dbLink);
+mysqli_close($dbLink);
mysql_ functions have been removed from PHP 7. You can now use MySQLi or PDO.
MySQLi example:
mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_dbname);
mysqli_connect reference link
Make sure you have not committed a typo as in my case
msyql_fetch_assoc should be mysql
For mysqli you can use :
$db = ADONewConnection('mysqli');
...
...
$db->execute("set names 'utf8'");
in case of a similar issue when I'm creating dockerfile I faced the same scenario:-
I used below changed in mysql_connect function as:-
if($CONN = #mysqli_connect($DBHOST, $DBUSER, $DBPASS)){
//mysql_query("SET CHARACTER SET 'gbk'", $CONN);
So here's the problem, the script I purchase is written on PHP 5.x, and I'm using xampp with PHP7.x installed for development. Now I want to migrate my script to PHP7.x. Now I know this was asked a million times already but do you mind if you could take a look at my code and give your thoughts about it, or simply share your knowledge. I would deeply appreciate it.
Here is the code for my config.php
<?php
// mySQL information
$server = 'localhost'; // MySql server
$username = 'admin'; // MySql Username
$password = 'admin' ; // MySql Password
$database = 'arcade'; // MySql Database
// The following should not be edited
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$con = mysql_connect($server, $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
// Get settings
if (!isset($install)) {
$sql = mysql_query("SELECT * FROM ava_settings");
while ($get_setting = mysql_fetch_array($sql)) {
$setting[$get_setting['name']] = $get_setting['value'];
}
}
?>
The deprecated functions are:
mysql_connect()
mysql_error()
mysql_fetch_array()
mysql_query()
mysql_select_db()
Now, I don't want to use the PDO approach, I want to use mysqli instead. Am I suppose to just replace the mysql_* into mysqli_*? So it will become like these? I don't want to hide/surpress the deprecate warnings.
mysqli_connect()
mysqli_error()
mysqli_fetch_array()
mysqli_query()
mysqli_select_db()
I just offer you that migrate to PDO driver. Because every update you may see a lot of deprecation errors.
But if you can not do it the first thing to do would probably be to replace every mysql_* function call with its equivalent mysqli_*, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.
Note that, for some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)
Look at difference between mysqli and mysql:
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT ...");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];
$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT ...", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
I have this error, I have seen on several pages how to fix it, increasing the max connections variable, but I was wondering if there is any way to retry connecting 'n' number of times before throwing that error,
I am using mysqli to create my connection.
I would be very grateful for any help you could give me to get an idea of how to do it if possible
update
con.php
<?php $con = new mysqli("localhost", "root", "", "grmv");
if($conexion->connect_errno) {
die ("Error: " . $con->connect_errno . "---" . $con->connect_error);
}
return $con;
?>
Products.php
<?php
include"con.php";
mysqli_query($con,"SET NAMES 'utf8'");
$result=mysqli_query($con,"select * from bio, carac where idprod=5");
while($data=mysqli_fetch_array($result)){
....
}
$conexion->close();
}
?>
More consistent way is to keep using OOP aproach, also good practice to use bind for any untrusted input, maybe not here specifically but still good practice.
$mysqli = new mysqli(
$connectionData['DB_HOST'],
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');
$stmt = $mysqli->prepare("select * from bio, carac where idprod=?");
$stmt->bind_param('5');
$stmt->execute();
while ($result = $stmt->fetch()) {
// do stuff
}
$stmt->close();
So I'm not sure as to why PHP is not creating a database. Let me show what my code looks like first, and then I will quote what warning/error it's giving me:
<?php
// Connection
$con = mysqli_connect("localhost", "root", "1monica1");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Creating a database
// The database is called alarm_db
$sql = "CREATE DATABASE alarm_db";
if (mysql_query($sql, $con))
{
echo "Database alarm_db created sucessfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
The error and warning I keep getting is this:
Warning: mysql_query(): A link to the server could not be established in B:\DropBox\Dropbox\EbadlyAgha\Ebad\reminders.php on line 51
Error creating database:
Line 51 is where the if (mysql_query($sql, $con)) is. Also, it won't give me the mysqli_error($con). It is just blank.
My MySQL connection is fine, because I never see the "Failed to connect to MySQL" statement.
It should be in mysqli_* while you executing DB creating query.
if (mysqli_query($sql,$con)) {
echo "Database alarm_db created sucessfully";
}
Try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.
Your connection is being generated by the mysqli library:
$con = mysqli_connect
but you are trying to query it using the mysql library:
mysql_query($sql,$con)
You need to be consistent about which library you use. Stick to mysqli throughout (since mysql is deprecated).
Note that mysqli_query expects the connection before the SQL:
mysqli_query($con, $sql);
You can try this to create a database using PHP:
<?php
$con = mysql_connect('localhost', 'root', '');
$query = mysql_query('create database alarm_db') or die(mysql_error());
if($query)
{
echo 'Database is created';
}
else
{
echo 'Database is not created';
}
?>
i am new in php and want to know the code for php mysql database connection code
Refer to the PHP documentation for mysql_connect.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Here is the bare bone of it:
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);
$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);
mysql_query(... , $db2);
More Info:
http://php.net/manual/en/function.mysql-connect.php
MySQL PHP Connect Tutorial
A Detailed Tutorial:
http://www.phpf1.com/tutorial/php-mysql-tutorial.html?page=1
<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("test") or die(mysql_error());
echo "Database was selected!<br/>";
?>
Watch also mysqli,it's the "new way" of connecting to mysql
http://php.net/manual/en/book.mysqli.php
it has more functions and there are rumors that in php6 mysql will be deprecated for the mysqli implementation.
you can use it as an object(but if you're new also to OO it may be a little more difficult to understand)like this:
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');//you can also use $db=new mysqli(....) but mysql_connect does the same thing and it's more cler on what it's doing
//--a simple query--
if($result=$db::query('SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',$result->num_rows,'rows<br/>';
while($row=$result->fetch_assoc()){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
$result->close();
}
else//query error
die('MYSQL ERROR:'.$db->error);
or with functions like in mysql
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');
//--a simple query--
if($result=mysql_query($db,'SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',mysql_num_rows($result),'rows<br/>';
while($row=mysqli_fetch_assoc($result)){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
mysql_free_result($result);
}
else//query error
die('MYSQL ERROR:'.mysqli_connect_error());
You can also use a persistent mysql connection prepending 'p:' to the sql host,for example if your host is sql.myhost.com:
$db=mysqli_connect('p:sql.mysqlhost.com','database_username','password','database_name');
Using a persistent connection should give you a great performance boost and mysqli should handle the persistent connection a lot better than the normal mysql extension.
Remember to sanitize the input of your query to avoid SQL INJECTION,you can do like this:
$result=mysql_query($db,"SELECT name,value FROM mytable where name='".mysqli_real_escape_string($input_name)."'");
or using a prepared statement that's a little more complicated and it's better only if you repeat the same command multiple times only changing the input data.