SitePoint Sponsor

User Tag List

Results 1 to 13 of 13
  1. #1
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    echo strips away some tags

    PHP Code:
    foreach($array as $value) {
      echo 
    '<div id="data">
        <p>Some text</p>
      </div>'
    ;

    This code prints out the following (supposing that $array's length is 2):

    Code:
    <p>Some text</p>
    <div id="data">
      <p>Some text</p>
    </div>
    Instead of

    Code:
    <div id="data">
      <p>Some text</p>
    </div>
    <div id="data">
      <p>Some text</p>
    </div>
    Why is this happening?

  2. #2
    SitePoint Evangelist hessodreamy's Avatar
    Join Date
    Apr 2005
    Location
    uk
    Posts
    525
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Looks ok to me, and products the desired output. Perhaps post more code? what's the content of the array? What are you using to check the html output?
    Note that your php code does not output a line break either at the end or the beginning of the loop. Putting a line break in will probably make your output more readable and easier to debug.
    ie
    Code:
    foreach($array as $value) { 
      echo '<div id="data"> 
        <p>Some text</p> 
      </div>
    '; 
    }
    So this outputs
    Code:
    <div id="data"> 
        <p>Some text</p> 
      </div>
    <div id="data"> 
        <p>Some text</p> 
      </div>

  3. #3
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by hessodreamy View Post
    what's the content of the array?
    User information.

    What are you using to check the html output?
    Firebug.

    Note that your php code does not output a line break either at the end or the beginning of the loop. Putting a line break in will probably make your output more readable and easier to debug.
    Thanks for the suggestion

    Here is the complete code:

    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

    <head>
    <title>Ricerca</title>
    <link rel="icon" href="img/favicon.ico">
    <meta http-equiv="Content-Type" content ="text/html; charset=utf-8"/>
    <link rel="stylesheet" href="css/reset.css" media="all"/>
    <link rel="stylesheet" href="css/styles.css" media="all"/>
    <link rel="stylesheet" href="css/print.css" media="print"/>
    </head>

    <body>

    <div id="header">
    <ul id="menu">
    <li><a href="index.php">Inserisci</a></li>
    <li>Ricerca</a></li>
    </ul>
    <img src="img/logo.png" />
    </div>

    <div id="container">

    <?php
        $conn 
    mysqli_connect('localhost''root''root''table');
        
        if (!
    $conn){
            echo 
    'Database Error: ' mysqli_connect_error() ;
            exit;
        }
        
        if (isset(
    $_GET['name']) && isset($_GET['surname'])) {
            
    $sql "SELECT type, name, surname, cf, city, province
                    FROM users
                    WHERE name='" 
    $_GET['name'] ."' AND surname='" $_GET['surname'] . "'";
        } else if (isset(
    $_GET['province'])) {
            if (
    $_GET['member'] == 2) {
                
    $sql "SELECT type, name, surname, cf, city, province
                        FROM users
                        WHERE province='" 
    $_GET['province'] . "'";
            } else if (
    $_GET['member'] == 1) {
                
    $sql "SELECT type, name, surname, cf, city, province
                        FROM users
                        WHERE province='" 
    $_GET['province'] . "'
                        AND member=1"
    ;
            } else {
                
    $sql "SELECT type, name, surname, cf, city, province
                        FROM users
                        WHERE province='" 
    $_GET['province'] . "'
                        AND member=0"
    ;
            }
        }
        
    $result mysqli_query($conn,$sql);
        if (isset(
    $_GET['name']) || isset($_GET['surname']) || isset($_GET['province'])) {
            if (
    mysqli_num_rows($result) == 0) {
                echo 
    '<p>Nessun utente trovato. <a href="search.php">Effettua una nuova ricerca</a></p>';
            } else {
                echo 
    '<a href="#" id="print" onclick="window.print()">Stampa lettere ed etichette per questi utenti</a>';
                echo 
    '<table>';
                while (
    $row mysqli_fetch_array($result)) {
                    
    $url sprintf(
                        
    'user.php?%s',
                        
    http_build_query(array('cf' => $row['cf']))
                    );
                    
    $members[] = $row;
                    echo 
    '<tr>
                            <td><a href="">Modifica</a></td>
                            <td><a href="' 
    $url '">Visualizza</a></td>
                              <td>' 
    $row["name"] . '</td>
                              <td>' 
    $row["surname"] . '</td>
                              <td>' 
    $row["cf"] . '</td>
                              <td>' 
    $row["city"] . '</td>
                              <td>' 
    $row["province"] . '</td>
                          </tr>'
    ;
                }
                echo 
    '</table';
                
                foreach(
    $members as $member) {
                    echo 
    '<div id="letter">
                            <ul id="member_address">
                                <li>' 
    $member["name"] . ' ' $member["surname"] . '
                                <li>Via ' 
    $member["street"] . ' ' $member["number"] . '
                                <li>' 
    $member["cap"] . ' ' $member["city"] . ' (' $member["province"] . ') ' '
                            </ul>
                            <ul id="onlus_address">
                                <li>Nome onlus</li>
                                <li>Indirizzo onlus</li>
                            </ul>
                            <p class="letterhead">Alla cortese attenzione del ' 
    $member["type"] . ' ' $member["name"] . ' ' $member["surname"] . ',</p>
                            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum odio metus, luctus non scelerisque quis, sagittis ac nibh. Aliquam euismod, odio a ultricies consequat, lacus urna laoreet nisl, sit amet rhoncus dui ante at dolor. Nullam justo lectus, rhoncus ut porttitor quis, pellentesque nec quam. Curabitur velit neque, molestie eu bibendum eget, eleifend sed ligula. Nam pulvinar ornare dolor et sodales. Pellentesque semper risus vitae justo ultricies in varius magna commodo. Curabitur accumsan faucibus est, ac suscipit massa tempus ac. Duis cursus eleifend velit, a sagittis velit facilisis ullamcorper. In placerat ultricies dui vitae rhoncus. Maecenas consectetur mi ac ligula viverra vitae adipiscing dui consequat. Mauris vel erat ipsum, quis consectetur nunc. Etiam facilisis hendrerit nisl, sed lacinia leo facilisis ut. In quis mauris arcu, ac fringilla sapien. Maecenas eget nibh risus. Nulla hendrerit, orci ut posuere fermentum, tortor lacus porttitor nisl, nec hendrerit metus neque eu augue.</p>
                            <p>Nunc varius porta libero, ac porta purus tempus et. Aenean gravida dignissim posuere. Maecenas dapibus diam vitae felis molestie in interdum eros mattis. Cras id leo ligula, eget feugiat ligula. Suspendisse posuere massa quis nisl imperdiet ac viverra leo ultrices. Morbi sapien quam, ultricies bibendum varius vel, dictum in urna. Proin magna leo, sollicitudin dignissim aliquam eu, suscipit vel magna. Nam justo purus, gravida non pharetra faucibus, feugiat id mauris. Quisque condimentum, mauris at convallis ornare, mi mauris mollis lacus, vitae hendrerit odio eros nec nibh. Mauris a tempus est. Curabitur est elit, vulputate et dignissim nec, vulputate ornare ipsum. Fusce ligula libero, pulvinar vel sollicitudin et, faucibus quis tellus. Donec at ligula libero, ac feugiat dui. Nulla quis orci eget mi consequat commodo in malesuada orci. Etiam eget leo iaculis nisi pretium ultrices. Ut laoreet sapien sed leo luctus porttitor.</p>
                            <p>Cordiali saluti,</p>
                            <p id="place_date">Luogo, l&igrave; ' 
    date('d/m/Y') . '<p>
                            <p id="signature">Firma</p>
                        </div>
                    '
    ;
                }
            }
        } else {
                    echo 
    '
                        <h2>Ricerca</h2>
                
                        <h3>Per nome e cognome</h3>
                        <form action="" method="get">
                            <label for="name">Nome</label>
                            <input type="text" name="name" />
                            <label for="surname">Cognome</label>
                            <input type="text" name="surname" />
                            <input type="submit" value="Cerca" />
                        </form>
                
                        <h3>Per provincia</h3>
                        <form action="" method="get">
                            <label for="province">Provincia</label>
                            <input type="text" name="province" />
                            <input type="radio" name="member" value="2" checked="checked" />Tutti
                            <input type="radio" name="member" value="1" />Solo iscritti
                            <input type="radio" name="member" value="0" />Non iscritti
                            <input type="submit" value="Cerca" />
                        </form>'
    ;
                }
                
    ?>
            </div>
        </body>

    </html>

  4. #4
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,301
    Mentioned
    460 Post(s)
    Tagged
    8 Thread(s)
    As an aside, use something like class="data" instead of id="data", as you can only use an ID once per page in HTML.

  5. #5
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ralph.m View Post
    As an aside, use something like class="data" instead of id="data", as you can only use an ID once per page in HTML.
    Lol thanks, I forgot to change it

  6. #6
    SitePoint Evangelist hessodreamy's Avatar
    Join Date
    Apr 2005
    Location
    uk
    Posts
    525
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    The problem with using firebug to debug php code is that firebug is showing you the DOM tree, and not the HTML. If your php outputs some invalid HTML (like incorrectly closed elements for example), then some elements may appear to be missing in firebug, but the intended HTML is there in the source. Have a look at the source HTML (ctrl U in firefox or chrome) and see if the missing html appears there. For a start, I can see that
    the ul id="member_address" has <li> items which are not closed. That could be your problem.

    Based on the snippet you started out with - there's nothing wrong with that. After fixing the broken <li> entries, at the html. If the actual html is not appearing on the page, post which part of your php script this missing content relates to.

    If it's in the html but not in firebug it means there's errors in your html. Post your html for us to look at that.

  7. #7
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by hessodreamy View Post
    The problem with using firebug to debug php code is that firebug is showing you the DOM tree, and not the HTML.
    I thought that it showed the HTML in the HTML tab...

    Anyway, the problem was simply that I had written </table instead of </table>

  8. #8
    SitePoint Evangelist hessodreamy's Avatar
    Join Date
    Apr 2005
    Location
    uk
    Posts
    525
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by D3V4 View Post
    I thought that it showed the HTML in the HTML tab...
    Not really. When parsing html the browser will often make guesses to overcome incorrect/invalid/broken html. It incorporates these guesses into the DOM it creates, and the firebug HTML tab does too.

    Consider the following invalid html:
    Code:
    <table>
    <tr><td>Content</td></tr>
    <td>2nd line</td>
    </table>
    You can see that the second row in this table is missing either an opening or closing <tr> tag. Since the previous <tr> is closed, it guesses we want a new one before our next <td>. And when we get to the end of the table without closing this <tr>, the browser puts a closing </tr> to make everything nice and correct. If you look at this code in firebug, it will show both of these missing tags as being there.

    Glad you got it sorted out, anyway.

  9. #9
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by hessodreamy View Post
    Not really. When parsing html the browser will often make guesses to overcome incorrect/invalid/broken html. It incorporates these guesses into the DOM it creates, and the firebug HTML tab does too.

    Consider the following invalid html:
    Code:
    <table>
    <tr><td>Content</td></tr>
    <td>2nd line</td>
    </table>
    You can see that the second row in this table is missing either an opening or closing <tr> tag. Since the previous <tr> is closed, it guesses we want a new one before our next <td>. And when we get to the end of the table without closing this <tr>, the browser puts a closing </tr> to make everything nice and correct. If you look at this code in firebug, it will show both of these missing tags as being there.
    Perfect explanation, thank you very much for your help

  10. #10
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    I'd suspect your array is NOT returning the data you think, or you've already indexed it somehow using a command like 'end'.

    Test 1: right before you do your WHILE statement:

    echo '<pre>',print_r($array),'</pre>';

    to make sure the values you want to output are actually in there. If they are... are you using any of the various array iteration commands before it? I'm not seeing them in the code, but that would be my only other guess.

    You might also want to get the final > on your </table> -- you missed it. (easy typo fix).... and if you use comma delimits on your echo instead of string addition it will behave more predictably and execute faster. Only use string addition (periods) when you HAVE TO, not 'just because' as it consumes much more memory (since the string has to be built completely before being sent to echo) meaning more time wasted on garbage collection.

    ... and lands sake man, get some sanitization in there (you've got mysqli, prepare those queries instead of string building!)

    You know, looking at this, you're building an array for no reason... waste of memory when you can use "seek" to go back to record zero.

    This is untested, probably has a few typo's, but here's how I'd be doing that:

    Code:
    <?php
    
    if ($conn=mysqli_connect('localhost', 'root', 'root', 'table')) {
    
    	if (
    		(isset($_GET['name']) && isset($_GET['surname']) ||
    		isset($_GET['province'])
    	) {
    
    		if (isset($_GET['province'])) {
    			$queryString='
    				SELECT type, name, surname, cf, city, province
    				FROM users
    				WHERE province=?
    			';
    			if ($_GET['member']==1) {
    				$queryString.=' AND member=1';
    			} else if ($_GET['member']!=2) {
    				$queryString.=' AND member=0';
    			}
    			$statement=$conn->prepare($queryString);
    			$statement->bindParam('s',$_GET['province']);
    		} else {
    			$statement=$conn->prepare('
    				SELECT type, name, surname, cf, city, province
    				FROM users
    				WHERE name=? AND surname=?
    			');
    			$statement->bind_param('ss',$_GET['name'],$_GET['surname']);
    		}
    
    		$result=$statement->execute();
    
    		if (($result->num_rows)==0) {
    
    			echo '
    				<p>
    					Nessun utente trovato.
    					<a href="search.php">Effettua una nuova ricerca</a>
    				</p>';
    				
    		} else {
    
    			echo '
    				<a href="#" id="print" onclick="window.print()">
    					Stampa lettere ed etichette per questi utenti
    				</a>
    				
    				<table>';
    				
    			while ($row=$result->fetch_assoc()) {
    				echo '
    					<tr>
    						<td><a href="">Modifica</a></td>
    						<td><a href="',sprintf(
    							'user.php?%s',
    							http_build_query(array('cf' => $row['cf'])
    						),'">Visualizza</a></td>
    						<td>',$row["name"],'</td>
    						<td>',$row["surname"],'</td>
    						<td>',$row["cf"],'</td>
    						<td>',$row["city"],'</td>
    						<td>',$row["province"],'</td>
    					</tr>';
    			}
    				
    			echo '
    				</table>';
    					
    			$result->data_seek(0); // reset results so we can fetch a second time
    			
    			while ($row=result->fetch_assoc()) {
    			
    				echo '
    				<div id="letter">
    					<ul id="member_address">
    						<li>',$row["name"],' ',$row["surname"],'</li>
    						<li>Via ',$row["street"],' ',$row["number"],'</li>
    						<li>',$row["cap"],' ',$row["city"],' (',$row["province"],')</li>
    					</ul>
    					<ul id="onlus_address">
    						<li>Nome onlus</li>
    						<li>Indirizzo onlus</li>
    					</ul>
    					<p class="letterhead">
    						Alla cortese attenzione del 
    						',$row["type"],'
    						',$row["name"],'
    						',$row["surname"],',
    					</p><p>
    						Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum odio metus, luctus non scelerisque quis, sagittis ac nibh. Aliquam euismod, odio a ultricies consequat, lacus urna laoreet nisl, sit amet rhoncus dui ante at dolor. Nullam justo lectus, rhoncus ut porttitor quis, pellentesque nec quam. Curabitur velit neque, molestie eu bibendum eget, eleifend sed ligula. Nam pulvinar ornare dolor et sodales. Pellentesque semper risus vitae justo ultricies in varius magna commodo. Curabitur accumsan faucibus est, ac suscipit massa tempus ac. Duis cursus eleifend velit, a sagittis velit facilisis ullamcorper. In placerat ultricies dui vitae rhoncus. Maecenas consectetur mi ac ligula viverra vitae adipiscing dui consequat. Mauris vel erat ipsum, quis consectetur nunc. Etiam facilisis hendrerit nisl, sed lacinia leo facilisis ut. In quis mauris arcu, ac fringilla sapien. Maecenas eget nibh risus. Nulla hendrerit, orci ut posuere fermentum, tortor lacus porttitor nisl, nec hendrerit metus neque eu augue.
    					</p><p>
    						Nunc varius porta libero, ac porta purus tempus et. Aenean gravida dignissim posuere. Maecenas dapibus diam vitae felis molestie in interdum eros mattis. Cras id leo ligula, eget feugiat ligula. Suspendisse posuere massa quis nisl imperdiet ac viverra leo ultrices. Morbi sapien quam, ultricies bibendum varius vel, dictum in urna. Proin magna leo, sollicitudin dignissim aliquam eu, suscipit vel magna. Nam justo purus, gravida non pharetra faucibus, feugiat id mauris. Quisque condimentum, mauris at convallis ornare, mi mauris mollis lacus, vitae hendrerit odio eros nec nibh. Mauris a tempus est. Curabitur est elit, vulputate et dignissim nec, vulputate ornare ipsum. Fusce ligula libero, pulvinar vel sollicitudin et, faucibus quis tellus. Donec at ligula libero, ac feugiat dui. Nulla quis orci eget mi consequat commodo in malesuada orci. Etiam eget leo iaculis nisi pretium ultrices. Ut laoreet sapien sed leo luctus porttitor.
    					</p><p>
    						Cordiali saluti,
    					</p><p id="place_date">
    						Luogo, l&igrave; ' . date('d/m/Y') . '
    					<p><p id="signature">
    						Firma
    					</p>
    				</div>';
    			}
    		}
    		
    	} else { // no $_GET passed, show form
    
    		echo '
    				<h2>Ricerca</h2>
    
    				<h3>Per nome e cognome</h3>
    				<form action="" method="get">
    						<label for="name">Nome</label>
    						<input type="text" name="name" />
    						<label for="surname">Cognome</label>
    						<input type="text" name="surname" />
    						<input type="submit" value="Cerca" />
    				</form>
    
    				<h3>Per provincia</h3>
    				<form action="" method="get">
    						<label for="province">Provincia</label>
    						<input type="text" name="province" />
    						<input type="radio" name="member" value="2" checked="checked" />Tutti
    						<input type="radio" name="member" value="1" />Solo iscritti
    						<input type="radio" name="member" value="0" />Non iscritti
    						<input type="submit" value="Cerca" />
    				</form>';
    				
    	}
    	
    } else die(''Database Error: '.mysqli_connect_error());
    
    
    ?>
    Played with the logic order a bit to simplify it down and make it clearer... and by using prepared queries from the start all your pesky untrustworthy user input is nice and sanitized for you.

    The 'big' thing though being this:
    $result->data_seek(0); // reset results so we can fetch a second time

    which lets you:
    while ($row=result->fetch_assoc()) {

    A second time! That way you don't need an extra array. One of the few things mysqli can do that PDO can't.

  11. #11
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by deathshadow60 View Post
    You might also want to get the final > on your </table> -- you missed it. (easy typo fix)
    That was indeed the problem

    and if you use comma delimits on your echo instead of string addition it will behave more predictably and execute faster. Only use string addition (periods) when you HAVE TO, not 'just because' as it consumes much more memory (since the string has to be built completely before being sent to echo) meaning more time wasted on garbage collection.
    I didn't know this, thanks! Can you explain this a bit more though? Meaning, if I use a comma, isn't the string built the same way as if I were using periods?

    and lands sake man, get some sanitization in there
    Lol you're right, but I meant to do it very soon

    (you've got mysqli, prepare those queries instead of string building!)
    I'll do it now

    You know, looking at this, you're building an array for no reason... waste of memory when you can use "seek" to go back to record zero.

    This is untested, probably has a few typo's, but here's how I'd be doing that:

    Code:
    <?php
    
    if ($conn=mysqli_connect('localhost', 'root', 'root', 'table')) {
    
    	if (
    		(isset($_GET['name']) && isset($_GET['surname']) ||
    		isset($_GET['province'])
    	) {
    
    		if (isset($_GET['province'])) {
    			$queryString='
    				SELECT type, name, surname, cf, city, province
    				FROM users
    				WHERE province=?
    			';
    			if ($_GET['member']==1) {
    				$queryString.=' AND member=1';
    			} else if ($_GET['member']!=2) {
    				$queryString.=' AND member=0';
    			}
    			$statement=$conn->prepare($queryString);
    			$statement->bindParam('s',$_GET['province']);
    		} else {
    			$statement=$conn->prepare('
    				SELECT type, name, surname, cf, city, province
    				FROM users
    				WHERE name=? AND surname=?
    			');
    			$statement->bind_param('ss',$_GET['name'],$_GET['surname']);
    		}
    
    		$result=$statement->execute();
    
    		if (($result->num_rows)==0) {
    
    			echo '
    				<p>
    					Nessun utente trovato.
    					<a href="search.php">Effettua una nuova ricerca</a>
    				</p>';
    				
    		} else {
    
    			echo '
    				<a href="#" id="print" onclick="window.print()">
    					Stampa lettere ed etichette per questi utenti
    				</a>
    				
    				<table>';
    				
    			while ($row=$result->fetch_assoc()) {
    				echo '
    					<tr>
    						<td><a href="">Modifica</a></td>
    						<td><a href="',sprintf(
    							'user.php?%s',
    							http_build_query(array('cf' => $row['cf'])
    						),'">Visualizza</a></td>
    						<td>',$row["name"],'</td>
    						<td>',$row["surname"],'</td>
    						<td>',$row["cf"],'</td>
    						<td>',$row["city"],'</td>
    						<td>',$row["province"],'</td>
    					</tr>';
    			}
    				
    			echo '
    				</table>';
    					
    			$result->data_seek(0); // reset results so we can fetch a second time
    			
    			while ($row=result->fetch_assoc()) {
    			
    				echo '
    				<div id="letter">
    					<ul id="member_address">
    						<li>',$row["name"],' ',$row["surname"],'</li>
    						<li>Via ',$row["street"],' ',$row["number"],'</li>
    						<li>',$row["cap"],' ',$row["city"],' (',$row["province"],')</li>
    					</ul>
    					<ul id="onlus_address">
    						<li>Nome onlus</li>
    						<li>Indirizzo onlus</li>
    					</ul>
    					<p class="letterhead">
    						Alla cortese attenzione del 
    						',$row["type"],'
    						',$row["name"],'
    						',$row["surname"],',
    					</p><p>
    						Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum odio metus, luctus non scelerisque quis, sagittis ac nibh. Aliquam euismod, odio a ultricies consequat, lacus urna laoreet nisl, sit amet rhoncus dui ante at dolor. Nullam justo lectus, rhoncus ut porttitor quis, pellentesque nec quam. Curabitur velit neque, molestie eu bibendum eget, eleifend sed ligula. Nam pulvinar ornare dolor et sodales. Pellentesque semper risus vitae justo ultricies in varius magna commodo. Curabitur accumsan faucibus est, ac suscipit massa tempus ac. Duis cursus eleifend velit, a sagittis velit facilisis ullamcorper. In placerat ultricies dui vitae rhoncus. Maecenas consectetur mi ac ligula viverra vitae adipiscing dui consequat. Mauris vel erat ipsum, quis consectetur nunc. Etiam facilisis hendrerit nisl, sed lacinia leo facilisis ut. In quis mauris arcu, ac fringilla sapien. Maecenas eget nibh risus. Nulla hendrerit, orci ut posuere fermentum, tortor lacus porttitor nisl, nec hendrerit metus neque eu augue.
    					</p><p>
    						Nunc varius porta libero, ac porta purus tempus et. Aenean gravida dignissim posuere. Maecenas dapibus diam vitae felis molestie in interdum eros mattis. Cras id leo ligula, eget feugiat ligula. Suspendisse posuere massa quis nisl imperdiet ac viverra leo ultrices. Morbi sapien quam, ultricies bibendum varius vel, dictum in urna. Proin magna leo, sollicitudin dignissim aliquam eu, suscipit vel magna. Nam justo purus, gravida non pharetra faucibus, feugiat id mauris. Quisque condimentum, mauris at convallis ornare, mi mauris mollis lacus, vitae hendrerit odio eros nec nibh. Mauris a tempus est. Curabitur est elit, vulputate et dignissim nec, vulputate ornare ipsum. Fusce ligula libero, pulvinar vel sollicitudin et, faucibus quis tellus. Donec at ligula libero, ac feugiat dui. Nulla quis orci eget mi consequat commodo in malesuada orci. Etiam eget leo iaculis nisi pretium ultrices. Ut laoreet sapien sed leo luctus porttitor.
    					</p><p>
    						Cordiali saluti,
    					</p><p id="place_date">
    						Luogo, lý ' . date('d/m/Y') . '
    					<p><p id="signature">
    						Firma
    					</p>
    				</div>';
    			}
    		}
    		
    	} else { // no $_GET passed, show form
    
    		echo '
    				<h2>Ricerca</h2>
    
    				<h3>Per nome e cognome</h3>
    				<form action="" method="get">
    						<label for="name">Nome</label>
    						<input type="text" name="name" />
    						<label for="surname">Cognome</label>
    						<input type="text" name="surname" />
    						<input type="submit" value="Cerca" />
    				</form>
    
    				<h3>Per provincia</h3>
    				<form action="" method="get">
    						<label for="province">Provincia</label>
    						<input type="text" name="province" />
    						<input type="radio" name="member" value="2" checked="checked" />Tutti
    						<input type="radio" name="member" value="1" />Solo iscritti
    						<input type="radio" name="member" value="0" />Non iscritti
    						<input type="submit" value="Cerca" />
    				</form>';
    				
    	}
    	
    } else die(''Database Error: '.mysqli_connect_error());
    
    
    ?>
    Played with the logic order a bit to simplify it down and make it clearer... and by using prepared queries from the start all your pesky untrustworthy user input is nice and sanitized for you.

    The 'big' thing though being this:
    $result->data_seek(0); // reset results so we can fetch a second time
    Great, I didn't know about this! I wished I had known it before.

    which lets you:
    while ($row=result->fetch_assoc()) {

    A second time! That way you don't need an extra array. One of the few things mysqli can do that PDO can't.
    Just one question about this: couldn't I use "mysqli_fetch_array" instead of "fetch_assoc"?

  12. #12
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by D3V4 View Post
    Can you explain this a bit more though? Meaning, if I use a comma, isn't the string built the same way as if I were using periods?
    Nope, not at all the same... at least for echo. The reason you can use a comma is the echo language construct can accept multiple values separated by commas, which are output one after another... string addition with period means all those values first have to be added together (using more memory) and then are sent all-at-once from the massive memory buffer.

    Basically:

    echo $this,' and ',$that;

    is 'under the hood' the same as going:

    echo $this;
    echo ' and ';
    echo $that;

    Except that it's one command instead of three.

    echo $this.' and '.$that;

    Is more akin to
    $output=$this.' and '.$that;
    echo $output;
    unset($output);

    Not an 'exact' comparison, but close enough...

    Basically using commas sends it as smaller chunks or pointers to the smaller chunks, while using periods means allocating enough memory for the result, copying all the values to it, sending a pointer to that memory to the echo function, and then releasing that memory when complete.

    It's one of those things that if you've done low level programming or had to handle your own memory use you'd be fully aware of, but if high level languages like PHP are all you know it might not even occur to you the difference. One of the problems with just learning the high level -- you never "really" learn how things actually work.

    There's a test-case I use to show this difference in action -- and it's a fun one.

    Code:
    <?php
    function test() {
      echo 'test ';
    }
    
    echo '
      This is a '.test().'<br />
      This is a ',test();
    ?>
    Because the string addition has to be run BEFORE being sent to the echo, the echo inside the function has to be called BEFORE the echo statement... so the output from that example ends up:

    test This is a
    This is a test

    A functional difference that can REALLY mess you up if you're unaware of it. String addition on echo is slower, consumes more memory, and forces more garbage collection -- so when possible, use commas to separate values.

    Just beware that sometimes you have to use string addition -- like inside inline-evaluations.

    echo ($this ? 'this='.$this : 'that');

    For example, if you replaced that string addition inside the evaluation with a comma, it wouldn't work.

    Gets a bit tricky, but it's important to know the difference... and it's VERY poorly explained just about everywhere.

    Just one question about this: couldn't I use "mysqli_fetch_array" instead of "fetch_assoc"?
    I prefer assoc if I'm not going to use the numerical indexes, because it means a smaller result set and less memory use.

    Some people might call it premature optimization, I prefer to call it good coding practices -- but I learned to program using toggle switches on a machine with 256 bytes of RAM, so I'm a bit more rabid about keeping memory use under control than others.

  13. #13
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, I understand now


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •