Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
IT Guy
Jan 12, 2010

You people drink like you don't want to live!

bobthecheese posted:

it can't easily and automatically encapsulate the complex relationships between your objects

I have a many-to-many relationship between an entity table and another table that is already a many-to-many lookup table between two entities. I quickly learned that an ORM was going to be more work than just writing queries.

Adbot
ADBOT LOVES YOU

nachos
Jun 27, 2004

Wario Chalmers! WAAAAAAAAAAAAA!

bobthecheese posted:

SQL scares people. This is also why NoSQL (Mongo, Redis, etc.) had a popularity surge recently.

More seriously, the idea is that it's meant to make your code more portable (you could theoretically deploy on any DB engine and the ORM takes care of it), and allow you to build in a more OOP way. The problem is that for a non-trivial system, an ORM just gets in the way because it can't easily and automatically encapsulate the complex relationships between your objects, or even data in a single object.

I don't like them, other than Python's SQLAlchemy, and even then, I use it in a very manual way.

Isn't Doctrine similar to SQLAlchemy? As I understand it, the issue with most ORMs (like Eloquent) is they adopt the ActiveRecord pattern which assumes a 1:1 relationship between models and database tables. SQLAlchemy uses data mapper which lets you separate the many-to-many (as an example) details into a mapper class. Instead of using Eloquent maybe a better idea would be to drop in the Doctrine bundle and use that instead. If I'm wrong let me know, I'm still learning this stuff myself :shobon:

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
ORMs are pure programmer wank.

Alex007
Jul 8, 2004

Also, say goodbye to performance, and then you are hosed because you can't optimize the queries.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Fluent (the query builder) also seems to be pretty bad.

php:
<?
    public static function get_operator_records($branch_id)
    {
        $records = DB::table('record')
            ->join('facility', 'record.facility_id', '=', 'facility.id')
            ->join('branch', 'facility.branch_id', '=', 'branch.id')
            ->join('category', 'record.category_id', '=', 'category.id')
            ->join('commodity', 'record.commodity_id', '=', 'commodity.id')
            ->join('variety', 'record.variety_id', '=', 'variety.id')
            ->join('user', 'record.user_id', '=', 'user.id')
            ->where('branch.id', '=', $branch_id)
            ->order_by('record.created_at', 'desc')
            ->get(array(
                'record.id',
                'branch.name as branch',
                'facility.name as facility',
                'category.name as category',
                'commodity.name as commodity',
                'variety.name as variety',
                'user.full_name as user',
                'record.status',
                DB::raw('DATE_FORMAT(`date`, "%M, %D") AS `date`'),
                DB::raw('DATE_FORMAT(`start`, "%l:%i %p") AS `start`'),
                DB::raw('DATE_FORMAT(`end`, "%l:%i %p") AS `end`')
            ));

        $classes = array(
            'approved' => 'success',
            'pending' => 'warning',
            'void' => 'error'
        );

        foreach ($records as $record)
        {
            $record->status = ($record->status && $record->status != 'open') ? ' class="' . $classes[$record->status] . '"' : '' ;
        }

        return $records;
    }
?>
Fluent goes through all the work to return an array of objects, which I then have to loop through again to do any formatting on the data before passing it to the view to then be looped again to be output.

I supposed I could format any data while looping it in the view, but that gets messy as gently caress, especially when you're applying formatting to more than one column compared to my example.

I'm using Fluent for now so that I can get this app rolled out as fast as possible. I will likely come back when the application is finished and rewrite the queries using raw SQL and optimizing the speed of the queries.

IT Guy fucked around with this message at 03:50 on Jan 16, 2013

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
I get frustrated very quickly with query builders that make you write most of the SQL anyway. I can write raw SQL much faster than I can figure out the code interfaces, and it only seems to come in handy when you need to write something dynamic that occasionally loads extra tables or filters on your base query.

Anyway, enough about your problems, let's talk about mine!

I have a client request where they would like to be able to build their own custom data exports in our PHP application via an SQL-like.
To go into more details, they want to be able to write a large number of flexible but simple queries, returning data in the same format every time - essentially just writing the WHERE, LIMIT, GROUP and ORDER portions. For anyone who's used Jira in the past, we're basically talking about a PHP version of JQL-type interface which is a simplified version of SQL.

The big draw for the client is that the DB structure is flattened, so they can do a query like "username = derek" to get all reports by derek, and not have to set their own joins or know the table "users" contains the field "username".

I understand the pitfalls and :can: this kind of thing can result in, but it's a pretty specific request from our client for a reasonable purpose, so I'd like to be able to deliver. Has anyone heard of a library for PHP which can do this already? I'm not opposed to rolling my own, but I'd rather not have to if a library exists.

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
edit: Ignore this. Was having major issues getting Zend2 working on Shared Hosting but the issues stemming from lack of documentation seem fundamental so I'm deleting it and not gonna bother

Sulla Faex fucked around with this message at 08:54 on Jan 16, 2013

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

v1nce posted:

I get frustrated very quickly with query builders that make you write most of the SQL anyway. I can write raw SQL much faster than I can figure out the code interfaces, and it only seems to come in handy when you need to write something dynamic that occasionally loads extra tables or filters on your base query.

Anyway, enough about your problems, let's talk about mine!

I have a client request where they would like to be able to build their own custom data exports in our PHP application via an SQL-like.
To go into more details, they want to be able to write a large number of flexible but simple queries, returning data in the same format every time - essentially just writing the WHERE, LIMIT, GROUP and ORDER portions. For anyone who's used Jira in the past, we're basically talking about a PHP version of JQL-type interface which is a simplified version of SQL.

The big draw for the client is that the DB structure is flattened, so they can do a query like "username = derek" to get all reports by derek, and not have to set their own joins or know the table "users" contains the field "username".

I understand the pitfalls and :can: this kind of thing can result in, but it's a pretty specific request from our client for a reasonable purpose, so I'd like to be able to deliver. Has anyone heard of a library for PHP which can do this already? I'm not opposed to rolling my own, but I'd rather not have to if a library exists.

So basically you join up all tables in to one giant mother table, which then gets paired down by user-supplied select/where/group/order/limit keys? That doesn't really require a big frameworky type thing, you can build your own little sql builder to do that.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
Let's talk templating engines!

So I've got a new project coming up which has to be able to be deployed to a large number of (probably lovely) PHP hosts with minimum of effort. I also want it to be pretty easily skinnable.

I want it to run pretty quickly, and with a very small footprint, so I want to avoid a full framework. It will be a small application (a single public page, a few management pages, and an API), and I don't want to bring down a massive amount of code for that.

In terms of templating engines:
* PHPTAL - I really love PHPTAL, but it is, unfortunately, very slow. You also have to build a template acquisition layer in front of it first. The templates involve absolutely no PHP conditionals, and can (with relative ease) be ported over to any other TAL-based system. The templates are XML-based, so the output is generally considered to be xhtml compliant (html5 syntax isn't necessarily XML compliant, though)

* Smarty - I really dislike Smarty. It is/was the "industry standard" for a long time, but that doesn't actually make it any good. It's still slower than I would generally like (but faster than PHPTAL). The templates are still too much like PHP for my liking.

* The embarrassingly lovely templating engine I built for Blogfile - It's very fast, and doesn't care if your templates are complete HTML chunks or not - it simply doesn't give a poo poo. It's pretty bad, but it served it's purpose. There is, however, no conditionals built into it or anything. You have to write PHP code with an awareness of "slots" available in the templates. I'm not really considering using it for this (I have used it in one or two other things. I felt dirty. I extended it a bit for them, though), but I really want something which lets people define basic HTML, and have it run fast.

* Raw PHP templates - well, it has the fast part... but not exactly what I'm looking for. I want to be able to separate display and business logic entirely.

Anyway, what are your suggestions for templating engines that meet my needs/wants/desires?

Please don't suggest I use a full framework. I don't need one. I just need a templating engine.

Communist Bear
Oct 7, 2008

Nevermind, wrong thread.

Communist Bear fucked around with this message at 13:22 on Jan 16, 2013

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

WMain00 posted:

EDIT: Come to think of it, am I in the right thread? Or should I post this in web design instead?

:ohdear:

I think that there's actually a Wordpress thread which would probably be the most appropriate place to post.

Communist Bear
Oct 7, 2008

bobthecheese posted:

I think that there's actually a Wordpress thread which would probably be the most appropriate place to post.


Ahh. So there is. Sorry about that! :)

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

bobthecheese posted:

Anyway, what are your suggestions for templating engines that meet my needs/wants/desires?

I don't really use templating engines, I've hosed around with Smarty a few times and I'm currently messing around with Blade which is built into Laravel. That being said, I've never used this but it gets all kinds of recommendations and buzz from what I've experienced. Anyway, check out Twig.

SimonNotGarfunkel
Jan 28, 2011
Any of you had experience using gzip, because I'm totally lost?

I'm just playing around with a Netflix Library for CodeIgniter which I downloaded.

I can pull back individual titles and other stuff but I can't figure out how to pull back the entire catalogue.

I'm calling this:

php:
<?
    /**
     * Retrieve a complete index of all instant-watch titles in the Netflix catalog
     *
     * @param array $params (optional) Additional parameters. See the netflix API reference for details
     **/
    public function all_titles_new(array $params = array())
    {
        $parstr = empty($params) ? '' : '?'.http_build_query($params);
        //Request that the response be gzipped because it will be massive
        $this->_header['Accept-encoding'] = 'gzip';
        $response = $this->_response_request("catalog/titles/full{$parstr}");
        //Reset the encoding for normal use.
        $this->_header['Accept-encoding'] = 'identity';
        return $response;
    }
?>
But I haven't got a clue what to actually do with $response. Is there a way to dump it to an XML file?

If I print() it or echo it it just outputs garbage.

Other code that might be useful to you...

php:
<?
 private $_header = array(
        'Host'=>self::HOST,
        'Connection'=>'close',
        'User-Agent'=>'CodeIgniter',
        'Accept-encoding'=>'identity'
    );

  private function _response_request($uri, $method = 'GET')
    {
        $request = "{$method} {$uri} HTTP/".self::HTTP_1.self::LINE_END;
        $url = self::SCHEME.'://'.self::HOST.'/'.$uri;
        
        $header = $this->_build_header($url, $method, $request, self::LINE_END);
        
        $response = $this->_connect($url, $header, $method, false);
        return $response;
    }
    
private function _build_header($url, $method, $prepend, $append, $overwrite = array())
    {
        $str = $prepend === false ? '' : $prepend;
        foreach($this->_header AS $key=>$value)
        {
            if(array_key_exists($key, $overwrite))$str .= $key.': '.$overwrite[$key].self::LINE_END;
            else $str .= $key.': '.$value.self::LINE_END;
        }
        $str .= get_auth_header($url, $this->_consumer['key'], $this->_consumer['secret'], $this->_access, $method, $this->_consumer['algorithm']);
        $str .= $append === false ? '' : $append;

        return $str;
    }

private function _connect($url, $header, $request, $postdata = false)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
        curl_setopt($ch, CURLOPT_SSLVERSION,3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
        curl_setopt($ch, CURLOPT_HTTPHEADER, explode(self::LINE_END, $header));
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);

        if(is_array($postdata))curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        
        $response = curl_exec($ch);
        
        echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
        
        if(self::DEBUG)
        {
            error_log(curl_getinfo($ch, CURLINFO_HEADER_OUT));
            error_log($response);
        }
        
        curl_close($ch);
        return $response;
    }
?>
I can't find much information on gzip at all so any help would be appreciated.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

bobthecheese posted:

* Raw PHP templates - well, it has the fast part... but not exactly what I'm looking for. I want to be able to separate display and business logic entirely.

You can do that. Easily. Just put the display logic in separate files and include() them. A common pattern is to write a simple wrapper object with the template file name given in the constructor, set random-rear end properties, then have a method that does the include. The included file gets the variable context of the function that called it, so it gets $this and all the random-rear end properties that you set.

The only reason you would ever "need" a template engine in PHP is if either A) you need to expose the templates to people that can/will not learn PHP, or B) you want to make sure that templates are sandboxed and nothing PHP-malicious could get in easily.

Also take a look at twig. It's written by some really smart people and I'd trust it more than smarty.

SimonNotGarfunkel
Jan 28, 2011
Ignore my last post.

It turns out I was getting too hung up on gzip when it was actually the curl stuff I needed to get to grips with.

I just needed to call curl_getinfo() and redirect to the redirect_url to download the catalog.

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
I'm reading up on MVC now. Is it possible to automaticllay create model classes based on Database structures? Or do you just manually create the classes based on the DB tables and any changes in either have to be tracked and updated manually?

McGlockenshire
Dec 16, 2005

GOLLOCKS!
The thing you're talking about is usually taken care of by ORMs. See the past page or two for relevant discussion.

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
I've read through it and it seems like ORMs are not worth the hassle. Is it a feature worth establishing purely for its own sake, i.e. coding your own DB->class set up, or do people find that its far simpler just to set up the classes manually and that changes are few and far enough inbetween not to cause issues?

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
ORMs are prized by people who are afraid of SQL.

They would have a use if you're just interested in putting out quick and nasty sites, so you have one less thing to worry about, but manually building your table structure and queries gives you much better control.

newberstein
Jul 17, 2005
really....that bad
Hi All,

I am quite new to AJAX(and web development in general), and have ran into a bit of a problem. I am using jQuery to post data from a link click, and then use PHP to update a table in MySQL. Using Firebug, I can see that the data is indeed posting, but my update is not working. I think it is possible that my PHP isn't even executing. Is something glaringly wrong with my PHP, or should I take another look at the jQuery?

This part is working...
code:
   function performAjaxSubmission() {
        $.ajax({
          url: 'likedislike.php',
          type: 'POST',
          data: {
		action: 'save',
		db_field: $(this).attr("db_field"),
		db_id: $(this).attr("db_id")
		},
          success: function() {
            alert("success!");
          }
		});
      return false;
	  }
	  
	  jQuery(document).ready(function() {
	  $(".votes").click(performAjaxSubmission);
	  });
But this doesn't.
php:
<?php
session_start();

$dsn 'mysql:host=localhost;dbname=blah_db';
$username 'root';
$password '';


$con = new PDO($dsn,$username,$password);
  
$field $_POST['db_field'];
$blah_id $_POST['db_id'];
   
$query $con->prepare("UPDATE blah SET ? = ? + 1 WHERE blah_id = ?");
$query->bindParam(1$field);
$query->bindParam(2$field);
$query->bindParam(3$blah_id);
$query->execute();

$con null;
?>

newberstein fucked around with this message at 04:44 on Jan 21, 2013

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Configure PDO to actually complain and make sure you have the php.ini display_errors directive enabled.

It's very likely that you have an SQL syntax error where you're trying to use placeholders for column names. Placeholders are intended for data, not identifiers. If you're in emulated mode (the default), PDO actually replaces the question marks with quoted string literals. The quotes and escaping rules for identifiers are way, way different than those needed for data, so the result is a syntax error. If you're using native mode (not the default), then MySQL will be complaining about its inability to do the same thing server-side.

If you need user-selectable column names, provide a whitelist of the column names in the script and verify that the user input matched before continuing. It's then safe to to SQL string concatenation

newberstein
Jul 17, 2005
really....that bad

McGlockenshire posted:

Configure PDO to actually complain and make sure you have the php.ini display_errors directive enabled.

It's very likely that you have an SQL syntax error where you're trying to use placeholders for column names. Placeholders are intended for data, not identifiers. If you're in emulated mode (the default), PDO actually replaces the question marks with quoted string literals. The quotes and escaping rules for identifiers are way, way different than those needed for data, so the result is a syntax error. If you're using native mode (not the default), then MySQL will be complaining about its inability to do the same thing server-side.

If you need user-selectable column names, provide a whitelist of the column names in the script and verify that the user input matched before continuing. It's then safe to to SQL string concatenation

Thank you for your reply.

I added the try, catch as described in the link. My new question is: how can I see the error message? From what I understand (and see) the jQuery doesn't redirect to the PHP page, merely runs the script therein.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

newberstein posted:

Thank you for your reply.

I added the try, catch as described in the link. My new question is: how can I see the error message? From what I understand (and see) the jQuery doesn't redirect to the PHP page, merely runs the script therein.

Here is an example setup I have on my sites:

/inc/db.inc.php
php:
<?
    define('DB_SERVER', '127.0.0.1');
    define('DB_NAME', 'name');
    define('DB_USER', 'user');
    define('DB_PASS', 'password');

    try
    {
        $pdo = new PDO('mysql:host=' . DB_SERVER . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->exec("SET NAMES 'utf8'");
    }
    catch (PDOException $e)
    {
        $error = '<strong>Unable to connect to the database server</strong>: ' . $e->getMessage();
        include $_SERVER['DOCUMENT_ROOT'] . '/inc/error.html.php';
        exit();
    }
?>
index.php
php:
<?
    include $_SERVER['DOCUMENT_ROOT'] . '/inc/db.inc.php';

    try
    {
        $sql = "SELECT COUNT(*)
                FROM `records`
                WHERE `facility_id` = :facility";
        $q = $pdo->prepare($sql);
        $q->bindValue(':facility', $facility_id);
        $q->execute();
    }
    catch (PDOException $e)
    {
        $error = '<strong>SQL Error</strong>: ' . $e->getMessage();
        include $_SERVER['DOCUMENT_ROOT'] . '/inc/error.html.php';
        exit();
    }
?>
If my query errors then it will include my error template/view which echos the $error variable and then exits the script.

Does this answer your question?

IT Guy fucked around with this message at 17:17 on Jan 21, 2013

newberstein
Jul 17, 2005
really....that bad

IT Guy posted:

Here is an example setup I have on my sites:

/inc/db.inc.php
php:
<?
    define('DB_SERVER', '127.0.0.1');
    define('DB_NAME', 'name');
    define('DB_USER', 'user');
    define('DB_PASS', 'password');

    try
    {
        $pdo = new PDO('mysql:host=' . DB_SERVER . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->exec("SET NAMES 'utf8'");
    }
    catch (PDOException $e)
    {
        $error = '<strong>Unable to connect to the database server</strong>: ' . $e->getMessage();
        include $_SERVER['DOCUMENT_ROOT'] . '/inc/error.html.php';
        exit();
    }
?>
index.php
php:
<?
    include $_SERVER['DOCUMENT_ROOT'] . '/inc/db.inc.php';

    try
    {
        $sql = "SELECT COUNT(*)
                FROM `records`
                WHERE `facility_id` = :facility";
        $q = $pdo->prepare($sql);
        $q->bindValue(':facility', $facility_id);
        $q->execute();
    }
    catch (PDOException $e)
    {
        $error = '<strong>SQL Error</strong>: ' . $e->getMessage();
        include $_SERVER['DOCUMENT_ROOT'] . '/inc/error.html.php';
        exit();
    }
?>
If my query errors then it will include my error template/view which echos the $error variable and then exits the script.

Does this answer your question?

Yes! Thank you!

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
After debating for a couple of months, we're about to settle on using CakePHP. The other contender was Symfony, but only one of our three developers really has framework experience and it's with Cake, and that seems much easier than Symfony to pick up. Is this a bad decision or, honestly, does it not really matter, and all that matters is What Feels Right?

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

Golbez posted:

After debating for a couple of months, we're about to settle on using CakePHP. The other contender was Symfony, but only one of our three developers really has framework experience and it's with Cake, and that seems much easier than Symfony to pick up. Is this a bad decision or, honestly, does it not really matter, and all that matters is What Feels Right?

It doesn't look like Cake supports any new PHP features like namespaces or traits (or rather, doesn't use them). I think it's still a very old codebase like Code Ignighter. Also, it doesn't use Composer for vendors. None of the code follows any of the PSR-0, PSR-1, PSR-2, or PSR-3 standards.

I am probably biased toward Symfony2 (don't use Symfony1 it's bad) but I think I'd stay away from Cake. Checkout the newer frameworks like Symfony2, Laravel, or.. I can't think of newer ones. Zend 2 maybe?

SimonNotGarfunkel
Jan 28, 2011
CodeIgniter continues to own.

I just realised you can stick a $this->db->trans_start() at the beginning of a bunch of queries, regardless of whether they're in different models or whatever and it'll automatically rollback/commit on fail/success.

So for instance I've got an article_model which is created and the article_id returned. I then use this article_id to create a bunch of article_tags in article_tag_model and it takes care of the transactions for me.

Probably standard stuff but I'm still getting the hang of frameworks. :3:

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

After debating for a couple of months, we're about to settle on using CakePHP. The other contender was Symfony, but only one of our three developers really has framework experience and it's with Cake, and that seems much easier than Symfony to pick up. Is this a bad decision or, honestly, does it not really matter, and all that matters is What Feels Right?

If you're stuck with Cake, at least make sure it's 2.x. 1.x is basically PHP4 code and should never be used. Ever.

As others have said, as far as awesomeness is concerned, Symfony 2 is currently the crownholder.

Crop Top Skank
Apr 4, 2007

I've used Symfony2 for three projects now, one of them a ticketing system and another an AJAX budgeting app and I'm definitely liking it more and more. It's surprising how well suited it is to a wide range of tasks. The only thing is that it's best if you're using APC or another bytecode cache to help speed things up on the production side.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
I know Symfony 2 is awesome, but the learning curve seems to be steep enough that we'll be toying with it for months before actually converting our site to it. Is it really worth the curve? Whereas with Cake we could probably hop right in and start moving things in.

My only experience with frameworks before this was Zend 1, and that was four years ago, then I spent 2 years here having to unlearn my meager knowledge because the lead programmer hated objects and frameworks. So I'm stumbling in the dark here.

Golbez fucked around with this message at 15:51 on Jan 22, 2013

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
Try this:

code:
curl -s https://getcomposer.org/installer | php
php composer.phar create-project symfony/framework-standard-edition symfony2/ 2.1.7

cd symfony2
php app/console server:run
Go to http://localhost:8000/. Go from there. Eventually tear your hair out with Doctrine.

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.

Golbez posted:

I know Symfony 2 is awesome, but the learning curve seems to be steep enough that we'll be toying with it for months before actually converting our site to it. Is it really worth the curve? Whereas with Cake we could probably hop right in and start moving things in.

My only experience with frameworks before this was Zend 1, and that was four years ago, then I spent 2 years here having to unlearn my meager knowledge because the lead programmer hated objects and frameworks. So I'm stumbling in the dark here.

If you want to have clean, future-compatible code, then yes. It's worth the curve.

Disclaimer: I've never used symphony, but I have used cake, and it's pretty horrible.

Adraeus
Jan 25, 2008

by Y Kant Ozma Post
I don't know how to articulate this, so I can't search for it...

How do I create a form element that the user can create more of? For example, let's say you were editing your user profile and you want to add more than one website address to your profile. You'd click the + button next to the field and another website field would appear.

Now that I write that out, would I basically store the various website field values as an array into a single entry in the database and then display the form elements based on whether there is more than one website?

The Gripper
Sep 14, 2004
i am winner
I think if you make multiple inputs with the same name, PHP will create an array from the $_GET or $_POST vars where duplicates are available. So really all you'd need to do is duplicate an <input ...> </input> block with the same name and submit away.

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

The Gripper posted:

I think if you make multiple inputs with the same name, PHP will create an array from the $_GET or $_POST vars where duplicates are available. So really all you'd need to do is duplicate an <input ...> </input> block with the same name and submit away.

Close. If they have the same name, the value in $_GET/$_POST will simply be the last one received; but if you bracket the end of it (e.g., <input type="text" name="website[]" />), all the values will be appended to an array.

php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    print_r($_POST);
}
?>
<form action="" method="post">
    <input type="hidden" name="foo" value="one" />
    <input type="hidden" name="foo" value="two" />
    <input type="hidden" name="bar[]" value="one" />
    <input type="hidden" name="bar[]" value="two" />
    <input type="submit" value="Post" />
</form>
code:
Array
(
    [foo] => two
    [bar] => Array
        (
            [0] => one
            [1] => two
        )

)

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

Adraeus posted:


Now that I write that out, would I basically store the various website field values as an array into a single entry in the database and then display the form elements based on whether there is more than one website?

I'm not sure if I read that correctly, but no, you should store the addresses in its own table in the database and link it with the user's id as the foreign key.

Example:

code:
User Table
id  |  name  |  other poo poo

Address Table
id  |  address  |  city  |  zip  |  user_id

SimonNotGarfunkel
Jan 28, 2011
This man is right. You'd have a separate table and a one-to-many relationship.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Oh wow, I didn't read that right, you're talking about URLs and I saw street addresses. However, the same thing applies, store the websites in its own table.

Adbot
ADBOT LOVES YOU

Adraeus
Jan 25, 2008

by Y Kant Ozma Post
Why would a single table be a bad idea?

code:
User Table
id  |  fname  |  lname  |  address  |  city  |  zip  |  phone  |  website  |  etc.
I was thinking of just storing multiple values as an array, like so:

code:
User Table
id  |  fname  |  lname  |  address            |  website      |
1   |  John   |  Smith  |  1234 Columbus, OH  |  www,www,www  |
I suppose having separate tables would be easier to manage though. Any other reasons?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply