Problem when posting into the DB

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

48 Replies - 852 Views - Last Post: 15 July 2013 - 05:40 AM Rate Topic: -----

#1 Yeronox  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 102
  • Joined: 12-March 12

Problem when posting into the DB

Posted 14 July 2013 - 11:37 AM

So, here`s another challenge after switching to PDO.
I need to post into the DB the user`s details.
include_once 'db.php';
	function user_register($email, $name, $password)
	{
		$pass_md5 = md5($password);
		query('INSERT INTO users(email, name, password) values(:email, :name, :password)',
				array( 'email'		=> $email,
					   'name'		=> $name,
					   'password'	=> $pass_md5),
				$conn
			);

	}

	$config = array(
			'username' => 'root',
			'password' => ''
		);


	function query($query, $binding, $conn)
	{
		$stm = $conn->prepare($query);
		$stm->execute($binding);
		return ($stm->rowCount()>0) ? $stm : false;
	}

Any idea?
And by the way, I read I can use mysql_* functions using mysqli_* and it is safer and supported, is it true?

This post has been edited by Yeronox: 14 July 2013 - 11:38 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Problem when posting into the DB

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10561
  • View blog
  • Posts: 39,071
  • Joined: 27-December 08

Re: Problem when posting into the DB

Posted 14 July 2013 - 11:43 AM

What specific problems or errors are you encountering?

Also, MD5 is a poor hash function to use. Pick something more modern and secure like Sha512. See the hash() function docs for more details.

Quote

And by the way, I read I can use mysql_* functions using mysqli_* and it is safer and supported, is it true?

You still want to use prepared statements with MySQLi. You shouldn't just blindly switch and replace mysql with mysqli. There are some mysqli functions that are deprecated or on the chopping board as well. Make sure to read up before using something.
Was This Post Helpful? 1
  • +
  • -

#3 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: Problem when posting into the DB

Posted 14 July 2013 - 11:46 AM

Hello there! When it comes to PDO what I would do is put your database stuff (such as the connection) in a static class like this..
<?php
	class DB
	{
		private static function getDB()
		{
			if (self::$connection === null)
				self::$connection = new PDO(DATABASE_DSN, DATABASE_USER, DATABASE_PASSWORD);

			return self::$connection;
		}

		public static function prepare($query)
		{
			return self::getDB()->prepare($query);
		}

		private static $connection;
	}
?>

Somewhere you will need to define the constants for your DSN, username and password, which would look something like this.
define('DATABASE_DSN', 'mysql:host=localhost;dbname=mydatabase');
define('DATABASE_USER', 'mydbuserbame');
define('DATABASE_PASSWORD', 'mydbpassword');

This means you won't be passing the connection through each time like you are, and you will be able to create queries like this..
<?php
	function user_register($email, $name, $password)
	{
		$query = DB::prepare('INSERT INTO users (email, name, password) VALUES(:email, :name, :password)');
		$query->bindValue(':email', $email);
		$query->bindValue(':name', $name);
		$query->bindValue(':password', md5($password));
		$query->execute();
	}
?>

Obviously you can work in the row-count feature you have there (I've just thrown this together as an example. You will also want to stray away from MD5 for storing passwords and look towards using the PHP crypt() function. What is the error you are experiencing anyway, or the 'challenge'?
Was This Post Helpful? 2
  • +
  • -

#4 nandureddy  Icon User is offline

  • D.I.C Head

Reputation: 28
  • View blog
  • Posts: 129
  • Joined: 31-January 11

Re: Problem when posting into the DB

Posted 14 July 2013 - 11:55 AM

View Postmacosxnerd101, on 14 July 2013 - 12:43 PM, said:

Quote

And by the way, I read I can use mysql_* functions using mysqli_* and it is safer and supported, is it true?

You still want to use prepared statements with MySQLi. You shouldn't just blindly switch and replace mysql with mysqli. There are some mysqli functions that are deprecated or on the chopping board as well. Make sure to read up before using something.

Refer to this mysqli summary on php.net.

This post has been edited by nandureddy: 14 July 2013 - 11:56 AM

Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3462
  • View blog
  • Posts: 11,729
  • Joined: 12-December 12

Re: Problem when posting into the DB

Posted 14 July 2013 - 11:59 AM

Yes, we need details about the problem you are having, but a brief look suggest $conn is not in scope in your function user_register() (doesn't have a value at this point).

FWIW I wouldn't name the function query(), it would only confuse me. Be a little more imaginative!

This post has been edited by andrewsw: 14 July 2013 - 12:00 PM

Was This Post Helpful? 0
  • +
  • -

#6 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: Problem when posting into the DB

Posted 14 July 2013 - 12:10 PM

View Postandrewsw, on 14 July 2013 - 07:59 PM, said:

FWIW I wouldn't name the function query(), it would only confuse me. Be a little more imaginative!


function flyingUnicornPigs() { }

Totally legitimate. :)
Was This Post Helpful? 0
  • +
  • -

#7 Yeronox  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 102
  • Joined: 12-March 12

Re: Problem when posting into the DB

Posted 14 July 2013 - 12:24 PM

Thanks for the replies :)/>/>
So, the problem is that it doesn`t post anything to the DB.
Here are the new codes, thanks to your posts.
function user_register($email, $name, $password)
	{
		$pass_hash = hash("sha512",$password);
		$query = DB::prepare('INSERT INTO users (email, name, password) VALUES(:email, :name, :password)');
		$query->bindValue(':email',$email);
		$query->bindValue(':name',$name);
		$query->bindValue(':password',$pass_hash);
		$query->execute();
	}

	class DB
	{
		private static function getDB()
		{
			if (self::$connection === null)
				self::$connection = new PDO(DATABASE_DSN, DATABASE_USER, DATABASE_PASSWORD);

			return self::$connection;
		}

		public static function prepare($query)
		{
			return self::getDB()->prepare($query);
		}

		private static $connection;

		public static function connect()
		{
			return DB::getDB();
		}
	}

I made that connect() function to check if the connection was made via $conn = DB::connect();

View PostKruithne, on 14 July 2013 - 06:46 PM, said:

What is the [...], or the 'challenge'?


Well, I studied C++ for some weeks but it was my first language and I was alone, so I had to quit (almost an year ago).
Now I am trying to learn PHP by myself and I`ve finished a video tutorial from a website (I don`t know if I can say it`s name, anyway a site where there are premium tutorials) about PHP (the course was called "PHP fundamentals") and I am trying to follow a tutorial on how to make an image upload website, like dropbox for images.
It`ll be long but I`m trying to learn and code by myself everyday!

This post has been edited by Yeronox: 14 July 2013 - 12:30 PM

Was This Post Helpful? 0
  • +
  • -

#8 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2983
  • Posts: 10,313
  • Joined: 08-August 08

Re: Problem when posting into the DB

Posted 14 July 2013 - 12:34 PM

I could be wrong, but I don't think you can return a copy of the connection. You want a reference to it. I think I'd make the connection an attribute and use $this->connection; or I'd pass a reference to the method.
Was This Post Helpful? 0
  • +
  • -

#9 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: Problem when posting into the DB

Posted 14 July 2013 - 12:46 PM

return DB::getDB(); is technically not right, because you are referencing it from inside the DB class so it would just be self::getDB(); however that is just acting as a return-through method, so you might as well make getDB public. That being said, simply returning the connection won't really check if the connection has been established, you will need to catch an exception on the connection attempt after setting the error mode to exception!
Was This Post Helpful? 0
  • +
  • -

#10 Yeronox  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 102
  • Joined: 12-March 12

Re: Problem when posting into the DB

Posted 14 July 2013 - 12:58 PM

	class DB
	{
		public static function getDB()
		{
			if (self::$connection === null)
				self::$connection = new PDO(DATABASE_DSN, DATABASE_USER, DATABASE_PASSWORD);

			return self::$connection;
		}

		public static function prepare($query)
		{
			return self::getDB()->prepare($query);
		}

		private static $connection;

		try {
			$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			return $connection;
		} catch (Exception $e) {
			return false;
		}
	}


	include 'func/db.func.php'; // db connection
	$conn = DB::getDB();
	if(!$conn) die('');

Was This Post Helpful? 0
  • +
  • -

#11 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10561
  • View blog
  • Posts: 39,071
  • Joined: 27-December 08

Re: Problem when posting into the DB

Posted 14 July 2013 - 12:59 PM

Okay... Is there a question?
Was This Post Helpful? 0
  • +
  • -

#12 Yeronox  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 102
  • Joined: 12-March 12

Re: Problem when posting into the DB

Posted 14 July 2013 - 01:02 PM

Yeah, sorry, I was editing the post as I accidentally forgot to write the things.
So, first of all with the last posted code I get:
Parse error: syntax error, unexpected 'try' (T_TRY), expecting function (T_FUNCTION) on line 28
Then, I still need to figure out why it doesn`t post my data to the DB :(
Was This Post Helpful? 0
  • +
  • -

#13 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: Problem when posting into the DB

Posted 14 July 2013 - 01:11 PM

You've got code just randomly floating inside your static class, that's bad! Let's rework that DB file just a little..
class DB
{
	// Made this private again, really shouldn't call this outside the DB wrapper.
	private static function getDB()
	{
		if (self::$connection === null)
		{
			try
			{
				// Correctly placed the settings array in the PDO constructor.
				self::$connection = new PDO(
					DATABASE_DSN,
					DATABASE_USER,
					DATABASE_PASSWORD,
					array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
				);
			}
			catch (PDOException $e)
			{
				die($e->getMessage()); // We failed, die with the message.
				// This should be correctly handled by an error handler in production code.
			}
			return self::$connection;
		}

	public static function prepare($query)
	{
		return self::getDB()->prepare($query);
	}

	private static $connection;
}

Basically, no need to check if the connection has failed, when you try to query you will get an error (which you should handle correctly).
Was This Post Helpful? 0
  • +
  • -

#14 Yeronox  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 102
  • Joined: 12-March 12

Re: Problem when posting into the DB

Posted 14 July 2013 - 01:15 PM

Should the "prepare()" function be public?
I get this error: Parse error: syntax error, unexpected 'public' (T_PUBLIC)
And I've deleted those lines
$conn = DB::getDB();
	if(!$conn) die('');

Was This Post Helpful? 0
  • +
  • -

#15 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: Problem when posting into the DB

Posted 14 July 2013 - 01:19 PM

I missed the bottom bracket out of the getDB() function, see corrected below.
private static function getDB()
{
	if (self::$connection === null)
	{
		try
		{
			// Correctly placed the settings array in the PDO constructor.
			self::$connection = new PDO(
				DATABASE_DSN,
				DATABASE_USER,
				DATABASE_PASSWORD,
				array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
			);
		}
		catch (PDOException $e)
		{
			die($e->getMessage()); // We failed, die with the message.
			// This should be correctly handled by an error handler in production code.
		}
		return self::$connection;
	}
}

Yes, the prepare function should be left public as that is how you create queries. With the DB wrapper like that, creating a query on your website is a simple as..
$query = DB::prepare('SELECT cost FROM fish WHERE cheese = :value');
$query->bindValue(':value', 'chips');
$query->execute();

while ($row = $query->fetchObject())
{
	// In this scope, each iteraction, $row will be another row with a cost value.
	echo $row->cost;
}

This post has been edited by Kruithne: 14 July 2013 - 01:19 PM

Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »