To understand a line of PHP code about a connection - php

What is connection() in the following code?
Code which I do understand completely
if($user->connection($email,$password)){
}
Let's assume connection() is pseudo-code.
Is the pg_prepare and pg_execute` enough to create the connection?
The line caused me to omit the use of its main code in generating a login system. Subsequently, SOers pointed out severe sequrity holes in my code.
I could not find the explanation for the function connection().
The code seems to be pseudo-code to me, since the connection does not have any attributes to the database, for instance by
Example of how the connection should be formed
$result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users
WHERE email=$1;");
$passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email']));

$user is an instance of a class.
connection is a method in that class.
$mail & $password are parameters to that method.
This has nothing todo with arrays. what you mean would be:
$foo = array("key" => "value");
maybe this can help you:
http://www.webstockbox.com/php/7-tutorials-on-how-to-create-a-php-login-system/

I haven't actually used php.net, but this just looks like connection is a method of object $user that takes 2 params. Nothing to do with arrays.

Related

is it safely to use Mysqli_connect link in a function as GLOBALS?

is it safely way to use Mysqli_connect link in a function as GLOBALS like on following example ? What problems might I face on with this way ?
function dbconnect(){
$link = mysqli_connect($db['host'], $db['user'], $db['pass']);
mysqli_select_db($link, $db['db']);
return $link;
}
function something_query($sql){
return mysqli_query($GLOBALS['conn'], $sql);
}
$conn = dbconnect();
$newsql = 'select * from table where 1';
something_query($newsql);
edit 1 : $conn is an unique string on whole code and it does not use as param in query
Yes, it's save (as in, there are no security risks with it).
It is not the best design though. Dependency injection is generally preferred to global variables, as it gives you the opportunity of testing only a small part of your code, and mocking the rest that is not needed for that test, and it increases the reusability of your code (you can just take a class/function and use it in a different project, without reading all the code and checking what values need to exist in global).

Connecting to a MySQL database with PDO

Pre-emptive apology: This post contains basic questions.However, I have searched and I have not found an answer, if there is one...sorry.
I am following some youtube tutorials for making a basic ajax web chat, and in the tutorial the person is using MySQLi to connect to the DB. I want to create the same ajax chat application except I want to use PDO instead of MySQLi.
The person uses these two files:
config.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'bucky_chat');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'bucky_chat');
?>`
chat.class.php
<?php
require_once('config.php');
require_once('error_handler.php');
class Chat {
private $mysqli;
//constructor opens DB connection
function __construct(){
$this->mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
}
//destructor closes db connection
function __destruct(){
$this->mysqli->close();
}
}
?>
I'm trying to replicate the above snippets with PDO. The problem is that I'm not sure how to adapt the PDO examples I have looked at to do this.
First of all I'm confused as to why he defined these things in a separate file.. are there any benefits in doing this?
In another PDO tutorial I am looking at I see it can be done the followings way:
<?php
$config['db'] = array(
'host' => 'localhost',
'username' => '',
'password' => '',
'dbname' => ''
);
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['db_name'], $config['db']['username'], $config['db']['password']);
//some code
$db = null; //closes connection
?>
`
I think this is what I need to use (in a try catch block), but why does he put these things in an array? it seems to over complicate things... why not just variables? But does this code replicate the mysqli example? Howcome I don't see __construct() being used with PDO?
Some minor questions...
When creating a website with a user, is there a standard place to store DB connection?
Any book recommendations?
Sorry for all these questions, All help is strongly appreciated!
To answer your questions:
First of all I'm confused as to why he defined these things in a separate file
The authentication details are defined in a second file because if you create another query script, now both scripts can include the authentication details. If the authentication details change, you only need to update one file. If you are just writing a simple application, than just keep everything in one file.
but why does he put these things in an array
I think this is just done in-case the authentication details are needed someone else in the script (much like the defined globals from your first sample). Its often best practice to define parameters into variables (even if you use the variable once). This way, if you typo a variable, you will get an error; versus copy and pasting the same string over and over again.
Howcome I don't see __construct() being used with PDO
When ever you create a new object in PHP, you do not need to call __construct, it is called automatically with the "new" statement.
$PDOConnection = new PDO($dsn, $username, $password);
When creating a website with a user, is there a standard place to store DB connection
Definitely make sure the authentication details are stored in an inaccessible file to the public. The connection object has no harm to be accessed by the public (unless of course you need to authenticate the client (website user) before establishing a database connection). Is is best practice to always begin your (secure) PHP files with:
<?php
BUT... never end the file with "?>". If an extra character is inserted after the "?>" on accident, your web server could display your whole script to the world (of course your Apache, etc... would have to be configured wrong). Like I said... best practices.
Any book recommendations?
Googleing "php arcitechture best practices" may help.
You are confusing WAY TOO MUCH things that can be explained in one answer. you don't even know what to ask.
Please, don't take the art of programming as a some sort of cheap trick one can learn in 2 hours. To write a AJAX-based chat one need to learn for at least several months. To learn by understanding, not by copy-pasting. To learn step by step, going from variables to arrays, from arrays to functions, from functions to classes and so on - not by throwing all the code they find in one bowl and then asking on SO how to deal with all that. One cannot get to another step without having understand a previous one. And of course all these youtube tutorials are definitive pieces of useless rubbish.
some of your confusions are:
__construct() method actually has nothing to do with PDO. Nor with mysql. this is a Chat class method. And method which is all wrong. Chat class shouldn't create its own connection but use already created one.
This thing on variables vs. array vs. constants doesn't really matter. To have connection options in a separate file is a good thing but nonetheless you need to have a connection code in the separate file as well, to avoid writing connection code in the every file.
You should not use this code in a try catch block (unless you have an idea what to do in case of error, which I doubt you have).
Before starting for a chat, you have to learn smaller, simpler applications, like telephone book or the like, to learn basic database operations, from which you'll be later able to build ANY application, like any house can be built of bricks.
PDO basics you can get right here, in the tag wiki. But OOP basics is not that easy.
First the reason you define config in different file is so that you can just include that file instead of writing the database configuration anytime you want database access. It is preferred best practice.
you can do:
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Do you stuffs
$PDOConnection = null;
}
catch(PDOException $e)
{
//Do something with error
}
Why not just do:
<?php
$hostname = 'host';
$dbname = 'dbname';
$username = 'uname';
$password = 'pw';
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
?>
In a separate PHP file I call mine dbPDO.php and then have:
require_once("dbPDO.php");
In your PHP pages. And then run queries by doing:
EDIT: to condense my answer.
$username = $_POST['username'];
$stmt = $db->prepare("SELECT field1, field2, field3, etc FROM mytable WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($r = $stmt->fetch()) {
$field1 = $r['field1'];
$etc = $r['etc'];
}
Make sure you bindParam and use the ':' in the query. Don't just put WHERE username = $username or WHERE username = $_POST['username'] That would led you prone to SQL Injection. Also, I didn't show it here, but you should have some sort of exemption handling for each query. I place the whole query in a Try/Catch, but I hear there are other ways to deal with it. I personally think its personal preference.
First of all you don't need an array nor variables, you can directly input the configuration..like:
try { //try connection
//common db
$db = new PDO('mysql:host=localhost;dbname=some_db_name', 'some_usernane', 'some_pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) { //connection failed
die("Oh no! It seems we took too long to respond, we are sorry for that..");
}
Secondly _constructor() means that whenever the class Chat is called everything in the _constructor() is executed .
Here is a good tutorial for PDO http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

How to use PHPUnit administrative connection to query DB?

Using the PHPUnit administrative connection to the database would avoid "polluting" any logging or other things going on inside of our app code with an SQL command that's only being used to implement the test.
I'd like to use $this->getConnection() to grab the administrative PHPUnit connection to the database rather than call our SystemDB::query() function directly, but I can't seem to get the syntax correct. Any thoughts would be appreciated.
This worked:
$result = $this->getConnection()->getConnection();
$query = $result->query( $sql );
$my_array = $query->fetchAll();
where $sql is the query and getConnection() is implemented according to the main phpUnit manual page http://phpunit.de/manual/current/en/database.html

joomla using multiple database queries in one function

In certain functions I may need to do a couple of queries like so:
$user = & JFactory::getUser();
$db = & JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id');
$query->from($db->quoteName('#__users'));
$query->where('username='.$db->quote($response->username));
$db->setQuery($query);
$user_id = $db->loadResult();
if ($user_id == "")
{
//do something
}
$query1 = $db->getQuery(true);
$query1->select('app_id');
$query1->from($db->quoteName('#__app_ids'));
$query1->where('app_descr='.$db->quote($this->app_descr).' AND app_valid=TRUE');
$db->setQuery($query1);
$app_id = $db->loadResult();
I find if I don't change query to query1 I can't get this to work for the subsequent queries. Outside of Joomla I've never had to do this as I close the mysql connection use the same variable as long as it is in the right order, all is well.
Two questions:
Is this right? Or is there a better way to do this?
Do I need to check for mysql failure of loadResult? How would I go about this. Looking at the Joomla core often I see nothing but sometimes there is a mix of things to handle this.
1) It should work with the same variable name, since you are getting a new query object since your method parameter is set to true. Try calling $query->clear(); just after getting query object
$query = $db->getQuery(true);
$query->clear();
$query->select('app_id');
2) In Joomla 3 it should be something like
try
{
$db->setQuery($query);
$user_id = $db->loadResult();
}
catch (RuntimeException $e)
{
$e->getMessage();
}
And in Joomla 2.5
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
}
Also, change
$user = & JFactory::getUser();
$db = & JFactory::getDBO();
to
$user = JFactory::getUser();
$db = JFactory::getDBO();
Objects are returned by reference anyway in PHP 5, and it will throw a warning since php 5.3+
Well, on Joomla the JFactory::getDBO() always returns the same instance of connection,(at the atual version today) so each time you set the SQL you, in true, are rewriting the previous SQL. In resume this code need multiple connections, and this way dont support, you will need to write your own version of JDatabaseDriver, maybe your own version of a global static array to control your own pool of mysqli connections. PHP is poor about pool connections, isn't as JAVA or .NET, to quick code you will need to think the logic and to try to use only one connection each time, one opened query each time, always think that the JFactory::getDBO() isn't thread safe, take care about this. You never can start one transaction inside one php without commit ou rollback, it causes problems on execution of other pages.

Strange mysql_ multiple connections issue

I'm kinda going crazy about this problem. I can't do it myself so I need the community to help me get this thing solved. I've been spending hours on this because I didn't know where to look. I now know a possible fix but it's just messy (read on). I just need someone who knows more about this than I do.
This is my situation:
I want to use 2 or more mysql connections.
I use OOP
I have a class called dbase, it has two functions, setConnection and getConnection and two class variables called $connection and $dbaseName.
In my main project file I include dbase and create two objects:
dbase
maindbase
then I do:
$this->dbase->setConnection($server, $uname, $pword);
$this->maindbase->setConnection($server, $uname, $pword);
the setConnection function looks like this:
function setConnection ($server, $serv_Username, $serv_Password) {
$this->connection = mysql_connect($server, $serv_Username, $serv_Password, true);
// echo $this->connection . "<BR>";
}
I echo it to see the resourcenumber and added true to mysql_connect (and I know it's deprecated since 5.5, I'm not here for that).
Now, as I understand OOP, the class variables are set per object. So $connection from dbase will never be the same as maindbase (unless, of course, I use the same credentials, but even then it will create a new link because of the $new_link option I enabled). They both have different resource ID's.
My problem:
In class dbase I also have a function which runs a query like this:
$connection = $this->getConnection();
$dbase_name = $this->getDbaseName();
mysql_select_db($dbase_name, $connection);
$q = "SELECT * FROM {$table_name} WHERE {$column} LIKE '{$value}'";
$result = mysql_query($q);
Now, when I use it like this, it will ALWAYS use the FIRST $connection that has been set in class dbase and it doesn't matter which object this is, either object dbase or maindbase.
I get this error:
Table 'testdbase1.skye_domains' doesn't exist
object dbase is connected to testdbase1
object maindbase is connected to testdbase2
the above error I get when trying to select results using the maindbase object.
When I remove the $connection string from mysql_select_db it works perfectly because it will try to open a new connection as if using mysql_connect.
Why is this? This is impossible right? How can objectmaindbase have the same $connection as object dbase? They are in NO WAY connected to eachother... Is PHP somehow using a global mysql_connect variable or buffer which I'm not aware about?
I would like to keep using connectionstrings as this is just handy now and then. Leaving the $connection string out seems messy.
Does anybody have any suggestions I can try to make PHP (or my head) sane again?
Try to put echo $this->connection EVERYWHERE you use it. Also, create an "id" member and fill it with a unique value upon constructing a dbase-object and echo it along the value of $this->connection. This way you can track where what happens to your connection.
And check if there's maybe some place outside of the class that assigns $foo->connection. If you're not using "private" on the members, you're bound to have such problems when you e.g. forget to remove a hack or an experiment from unrelated parts of your code.

Categories