Connect to XAMPP MySQL Database from Document Root on another Drive - php

would like to ask about configuration of XAMPP mySQL database.
I have set my xampp document root to drive D, and now i unable to connect to SQL database and always get error.
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in D:\localserver\connection.php:3 Stack trace: #0 D:\localserver\login.php(4): include() #1 {main} thrown in D:\localserver\connection.php on line 3
the file that handle the connection look like this
<?php
$connect = mysql_connect("localhost","root","");
if(!$connect) {
die ('connection fail!!!');
} else {
print ('connection okay!!!');
}
$connectdb = mysql_select_db('admin_login');
if(!$connectdb) {
die ('connection fail!!!');
} else {
print ('connection okay!!!');
}
?>

The mysql_connect() function is from a library that is deprecated since a couple of years and has been removed in PHP 7.
Use mysqli_connect() or PDO.
UPDATE
You can pass the name of the database into mysqli_connect() and get rid of the extra mysqli_select_db(). If you want to user mysqli_select_db() in procedural style instead of object oriented it expects the link that is returned by mysqli_connect() as the first parameter and the database name as the second one like this:
$link = mysqli_connect("localhost", $user, $password);
$db = mysqli_select_db($link, $dbname);

Related

Why I'm not able to create a new database in MySQL using PDO? Is it necessary to have a database already present before creating a new one using PDO? [duplicate]

This question already has answers here:
Pdo connection without database name?
(4 answers)
Closed 5 years ago.
I've installed the latest available version of XAMPP Package on my machine running on Windows 10 Home Single Language Edition.
I'm learning PHP and MySQL.
So, first of all in order to create a new database I wrote following code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();//Getting 'Notice : Undefined variable : sql' for this line
}
$conn = null;
?>
The database didn't get created and I received following error in output after running above file in a web browser :
Notice: Undefined variable: sql in prog_1.php on line 16
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Can someone please help me by correcting my code, so that I can further start studying the database concepts in actual manner?
Is it necessary to have a database already present when accessing the same using PDO?
P.S. : The database titled 'mydb' is currently not present in MySQL RDBMS.
You're setting the DB name in your DSN connection string, and it looks like mydb doesn't exists.
Just remove that part from the DSN string and try again.
Your $conn = new PDO() fails because there isn't a database called myDB (SQLSTATE[HY000] [1049]). Because that line fails your try catch statement will evaluate to the catch part before it declares the $sql variable. So when you try to access the $sql variable in the catch part it does not exist and will throw an Undefined variable error.
You'll have to move the $sql above the $conn = new PDO() line to fix the undefined variable error. To fix the missing database error you'll have to create a database called myDB.
try {
$sql = "CREATE DATABASE myDBPDO"; // moved it here
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// (...)
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage(); // no undefined variable
}
To connect to the database without selecting a specific database you'll have to change your new PDO() DSN to this:
$conn = new PDO("mysql:host=$servername", $username, $password);
For more information please check this answer.

Cron job returns an error message

I'm trying to connect to my database via cron job. However i keep receiving an error messages. After many frustrating hours im posting here for help.
My cron script php file:
<?php
define("HOST","localhost");
define("USERNAME","user_muser");
define("PASSWORD","*********");
define("DB_DATABASE","databasename");
$conn = mysqli_connect('HOST', 'USERNAME', 'PASSWORD','DB_DATABASE');
// Check connection
if (mysqli_connect_errno())
{
"Failed to connect to MySQL: " . mysqli_connect_error();
}
// Check if server is alive
if (mysqli_ping($conn))
{
"Connection is ok!";
}
else
{
"Error: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
This is the error i received:
mysqli_connect(): (HY000/2005): Unknown MySQL server host 'HOST' (0)
mysqli_ping() expects parameter 1 to be mysqli
mysqli_error() expects parameter 1 to be mysqli
mysqli_close() expects parameter 1 to be mysqli
Any help? Thanks!
You're quoting constants, which makes them strings.
define("HOST","localhost");
define("USERNAME","user_muser");
define("PASSWORD","*********");
define("DB_DATABASE","databasename");
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DB_DATABASE);
You should write constants out of quotes as following. Otherwise they are usual strings.
$conn = mysqli_connect(HOST, USERNAME, PASSWORD,DB_DATABASE);

Access denied for user ''#'localhost' (using password: NO) [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 4 years ago.
Attempting to connect to localhost sql db using the following code (Not doing anything with query at this point just want the query to execute):
<?php
$host = "localhost";
$port = 3306;
$socket = "";
$user = "root";
$password = "Password1";
$dbname = "CIIP_WIKI";
$con = new mysqli($host, $user, $password, $dbname, $port);
if(!$con)
{
echo ("db connection failed!");
die ('Could not connect to the database server' . mysqli_connect_error());
}
else {
echo ("db connection established.");
echo ("<br/>");
}
$query = sprintf("SELECT first_name FROM actor WHERE actor_id='1'");
$result = mysql_query($query);
$con->close();
?>
I keep getting the following...
Welcome
db connection established.
Warning: mysql_query(): Access denied for user ''#'localhost' (using password: NO) in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31
Warning: mysql_query(): A link to the server could not be established in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31
Why does this not work?
This is because you create a connection using mysqli_ and then use mysql_ to try to fetch your result. They are different API's.
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
printf("Success... %s\n", mysqli_get_host_info($mysqli));
Example taken from the PHP manual
This warning will be logged anytime you try to execute a query without a valid connection object being available.
In your case you thought you had a valid connection object available, but you created it using mysqli while your query is being executed using mysql. Those are two different APIs and so the mysql_query function was looking for a mysql connection object and didn't find it.

Warning: mysql_error(): supplied argument is not a valid MySQL-Link resource [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
$err = mysql_query("INSERT INTO tridy (id,NazevTridy,url) VALUES (
'$i',
'$tridy->find('div[class=rozvrhseznam]', 0)->find('a[href]', $i)->outertext',
'$tridy->find('div[class=rozvrhseznam]', 0)->find('a[href]', $i)->href')");
mysql_error($err); // line 97
Warning: mysql_error(): supplied argument is not a valid MySQL-Link resource in /hosting/www/cran-web.com/www/rozvrh/engine.php on line 97
--- lines 2-6:
$username="*****.com";
$password="*********";
$database="*********";
mysql_connect('127.0.0.1', $username, $password) or die('Could not connect'.mysql_error());
mysql_select_db($database) or die( "Cannot select db.");
I'm getting this error when I try to execute my query. Can you tell what does the error message mean and how to fix it?
mysql_error($err); remove the argument!
It takes link to the resource not number of error.
Link is used to recognise different connections (you can retrieve one using mysql_connect) read about this if u need more.
mysql_error() expects a "Link resource" and no "result resource". Te correct way would be something like:
$username="*****.com";
$password="*********";
$database="*********";
$connection = mysql_connect('127.0.0.1', $username, $password) or die('Could not connect'.mysql_error());
mysql_select_db($database, $connection) or die( "Cannot select db.");
$err = mysql_query("INSERT INTO tridy (id,NazevTridy,url) VALUES (
'$i',
'$tridy->find('div[class=rozvrhseznam]', 0)->find('a[href]', $i)->outertext',
'$tridy->find('div[class=rozvrhseznam]', 0)->find('a[href]', $i)->href')", $connection);
mysql_error($connection); // line 97
Mind the use of $connection. Wile $connection could be dropped everywhere as in
mysql_error();
Which uses the last opened connection or opens a new one by default. While depending on the default connection is bad. You might also want to look into mysqli or PDO as alternative ways to talk to MySQL.
You are passing a query into mysql_error, you need to pass a link identifier.
Also mind that mysql_query() dealing with INSERT returns true on success and false on failure.
So naming the variable $err is somehow misleading, if($err) would mean no error occurred and vice versa.
Better:
$success = mysq_query("INSERT....");
if(!$success) {
// use of $connection is pointed to in other answers
$error_msg = mysql_error($connection);
// so some error handling
}
About mysql_error():
Parameter: The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed
and the return value:
Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.
So you also do something with the return value. Just calling mysql_error() is of no use!

mysqli_error() expects exactly 1 parameter, 0 given [duplicate]

This question already has answers here:
Warning: mysqli_error() expects exactly 1 parameter, 0 given error
(4 answers)
Closed 2 years ago.
I am trying to get my head around mysql. Can someone tell my why this mysql query is not working? I am getting the following error:
Warning: mysqli_error() expects
exactly 1 parameter, 0 given in
/home/freebet2/public_html/test.php on
line 11
test.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$conn = db_connect();
$result = $conn->query("ALTER TABLE users ADD COLUMN refer_old INT(10) AFTER refer_id");
if(!$result){
echo "Error with MySQL Query: ".mysqli_error();
}
?>
db.php
<?php
function db_connect() {
$result = new mysqli('localhost', 'user', 'password', 'db');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>
If I change the alter string to something like : $result = $conn->query("SELECT * FROM users refer_id"); I get no error for some reason.
You are mixing the object-oriented and the procedural styles of the mysqli API :
You are using object-oriented :
$result = new mysqli('localhost', 'user', 'password', 'db');
And, then, procedural :
echo "Error with MySQL Query: ".mysqli_error();
You should use either OO, or procedural -- but not both ; and if you choose procedural, the functions expect the link identifier passed as a parameter.
For instance, mysqli_error should be called either using the object-oriented API :
$link = new mysqli(...);
echo $link->error;
Or the procedural API :
$link = mysqli_connect(...);
echo mysqli_error($link);
(Of course, it will not change the fact that you are having an error in your SQL query, but it'll allow you to get the error message, which should help finding the cause of that error)
As far as the sql error is concerned, does 'user' have permissions to alter the table?
Use mysqli_error($result) as mysqli_error expects the connection to be passed as a parameter.

Categories