"No database selected"... but only in a function - php

Okay, so I have the weirdest problem right now. My code is fine! It works PERFECTLY as I want and expect it to, which is a major shock to me, because every time I go to do MySQL I get endless problems that I can never find a solution to.
But today, everything works perfectly. So what's the problem? The problem is that when I try to wrap my code in a function, it just... stops working! I have error checking after every step and it works fine when in it's own file and lines. But I need to put it in a function so I can add parameters (hence the "extraQuery" variable), and "return" it so that I can access it from a separate file.
Here is my base code:
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
As I said, it works completely fine as that is. But when I do this....
function getResult(){
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
}
getResult();
..It stops working at the second line, telling me "No database selected". But as you can see, I am explicitly selecting a database that DOES exist and otherwise works when it's not in a function.
And just to stress this, it is NOT my user permissions, nor is it the name of the database; because it works perfectly when outside of the function.
Any possible aid would be greatly appreciated.

Due to variable scope your database variables are not available inside of the function. You need to pass it as an argument for getResult() to have access to it:
function getResult($db_host, $db_user, $db_pass, $db_name, $extraQuery){
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
}
getResult();

variables $db_host,..., $db_name are there because you wanted to hide your access, or the function is exactly as it is written here?
If it is exactly you may need to declare these variables global (first row of the function: global $db_host,..., $db_name;), else their value inside a function is uninitialized.
NOTE: It is not good to use this. Just think your code to avoid this and as advised use at least MySQLi or PDO

It looks like the variables to access the database are not in the scope of the function.
You'd need to do something like:
function getResult( $db_host, $db_user, $db_pass, $db_name)
Then call the function with:
getResult( $db_host, $db_user, $db_pass, $db_name);
Or declare all of those variables as global variables, like so:
global $db_host, $db_user, $db_pass, $db_name;
This makes sure they are in the scope of the function. Otherwise, they are all undefined.

You need to declare $db_host, $db_name,etc as global, or pass them to the function, like this.
function getResult($db_host, $db_user, $db_pass){
//
}
getResult('localhost', 'user', 'pass');

Related

Cannot add values to table using mysql and php

I have a problem with my code. I'm trying to add new post to the table events. I'm confused because I have used this code in other place on the same website (but it was using mysqli_query to register new user). mysqql_error returns "No database selected"
This is the code:
<?php
$add_title = $_POST['add_title'];
$add_happen = $_POST['add_happen'];
$add_created = date('Y-m-d');
$add_content = $_POST['add_content'];
$add_author = $_POST['add_author'];
//connect to
//localhost
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
$query = "
INSERT INTO events ( title, happen, created, content, author )
VALUES ( '$add_title', '$add_happen', '$add_created', '$add_content', '$add_author') )
";
$retval = mysql_query($query, $db_con);
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($db_con);
//header('Location: ../../index.php?link=events');?>
I've tried to fix it using trial and error method playing with different combinations both mysql_query and mysqli_query
You are confusing mysql_connect and mysqli_connect functions in the way you pass those parameters. In your example:
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
you are passing a fourth parameter which is the database name but that wont work as you should only pass the three first (host,username,password) and then call mysql_select_db():
$db_con = mysql_connect($db_host, $db_username, $db_password);
mysql_select_db( $db_dbname, $db_con );
In mysqli which is the BETTER way of doing it since mysql_ functions are very vulnerable and being deprecated from php you could pass four elements like here:
$db_con = mysqli_connect($db_host,$db_username, $db_password, $db_dbname) or die("Error " . mysqli_error($link));
which is close to what you are trying to do, but in a correct mysqli_ way.
Well then, you need to select the database! ;) The fourth parameter of mysql_connect() is not the database name. You need to do this separate of connecting to the MySQL server.
Using mysql_select_db() function:
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password );
mysql_select_db( $db_dbname, $db_con );
And of course all the obligatory warnings about SQL injection, sanitizing your data, deprecation of mysql_* functions.
You need to select which database to connect to using the mysql_select_db function:
// make $db_dbname the current db
$db_selected = mysql_select_db($db_dbname, $db_con);
if (!$db_selected) {
die ("Can't use $db_dbname : " . mysql_error());
}
See the PHP manual for more info: http://php.net/manual/en/function.mysql-select-db.php

mysqli_select_db() not working properly ..?

function db_connect($db_host, $db_user, $db_pass, $db_name) {
$db_connect = mysqli_connect($db_host, $db_user, $db_pass) or die('Could not connect: ' . mysqli_error($db_connect));
$db_select = mysqli_select_db($db_name, $db_connect) or die ('Could not select ' . $db_name . ': ' . mysqli_error($db_select));
}
Every variable is defined. All that appears is
Could not select CMS:
There isn't even an error message. What am I doing wrong? As far as I am aware, it is connecting to MySQL, but it isn't connecting to the specified database 'CMS'.
According to php.net, mysqli_select_db exepts to be first parameter MYSQLI link, seccond DB Name
bool mysqli_select_db ( mysqli $link , string $dbname )
http://php.net/manual/en/mysqli.select-db.php
You should turn on error reporting for next time, to catch that error.
error_reporting(1);

Changing a global MySQL db file to MySQLi db file from PHP 4 to PHP 5.4

I have always used the following for MySQL database connection for procedural coding not OO running on PHP 4 and now I am moving some old websites to PHP 5.4:
<?php
global $db_user;
global $db_pass;
global $db_host;
global $db_name;
$db_user = 'USERNAME';
$db_pass = 'PASSWORD';
$db_host = 'HOST';
$db_name = 'DBNAME';
function do_query ( $sql )
{
global $db_user;
global $db_pass;
global $db_host;
global $db_name;
mysql_pconnect( $db_host, $db_user, $db_pass )or die("Cant connect to $db_host: ");
mysql_select_db( $db_name )or die("Cant select $db_name: ");
$res = mysql_query( $sql )or die("You messed up in your sql Using <b>$sql</b>\n\r" . mysql_error());
return $res;
}
?>
How can I change this to work with PHP 5.4 as all that is required for my website is to change this file as everything else now is up to date and the current way I connect with MySQLi never output errors the same way?
Thanks in advance.
UPDATE:
I tried the following:
<?php
$db_user = 'USERNAME';
$db_pass = 'PASSWORD';
$db_host = 'HOST';
$db_name = 'DBNAME';
function do_query ( $sql )
{
mysqli_connect( $db_host, $db_user, $db_pass )or die("Cant connect to $db_host: ");
mysqli_select_db( $db_name )or die("Cant select $db_name: ");
$res = mysqli_query( $sql )or die("You messed up in your sql Using <b>$sql</b>\n\r" . mysqli_error());
return $res;
}
?>
And use a mysqli_close(); at the end but it still doesn't work.
I also tried using it procedurally with:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
But I can't seem to make that work as a function.
I have done loads of tests with different versions but I didn't want to over fill the page with information most people already know so I just put up the original code I have used in the past as I have so many other variations I have tried. I was not just trying to pass the buck, just trying to explain what exactly I was trying to convert to MySQLi. Sorry if people think this is pointless but I am stuck. Thanks.
Three flaws in one post.
First, using a function to create a connection and then query is a bad idea.
Second, you're using a persistent connection. So even when the page is done the connection remains. You'll exhaust your pool of database connections like that.
Third, you're using mysql_ functions, which are deprecated.
So here's the preferred way to do things now, using mysqli and an object approach. I don't recommend $GLOBALS normally but it sounds like you're working with legacy code
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
function do_query($sql) {
$mysqli = $GLOBALS['mysqli'];
$res = $mysqli->query($sql)or die("You messed up in your sql Using <b>$sql</b>\n\r" . mysqli->error);
return $res;
}

php Insert Query - Why Are There Two Connections to a Database?

In my script I link to a page that connects to my database :
include "connect.php";
connect.php
<?php
error_reporting(E_ERROR);
/* Allows PHP to connect to your database */
// Database Variables
$Host = "myhost";
$User = "username";
$Password = "password";
$DBName = "database";
// Connect to Database
$connect = mysql_connect($Host, $User, $Password)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($DBName)
or die ("Could not connect to database ... \n" . mysql_error ());
?
Then in another script I have an insert query:
include "connect.php";
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO mytable VALUES ('0','".mysql_escape_string($forename)."','".mysql_escape_string($surname)."', '".mysql_escape_string($username)."', '".mysql_escape_string($password)."', '".mysql_escape_string($email)."')";
if(mysql_db_query ($DBName, $Query, $Link)) {
$message = "You have successfully registered";
header("Location: register.php?message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
Why is this necessary :
$Link = mysql_connect($Host, $User, $Password);
Hasn't the connection already been established?
There is no point in doing this, especially as mysql_* functions will assume the last opened connection if none is given.
However, even with two calls to mysql_connect, only one connection is made. From the docs:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
So by default, the existing connection will be returned.

Can't make mysql connection

If I use the following code, it works:
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
But when I do this, it doesn't:
$db_host='localhost';
$db_id='root';
$db_pass='';
$con = mysql_connect($db_host, $db_id, $db_pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
Trying to swap (") and (').
mysql_ functions are discouraged for new applicationa you are advised to use mysqli or PDO. The following code uses PDO to connect to database.
//dependant on your setup
$host= "localhost";
$username="XXX";
$password="YYY";
$database="ZZZ";
// connect to the database
try {
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
//Remainder of code
}
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]'). $e->getMessage()."\r\n", FILE_APPEND);//Change file name to suit
}
// close the connection
$dbh = null;
try using a script like this
$db_host = 'localhost';
$db_id = 'root';
$db_pass ='';
$con = mysql_connect ($ db_host, $ db_id, $db_pass) or die ('Could not connect:'. mysql_error ());
That code is fine. Review the error log- the problem has to be external to that code.

Categories