I have codeigniter configured to use multiple databases. For some customers, we need to query an additional database so this is a matter of:
if( isConfigured(database) )
foo();
However, the attempts I have made have either given the same result whether or not the db is configured in databases.php, or throws an error.
I have attempted the following:
if( $this->load->database('optional') == FALSE )
Which raises the error You have specified an invalid database connection group
try( $this->load->database('optional') )
{
foo();
}
catch(Exception $e)
{
doNothing();
}
Which raises the same error
The documentation states that $this->load->database('optional', TRUE) returns the connection ID however I cannot check this as the code errors out before returning a value.
I was expecting to be able to check whether or not a property had been set, e.g. $this->config->item('db')['optional'] but this would be largely guesswork to determine how to access the correct property
I have also looked into the dbutil class but this only applies to databases which have already established a connection.
$db['db1']['hostname'] = 'localhost';
$db['db1']['username'] = 'root';
$db['db1']['password'] = '';
$db['db1']['database'] = 'mydatabase';
$db['db1']['dbdriver'] = 'mysql';
$db['db1']['dbprefix'] = '';
$this->load->database('db1',TRUE);
Related
My automation code encountered a subject-like problem when calling a particular function.
It occurs randomly during execution, not immediately after execution, and after the problem occurs, the error "mysql_num_rows() expect parameters 1 to be resource, boolean given in" occurs and normal behavior is not performed.
The OS is Ubuntu 18.04.
PHP version is 5.6.40.
Mysql version is 5.7.38.
The problematic function code.
$conn = mysql_connect("127.0.0.1","ID","PW");
if($conn ==NULL)
{
echo "<script> alert(\" Error : DB 연결 에러입니다. 불편을 드려 죄송합니다. 관리자에게 문의 하십시요\"); </script>";
return $conn;
}
mysql_select_db("mysql");
mysql_query("set session character_set_connection=utf8;");
mysql_query("set session character_set_results=utf8;");
mysql_query("set session character_set_client=utf8;");
$dbname = "test_table";
$str = "select * from $dbname where 1";
$leak_result = mysql_query($str);
$leak_num1 = mysql_num_rows($leak_result);
Please give me a solution.
This error is appearing because of the maximum number of database connection requests have made.
Your Ubuntu 18 with PHP server it's making a lot of requests.
The "PID=3629" you read it's the Process Id that generates the error.
The method you are using mysql_query it's old and deprecated.
Now PHP uses mysqli method like this
$connect = mysqli_connect( $host, $user, $pass, $DBname );
$query = 'SELECT .... '; //here your query
$result = mysqli_query($connect,$query);
Like said in comments, if there's an error mysqli_query gives back a false result
PHP OFFICIAL SITE
If you want a more complete answer on the error use the mysqli_error() function.
Good luck
I have a simple question. I'm not too good at programming yet but is this safe and correct?
Currently I am using functions to grab the username, avatars, etc.
Looks like this:
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
config.php ^^
function getUsername($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT username FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$name = $stmt->fetch();
return $name["username"];
}
function getProfilePicture($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$image = $stmt->fetch();
return $image["profilepicture"];
}
Is this correct and even more important, is this safe?
Yes, it's safe with respect to SQL injections.
Some other answers are getting off topic into XSS protection, but the code you show doesn't echo anything, it just fetches from the database and returns values from functions. I recommend against pre-escaping values as you return them from functions, because it's not certain that you'll be calling that function with the intention of echoing the result to an HTML response.
It's unnecessary to use is_int() because MySQL will automatically cast to an integer when you use a parameter in a numeric context. A non-numeric string is interpreted as zero. In other words, the following predicates give the same results.
WHERE id = 0
WHERE id = '0'
WHERE id = 'banana'
I recommend against connecting to the database in every function. MySQL's connection code is fairly quick (especially compared to some other RDBMS), but it's still wasteful to make a new connection for every SQL query. Instead, connect to the database once and pass the connection to the function.
When you connect to your database, you catch the exception and echo an error, but then your code is allowed to continue as if the connection succeeded. Instead, you should make your script die if there's a problem. Also, don't output the system error message to users, since they can't do anything with that information and it might reveal too much about your code. Log the error for your own troubleshooting, but output something more general.
You may also consider defining a function for your connection, and a class for your user. Here's an example, although I have not tested it:
function dbConnect() {
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
error_log("PDO connection failed: " . $e->getMessage());
die("Application failure, please contact administrator");
}
}
class User {
protected $row;
public function __construct($userid) {
global $conn;
if (!isset($conn)) {
$conn = dbConnect();
}
$stmt = $conn->prepare("SELECT username, profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$this->row = $stmt->fetch(PDO::FETCH_ASSOC);
}
function getUsername() {
return $this->row["username"]
}
function getProfilePicture() {
return $this->row["profilepicture"]
}
}
Usage:
$user = new User(123);
$username = $user->getUsername();
$profilePicture = $user->getProfilePicture();
That looks like it would work assuming that your config file is correct. Because it is a prepared statement it looks fine as far as security.
They are only passing in the id. One thing you could do to add some security is ensure that the $userid that is passed in is the proper type. (I am assuming an int).
For example if you are expecting an integer ID coming in and you get a string that might be phishy (possible SQL injection), but if you can confirm that it is an int (perhaps throw an error if it isn't) then you can be sure you are getting what you want.
You can use:
is_int($userid);
To ensure it is an int
More details for is_int() at http://php.net/manual/en/function.is-int.php
Hope this helps.
It is safe (at least this part of the code, I have no idea about the database connection part as pointed out by #icecub), but some things you should pay attention to are:
You only need to require your config.php once on the start of the file
You only need to prepare the statement once then call it on the function, preparing it every time might slow down your script:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. - PHP Docs
(Not an error but I personally recommend it) Use Object Orientation to help organize your code better and make easier to mantain/understand
As stated by #BHinkson, you could use is_int to validate the ID of the user (if you are using the IDs as numbers)
Regarding HTML escaping, I'd recommend that you already register your username and etc. HTML escaped.
<?php
$username='root';
$password='xyz';
$database='abc';
$host='localhost';
function MongoConnect($username, $password, $database, $host) {
$con = new Mongo("mongodb://{$username}:{$password}#{$host}"); // Connect to Mongo Server
$db = $con->selectDB($database); // Connect to Database
}
$collection=$db->movie;
$document = array( "name" =>"Calvin and Hobbes");
$collection->insert($document);
// find everything in the collection
$cursor = $collection->find();
// iterate through the results
foreach ($cursor as $document) {
echo $document["name"] . "\n";
}
?>
I had installed MONGO DB and tried to test my DB, but I am getting an ERROR
"Internal Server Error 500"
And also my Test.php file have my own content called Hello World, but if I had run the TEST.php file it displays Nothing.
My DB table is not accessing and I wasn't able to retrieve data from my Database.
So Kindly help me out here.
There can be several things wrong.
First - is Mongo driver installed?
Second - your MongoConnect function have no effect. You are defining it and not calling. Plus even if you would call it there would be no effect as $db is only in function scope and not outside.
Third - because function MongoConnect have no effect "$collection=$db->movie;" will result in problem as $db is not defined.
Consult http://php.net/manual/en/mongocollection.insert.php on how to insert data in collection.
Internal Server Error only occured when misspelled in code or some of function called wrongly. Please review ur code.
I use the following connection code in open function of a session handler file named sessionhandler.php for establishing connection between session handler and MySql database named AB, for example.
<---sessionhandler.php--->
function _open()
{
global $db;
$hostname_AB = "localhost";
$database_AB = "database";
$username_AB = "user";
$password_AB = "pass";
$AB = mysql_pconnect($hostname_AB, $username_AB, $password_AB) or trigger_error(mysql_error(),E_USER_ERROR);
$db = mysql_select_db($database_AB, $AB) or die("Couldn't select database");
if ($db = mysql_pconnect($hostname_AB, $username_AB, $password_AB))
{
return mysql_select_db('sessionhandler', $db);
}
return FALSE;
}
function _close()
{
global $db;
return mysql_close($db);
}
The problem is that, I can't make query to any other table for example my_table1, my_table2, etc. of AB database using the connection code quoted in the first block above. The first code block only establishes connection between the session handler file sessionhandrer.php & database table sessionhandler only.
In order to make query to other tables of the database AB I had to use seperate connection file that contains the following code:
$hostname_AB = "localhost";
$database_AB = "database";
$username_AB = "user";
$password_AB = "pass";
$AB = mysql_pconnect($hostname_AB, $username_AB, $password_AB) or
trigger_error(mysql_error(),E_USER_ERROR);
Example of a query using above connection code that ignores the connection code of sessionhandler.php :
mysql_select_db($database_AB, $AB);
$query_test = "SELECT users.id, users.name FROM users WHERE users.id = >= 1";
$test = mysql_query($query_test, $AB) or die (mysql_error());
$row_test = mysql_fetch_assoc($test);
$totalRows_test = mysql_num_rows($test);
Absence of the above connection file causes typical MySql connection error in case there are any queries there from other tables of AB database.
How shall I combine these two connection files for making queries to all tables of database AB?
Though I haven't had time to merge these two connection queries into one, mathematical logic says that
if ($db = mysql_pconnect($hostname_AB, $username_AB, $password_AB))
{
return mysql_select_db('sessionhandler', $db);
}
the above block of equation confines the database connection to a single table sessionhandler and primarily that's why query to other tables using this connection code is invalid.
I tried to rename my database (I am using hostmonster) and now nothing is loading on my page. I can't seem to find any documentation anywhere on this. I renamed the database back to what it originally was and I still getting the same error and nothing is loading on my page now. I am using codeigniter (as the title would suggest). The following error is:
A Database Error Occurred
Unable to select the specified database: xxxxx
Filename: core/Loader.php
Line Number: 346
I go to this file and there is nothing of relevance there:
// Load the DB class
$CI->db =& DB($params, $active_record);
Do I have to completely re-install my files to the server now? Here is what database.php looks like...
$active_group = 'main';
$active_record = TRUE;
$db['main']['hostname'] = 'localhost';
$db['main']['username'] = 'xxxx';
$db['main']['password'] = 'xxxx';
$db['main']['database'] = 'xxxx';
$db['main']['dbdriver'] = 'mysql';
$db['main']['dbprefix'] = '';
$db['main']['pconnect'] = TRUE;
$db['main']['db_debug'] = TRUE;
$db['main']['cache_on'] = FALSE;
$db['main']['cachedir'] = '';
$db['main']['char_set'] = 'utf8';
$db['main']['dbcollat'] = 'utf8_general_ci';
$db['main']['swap_pre'] = '';
$db['main']['autoinit'] = TRUE;
$db['main']['stricton'] = FALSE;
Obviously, I don't really use the (xxxx)'s...
In your control panel , go to MySQL Databases
I assumed you have already created a user , Now what you are missing out ... is that you did not add the user to the database
after adding , confirm the necessary permission , then you are good to go!
Set $db['default']['pconnect'] = FALSE;. Here mysql_pconnect() is disabled, So we are using mysql_connect().
open application->config->database.php
and set the configuration variable
$db['default']['database'] = 'new name';
Using command prompt/terminal, type in the following from your mysql bin folder:
mysql -u USER -h localhost -p PASSWORD DATABASENAME
See if that throws any issues at you (wrong password, wrong database name, etc..). Make sure you use the same text from your configs (copy/paste).
I had same problem under CPanel.
It helped to set:
$db['main']['db_debug'] = FALSE;