php-general Digest 23 Feb 2011 09:54:23 -0000 Issue 7196

Topics (messages 311527 through 311535):

Re: How to write code: how wrong am I?
        311527 by: Paul M Foster
        311528 by: Alexis
        311529 by: larry.garfieldtech.com

Large binary objects in MySQL - problem
        311530 by: Florin Jurcovici
        311534 by: Tommy Pham

Problems with PDO and LOB columns in mysql
        311531 by: Florin Jurcovici

Dynamically Created Checkboxes
        311532 by: Gary
        311535 by: Pete Ford

Re: Regex pattern for preg_match_all
        311533 by: Tommy Pham

Administrivia:

To subscribe to the digest, e-mail:
        [email protected]

To unsubscribe from the digest, e-mail:
        [email protected]

To post to the list, e-mail:
        [email protected]


----------------------------------------------------------------------
--- Begin Message ---
On Tue, Feb 22, 2011 at 01:29:30PM +0200, Dotan Cohen wrote:

> I wrote a short page on how to actually type of code that one writes,
> it can be found here:
> http://dotancohen.com/howto/write_code.html
> 
> The point that I stress on the page is that first you close an
> element, then you fill it's contents. The page has examples in HTML
> and PHP. I would like to know what the experienced programmers here
> think about this. Am I going about it wrong?

Not a bad idea for HTML, not so great for PHP. Some of what you're
trying to solve/avoid can be handled by a decent editor, one that does
syntax highlighting and/or does brace and parenthesis checking. It
doesn't require an expensive IDE. I use Vim, and it works fine for this.
And honestly, if you're serious about programming, you really shouldn't
be using something like Notepad on Windows. Seriously. We had a coder
working for a company where I was who coded in Word of all things. We
just looked at him like he was crazy.

Annotating end-braces is also very helpful for long conditionals. Vim
can track start and stop braces, but when they span several screen
pages, it can be a problem.

Likewise commenting code as you go is an excellent idea. 2:1 comments
are a bit much; Linus Torvalds would kick your butt. But I often do this
if I'm not exactly sure how I'm going to code something, but I know the
rough logic of it. Lay out the conditionals, comment on what should
happen within each code block, and then go back and fill in the blocks
with actual code.

It's also worth noting that sometimes code is hard to follow. And even
if you're going to be the only one updating it, you may well forget the
logic six months from now. Commenting allows you to recapture that logic
more easily.

And then there's the PHP interpreter. If you make a syntax error, like
failing to add an closing brace, the interpreter will tell you so. If
you spend *enough* time coding, you can usually track down where your
mistakes are relatively easily. If you've ever coded in C, the same is
true for the C compiler. Its behavior is very very similar to that of
the PHP interpreter. It's something you get used to over time as you
code more and more. Also, what could be called "incremental coding" or
"stepwise development" helps: Code a little. Run/compile. Code a little,
run/compile. That way, errors are easier to catch than after you've
written 5000 lines in a file.

Paul

-- 
Paul M. Foster
http://noferblatz.com


--- End Message ---
--- Begin Message ---


On 22/02/11 09:40, Dotan Cohen wrote:
On Tue, Feb 22, 2011 at 16:15, Robert Cummings<[email protected]>  wrote:
If you switch to vertically aligned braces you will have an easier time
matching up open and close braces...

if (something)
{
    // Code here
}

It's trivial to match using this style since you only need to scan one axis.


That bracing style drives me nuts! But I have no problem scanning a
single axis for the close brace and any statement, be it an if, while,
switch, or something else.


Well the way you do it, drives me nuts  :)

Morale of the story, do whatever *you* are most comfortable with..personally I indent as well, has it's downsides I admit, but it's what I've done for the last 20 years and I'm comfortable with it.

Alexis

--- End Message ---
--- Begin Message ---
On 2/22/11 12:04 PM, Alexis wrote:

On 22/02/11 09:40, Dotan Cohen wrote:
On Tue, Feb 22, 2011 at 16:15, Robert Cummings<[email protected]>
wrote:
If you switch to vertically aligned braces you will have an easier time
matching up open and close braces...

if (something)
{
// Code here
}

It's trivial to match using this style since you only need to scan
one axis.


That bracing style drives me nuts! But I have no problem scanning a
single axis for the close brace and any statement, be it an if, while,
switch, or something else.


Well the way you do it, drives me nuts :)

Morale of the story, do whatever *you* are most comfortable
with..personally I indent as well, has it's downsides I admit, but it's
what I've done for the last 20 years and I'm comfortable with it.

Alexis

The most important thing is that you are consistent within a project and within a team. Your entire team should be consistently using one format standard, whatever it is. Failure to do so results in unreadable code, because your brain has to shift gears depending on who wrote a given block of code. That's bad news.

I'd rather see code written in brace-on-own-line style (which I despise) than code that freely switches between that and inline-brace style (my preference) every other for-loop. That's simply unreadable.

--Larry Garfield

--- End Message ---
--- Begin Message ---
Hi.

I use PDO and have written myself a class to abstract the database a bit.

It has a method for querying the database specifically for large
objects, like this:

                $connection = $this->getConnection();   // what's returned is a
PDOStatement, and a transaction is already started
                $statement = $connection->prepare($sql);
                $result = true;
                foreach ($parameters as $key => $parameter)
                        $statement->bindValue($key, $parameter->value, 
$parameter->type);
                try
                {
                        $result = $statement->execute();
                }
                catch(Exception $ex)
                {
                        $statement->closeCursor();
                        throw $ex;
                }
                if (!$result)
                {
                        $statement->closeCursor();
                        throw new Exception("SQL statement failed: ".$sql);
                }
                $data = array();
                $receiverRow = array();
                $i = 0;
                foreach ($columns as $column => $type)
                {
                        $receiverRow[$column] = NULL;   // this is probably not 
necessary, I
added it after it didn't work without, but it didn't help
                        $statement->bindColumn($i++, &$receiverRow[$column], 
$type);
                }
                while ($statement->fetch(PDO::FETCH_BOUND))
                {
                        $row = array();
                        foreach ($columns as $column => $type)
                                $row[$column] = $receiverRow[$column];
                        $data[] = $row;
                }
                $statement->closeCursor();
                return $data;

The problem is, after $statement-> execute() the first fetch returns
false, although there's definitely a record in there -
$statement->rowCount() says 1, if called before $statement->fetch().
No exception is thrown, $statement->errorInfo() and
$statement->errorCode don't contain anything useful.

What am I doing wrong?

br,

flj

-- 
Fine counsel is confusing, but example is always clear. (Edgar A.
Guest, The Light of Faith)

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 1:07 PM, Florin Jurcovici
<[email protected]> wrote:
> Hi.
>
> I use PDO and have written myself a class to abstract the database a bit.
>
> It has a method for querying the database specifically for large
> objects, like this:
>
>                $connection = $this->getConnection();   // what's returned is a
> PDOStatement, and a transaction is already started
>                $statement = $connection->prepare($sql);
>                $result = true;
>                foreach ($parameters as $key => $parameter)
>                        $statement->bindValue($key, $parameter->value, 
> $parameter->type);
>                try
>                {
>                        $result = $statement->execute();
>                }
>                catch(Exception $ex)

Wrong catch? [1]

Regards,
Tommy

[1] http://php.net/pdoexception

>                {
>                        $statement->closeCursor();
>                        throw $ex;
>                }
>                if (!$result)
>                {
>                        $statement->closeCursor();
>                        throw new Exception("SQL statement failed: ".$sql);
>                }
>                $data = array();
>                $receiverRow = array();
>                $i = 0;
>                foreach ($columns as $column => $type)
>                {
>                        $receiverRow[$column] = NULL;   // this is probably 
> not necessary, I
> added it after it didn't work without, but it didn't help
>                        $statement->bindColumn($i++, &$receiverRow[$column], 
> $type);
>                }
>                while ($statement->fetch(PDO::FETCH_BOUND))
>                {
>                        $row = array();
>                        foreach ($columns as $column => $type)
>                                $row[$column] = $receiverRow[$column];
>                        $data[] = $row;
>                }
>                $statement->closeCursor();
>                return $data;
>
> The problem is, after $statement-> execute() the first fetch returns
> false, although there's definitely a record in there -
> $statement->rowCount() says 1, if called before $statement->fetch().
> No exception is thrown, $statement->errorInfo() and
> $statement->errorCode don't contain anything useful.
>
> What am I doing wrong?
>
> br,
>
> flj
>
> --
> Fine counsel is confusing, but example is always clear. (Edgar A.
> Guest, The Light of Faith)
>

--- End Message ---
--- Begin Message ---
Hi.

The code I use to extract the data from a query which was just
performed looks like this:

                $data = array();
                $receiverRow = array();
                $i = 0;
                foreach ($columns as $column => $type)
                        $statement->bindColumn($i++, &$receiverRow[$column], 
$type);
                while ($statement->fetch(PDO::FETCH_BOUND))
                {
                        $row = array();
                        foreach ($columns as $column => $type)
                                $row[$column] = $receiverRow[$column];
                        $data[] = $row;
                }


I know there is a record that fetch should fetch, since $statement->
rowCount() says so. Everything works really well, and even if I check
$statement->errorInfo() and $statement->errorCode() after each
operation with the database, I can see no error. The types with which
the variables are bound are also right.

However, the $statement->fetch() inside the the while statement
returns false at the very first call, so I can't fetch anything from
within the $statement. There is no exception, no non-zero value in
$statement->errorInfo(), and $statement->errorCode() says
uninitialized. So I don't know what actually went wrong.

The entire process happens inside a transaction. At the end, finding
out that the record was not retrieved, the transaction is rolled back.

The statement is an insert following by a select. When calling
PDO::lastInsertId, I get a proper value, which means the insert is
succesful. When checking $statement->rowCount() I also get a count of
1, which means the select also worked properly. I just fail to fetch
the just inserted record into some PHP variables.

What am I doing wrong? As far as I can tell, I did everything as the
manual says.

br,

-- 
Fine counsel is confusing, but example is always clear. (Edgar A.
Guest, The Light of Faith)

--- End Message ---
--- Begin Message ---
I have a script that was working, however I discovered it was only working 
in IE7, not in FF or Chrome. It also has stopped working in IE7 once I put 
it on the remote server.  It is to create checkboxes from data called from 
the db. I have echo'd the mysql_num_row and am getting a result, so the 
query seems to be working.  At this point I get a blank page.  Can someone 
point me in the right direction to get this working (again).

$choice=$_POST['state'];
mysql_select_db($database_assess, $assess_remote);
$query_Recordset1 = ("SELECT * FROM `counties` WHERE state_id = 
'$choice'")or die(mysql_error());
$Recordset1 = mysql_query($query_Recordset1, $assess_remote) or 
die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
   <?php
echo "$totalRows_Recordset1";
echo "$row_Recordset1";
if ( isset($_POST['submit']) ) { // if form is submitted, process it



/////////////////////////////////////////I believe my issue is 
below\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

for($i=1; $i<=$_POST['counties']; $i++) {
if ( isset($_POST["county{$i}"] ) ) {
print $_POST["county{$i}"]." is checked.<br/>";
}
}

} else { // if form isn't submitted, output the form
$county_choice=$_SESSION['county{$1}'];
print "<form action=\"phpForm3.php\" method=\"POST\">\n";

if ($Recordset1) {
print "<table width=200 border=1>\n";

print "<th>&nbsp; </th>\n";
print "<th> State </th>\n"; //2 fields in Counties table, State and County
print "<th> County </th>\n";

print "</tr>\n";
//create table
$i = 0;
while ( $row = mysql_fetch_array($Recordset1) ) {
$i++;
print "<tr>\n";

print "<td><input type=\"checkbox\" name=\"county$i\" 
value=\"$row[name]\"></td>\n";

echo "<td>{$row['state_id']}</td>\n";

echo "<td>{$row['name']}</td>\n";

echo "</tr>\n";

}//end while
print "</table>\n";
} else {
echo("<P>Error performing query: " .
mysql_error() . "</P>");

}
print "<input type=\"hidden\" name=\"counties\" value=\"$i\"/>\n";
print "<input type=\"submit\" name=\"submit\" value=\"Go\"/>\n";
}

?>

Would appriciate your help.

Thank you.
-- 
Gary 



__________ Information from ESET Smart Security, version of virus signature 
database 5897 (20110222) __________

The message was checked by ESET Smart Security.

http://www.eset.com





--- End Message ---
--- Begin Message ---
This bit?

On 22/02/11 22:06, Gary wrote:
for($i=1; $i<=$_POST['counties']; $i++) {
if ( isset($_POST["county{$i}"] ) ) {

You loop over $_POST['counties'] and look for $_POST["county$i"]

I suspect that there is no field 'counties' in your form, so the server is complaining about the missing index - seems likely that the production server
is not showing the error, but instead just giving up on the page.

I think the IE7/Firefox browser difference is a red herring: it wasn't actually working in any browser, or the code changed between tests. Remember, PHP is server side and generates HTML (or whatever). Unless you tell the PHP what browser you are using and write PHP code to take account of that (not generally recommended) then the server output is the same regardless of browser.

--
Peter Ford, Developer                 phone: 01580 893333 fax: 01580 893399
Justcroft International Ltd.                              www.justcroft.com
Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United Kingdom
Registered in England and Wales: 2297906
Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 1XS

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 7:20 AM, Yann Milin <[email protected]> wrote:
> Le 19/02/2011 0:23, Tommy Pham a écrit :
>>
>> @Simon,
>>
>> Thanks for explaining about the [^href].  I need to read up more about
>> greediness.  I thought I understood it but guess not.
>>
>> @Peter,
>>
>> I tried your pattern but it didn't capture all of my new test cases.
>> Also, it captures the single/double quotes in addition to the
>> fragments inside the href.  I couldn't figure out how to modify your
>> pattern to exclude the ', ", and URL fragment from group 1 matches.
>>
>> Below is the new pattern with the new sample test cases that I got it
>> to work.  The new pattern failed only 1 of the non-compliant.
>>
>> $html =<<<HTML
>> <a href=/sample/link>content</a>
>> <a class=link href=/sample/link_extra_attribs title=sample
>> link>content link_extra_attribs</a>
>> <a href='/sample/link_single_quote'>content link_single_quote</a>
>> <a class='link' href='/sample/link_single_quote_pre_attribs'>content
>> link_single_quote_pre_attribs</a>
>> <a class='link' href='/sample/link_single_quote_extra_attribs'
>> title='sample link'>content link_single_quote_extra_attribs</a>
>> <a class='link'
>> href='/sample/link_single_quote_extra_attribs_frag#fragment'
>> title='sample link'>content
>> link_single_quote_extra_attribs_frag#fragment</a>
>> <a class='link'
>> href='/sample/link_single_quote_extra_attribs_query_frag?par=val#fragment'
>> title='sample link'>content
>> link_single_quote_extra_attribs_query_frag?par=val#fragment</a>
>> <a href="/sample/link_double_quote">content link_double_quote</a>
>> <a class="link" href="/sample/link_double_quote_pre_attribs">content
>> link_double_quote_pre_attribs</a>
>> <a class="link"
>> href="/sample/link_double_quote_extra_attribs_frag#fragment"
>> title="sample link">content
>> link_double_quote_extra_attribs_frag#fragment</a>
>> <a class="link"
>> href="/sample/link_double_quote_extra_attribs_nested_tag"
>> title="sample link"><img class="image" src="/images/content.jpg"
>> alt="content" title="content">
>> link_double_quote_extra_attribs_nested_tag</a>
>> <a href="#fragment">content fragment</a>
>> <a class="link" href="#fragment" title="sample link">content fragment</a>
>> <li class="small  tab "><a class="y-mast-link images"
>> href="http://images.search.yahoo.com/images";
>> data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
>> style="padding-left:0em;padding-right:0em;">Images</span></a></li>
>> <li class="small  tab "><a class="y-mast-link video"
>> href="http://video.search.yahoo.com/video";
>> data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
>> style="padding-left:0em;padding-right:0em;">Video</span></a></li>
>> <li class="small  tab "><a class="y-mast-link local"
>> href="http://local.yahoo.com/results";
>> data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
>> style="padding-left:0em;padding-right:0em;">Local</span></a></li>
>> <li class="small  tab "><a class="y-mast-link shopping"
>> href="http://shopping.yahoo.com/search";
>> data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
>> style="padding-left:0em;padding-right:0em;">Shopping</span></a></li>
>> <li class="small lasttab more-tab "><a class="y-mast-link more"
>> href="http://tools.search.yahoo.com/about/forsearchers.html";><span
>> class="tab-cover y-mast-bg-hide">More</span><span
>> class="y-fp-pg-controls arrow"></span></a></li>
>> HTML;
>>
>> $pattern =
>> '%<a[\s]+[^>]*?href\s*=\s*["\']?([^"\'#>]*)["\']?\s?[^>]*>(.*?)</a>%ims';
>>
>> preg_match_all($pattern, $html, $matches);
>>
>> Thanks for your time,
>> Tommy
>
> Hi Tommy,
>
> This is why you shouldn't mix regexes and HTML/XML, especially when you are
> not sure that you are working with valid/consistent html.
> A great/fun answer has been posted on StackOverflow about this at
> http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
>
> You could easily break any regular expressions solution by adding some valid
> comments, see example here :
> http://stackoverflow.com/questions/1357357/regexp-to-add-attribute-in-any-xml-tags/1357393#1357393
>
> You really should consider using a XML parser instead for this kind of job.
>
> Here is a simple sample that matches your example :
>
> <?php
> $oTidy = new tidy();
> $html = $oTidy->repairString($html,array("clean" => true,
> "drop-proprietary-attributes" => true));
> unset($oTidy);
>
> $matches = get_links($html);
>
> function get_links($html) {
>
>    // Create a new DOM Document to hold our webpage structure
>    $xml = new DOMDocument();
>
>    // Load the url's contents into the DOM
>    $xml->loadHTML($html);
>
>    // Empty array to hold all links to return
>    $links = array();
>
>    //Loop through each <a> tag in the dom and add it to the link array
>    foreach($xml->getElementsByTagName('a') as $link) {
>        $links[] = array('url' => $link->getAttribute('href'), 'text' =>
> $link->nodeValue);
>    }
>
>    //Return the links
>    return $links;
> }
> ?>
>
> Regards,
> Yann
>

Hi Yann,

I already have a working code based on DOMDocument+XPath.  But I
wanted to filter out the fragments too in one swoop.  Thus,
preg_match_all came into mind.  With DOMDocument, I'd have to add
check condition.  I've thought about using Tidy for cleaning the
non-compliant pages prior to extraction but I haven't tested Tidy on
its cleaning process.

Thanks,
Tommy

--- End Message ---

Reply via email to