PHP database connection - error when selecting database - php

I'm having problems when trying to connect to a database with PHP. I am getting the following errors
Notice: Undefined variable: dbhandle in /opt/lampp/htdocs/connection/Connection.php on line 17
Warning: mysql_select_db() expects parameter 2 to be resource, null given in /opt/lampp/htdocs/connection/Connection.php on line 17
Could not select test
My connection file:
<?php
function Connection() {
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysql_query("SET NAMES utf8");
}
function SelectDatabase() {
$name = "test";
$selected = mysql_select_db("$name",$dbhandle)
or die("Could not select $name");
}
?>
Index.php
<html>
<head>
<?php include 'Connection.php'; ?>
</head>
<body>
<?php Connection() ?>
<?php SelectDatabase() ?>
</body>
</html>

$dbhandle is out of scope when used in SelectDatabase. You might want to have Connection() return $dbhandle. That way, you could do:
<?php SelectDatabase(Connection()) ?>
Of course, you would have to modify SelectDatabase to take the connection variable as a parameter.
Or, alternatively, you could make $dbhandle a global variable so you can use it anywhere in your script.

It's a scoping problem: $dbhandle is local to Connection()
You can either use a global variable (put global $dbhandle; at the start of both functions), which is not very elegant, or
function Connection() {
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysql_query("SET NAMES utf8");
return $dbhandle;
}
function SelectDatabase($dbhandle) {
$name = "test";
$selected = mysql_select_db("$name",$dbhandle)
or die("Could not select $name");
}
and
</head>
<body>
<?php $db=Connection() ?>
<?php SelectDatabase($db) ?>
</body>
</html>

The problem here is easy to spot; you never pass the $dbhandle parameter to your function. You need to do this so the function can use the parameter; due to scope issues, not all parameters are immediately available to all functions.
Try the following instead:
function SelectDatabase($dbhandle) {
$name = "test";
$selected = mysql_select_db("$name",$dbhandle)
or die("Could not select $name");
}
And then, when you call the function:
SelectDatabase($dbhandle);
Make sure that $dbhandle is global.
Either that, or as others have pointed out, have Connection() return the variable name, and use it within the call.
Secondly, mysql_* functions are deprecated. I would suggest you use PDO instead.

you don't make your life easier :p
you just have to do this :
$connexion = new PDO("mysql:host=localhost;dbname=test","root","password");
and if you want to make sql request just :
$connexion->query("SQL REQUEST ....");

Related

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

Why isn't my PHP connecting to my database or displaying an error?

I am creating a form that will take a person's name and email and see if the email exists in the database already but I can't get the database to be selected. The mysql_error() won't display the error either. Is there something wrong with my code for selecting the database? All it shows is the hardcoded text "Could not select database because" then nothing. I replaced all the variables associated with the database with random fillers so as not to give away my info but everything I have is correct regarding that.
$host = "host";
$user = "user";
$password = "pass";
$database = "db";
$port = xxxx;
$table = "table";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection Successful";
mysqli_select_db($database)
or die("Could not select database because".mysqli_error());
// check if the username is taken
$check = "select email from $table where email = '".$_POST['email']."';";
$qry = mysqli_query($check)
or die ("Could not match data because ".mysqli_error());
$num_rows = mysqli_num_rows($qry);
if ($num_rows != 0) {
echo "Sorry, there the username $username is already taken.";
}
Don't call mysqli_select_db. You've already selected your database with the fourth parameter to mysqli_connect.
You only need to call mysqli_select_db if you want to access a different database after the connection has been established.
Also, Raptor is correct that if you call procedural mysqli_error() you must pass it a connection handle.
For Procedural style mysqli_error(), you must supply the MySQLi DB link as parameter:
mysqli_select_db($database)
or die("Could not select database because" . mysqli_error($conn));
But it's useless to call mysqli_select_db() as you already specified the DB schema in mysqli_connect().
Additionally, your SQL is vulnerable to SQL Injection attack. Always escape the parameter before putting into SQL statement, or use prepared statements.
try this code
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>

How do i connect to mysql server? and what do i use for the parameters?

Im trying to create a login for my website and i need to store emails, usernames, passwords, ect in a database i have created already using phpMyAdmin. I have gone through article after article and nothing seems to be working. i have my connect.php like this:
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
mysql_connect($hostname, $username, $password) or die("Cannot connect to server");
mysql_select_db($databaseName) or die("Cannot select database");
?>
And my main.php like this:
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
?>
And i have created a simple form in my html like this:
<html>
<head></head>
<body>
<form>
<input type = "submit" action = "main.php" method = "post" value = "Login">
</form>
</body>
</html>
After submitting the form it says cannot connect to server. I am new to php and mysql and i dont understand what each parameter in the mysql_connect is, and i dont know what they do therefore im not sure what im supposed to enter in but everyone i keep reading about seems to be inputing random values? I could use a brief explanation on that, because i am stuck at connecting and cant even get past this point sadly enough. Also i have been reading that mysql_connect is deprecated and isnt valid anymore but i dont understand what im supposed to use as an alternative. I know its mysqli but thats it and im unclear of the syntax.
mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "start<br/>";
try {
$mysqli= new mysqli('localhost', 'myusername', 'mypassword', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
If you need to know how to create users, what the heck the hostname is, how to grant access (often useful after the connect :>), just ask.
Try this code in 'connect.php'
<?php
error_reporting(0);
$con=mysql_connect('localhost','root','');// here 'root' is your username and "" is password
if(!$con)
{
echo 'not connect';die;
}
mysql_select_db('dbname',$con);// here 'dbname' is your database name
?>
And also try following code to include sql connection in your other php file(main.php)
<?php
include 'connect.php';
$sql = "SELECT * FROM myUsers";
$result=mysql_query($sql);
?>
Let me convert it to mysqli for you and maybe that will fix the problem. Also, make sure the username, password, and database name are correct.
Try this code. At very least, it will provide a better error message for debugging.
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
$con = mysqli_connect($hostname, $username, $password, $databaseName) or die(mysqli_error($con));
?>
Main.php
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysqli_query($con,$sql);
?>

Global database connection inside functions

Trying to global database connection in all functions in a .php file.
sql.php:
<?php
$servername = "XXXXX";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
save.php
$conn = require_once('../path/to/sql.php');
function save()
{
global $conn;
$sql = "INSERT INTO `content` (title, text, cat)
VALUES ('".$_POST["title"]."', '".$_POST["text"]."', '".$_POST["category"]."')";
if ($conn->query($sql) === TRUE) {
show();
}
$conn->close();
}
well i want to get sql.php with require_once and then make it global then put this in save() function.
error is:
Fatal error: Call to a member function query() on a non-object in
/homepages/3/xxxxxxxx/htdocs/xxxxxxxx/xxxxxxxx/content.php on line 37
actually i don't know this way to make it global is correct or not, so please help me to choose best way to make a global database connection inside the functions.
Try
define('DATABASE_USERNAME', 'root');
define('DATABASE_PASSWORD', 'password');
define('DATABASE_HOST', 'localhost');
define('DATABASE_DBNAME', 'db');
$conn = new mysqli(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_DBNAME);
Named constants are great for static global data.
Also you just need to do
require_once 'path/to/sql.php';
And not
$conn = require_once 'path/to/sql.php';
$conn is already being set in your require_once.

PHP getting data from SQL from database

Hey I'm wanting to retrieve some data from the a database. But it seems whenever I enter my credentials into the SQL database to retrieve the data I get the following error:
Since i presume this is a similar use case as your last question
Your php file is missing the configuration of the connection:
<?php
$dbuser = "******";
$dbpass = "*******";
$db = "SSID";
$connect = OCILogon($dbuser, $dbpass, $db);
if (!$connect) {
echo "An error occurred connecting to the database";
exit;
}
So it knows which connection you are using and passing to the checkUserPass() function.
UPDATE:
For the table name you need to pass $dbtable as you can see in the function declaration
function checkUserPass($connect,$username, $password, $dbtable)
so either set a $dbtable variable before calling the function:
$dbtable="register_table";
or send it immediately as a string:
function checkUserPass($connect,$username, $password, "register_table")

Categories