SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 39
  1. #1
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with inserting mysql data into a div

    Hi Everyone,

    I am busy trying to make a download section on my site which caters for free apps, games and themes for blackberry phones.

    I am putting my ideas together and at the moment i have the following:

    -a mysql database with 2 tables.
    -the first table "downloads" contains 3 rows, each with a unique id that and each represent the type of file being downloaded. e.g. application or theme.
    -the second table contains the information about each download, these fields are the models supported by the download, the title, a picture, a brief description and a download link. each download has a unique id.

    Now what i am trying to do is insert the data into a set of divs, these divs are as follows:

    Code:
    <div class="dlcontainer">
     <div class="dlitem">
      <div class="dltitle"><php $row['title'] ?></div>";
      <div class="dlimage"><php $row['image'] ?></div>";
      <div class="dldescription"><php $row['description'] ?></div>";
      <div class="dllink"><php $row['downlink'] ?></div>";
     </div>
    </div>
    As you can see i have been trying to populate the divs with information called from the database and that was my first attempt.

    I didn't feel like i was going about this with the right approach, so i ended up with this, which also does not seem to work:

    Code:
    <?php
    $con = mysql_connect("test","test","test");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db("test", $con);
    
    $result = mysql_query("SELECT * FROM `content` WHERE pid = '2' AND models = 'all' OR models = $chosen");
    
    while($row = mysql_fetch_array($result))
    
      {
        echo "<div class=\"dlcontainer\">";
         echo "<div class=\"dlitem\">";
          echo "<div class=\"dltitle\">$row['title']</div>";
          echo "<div class=\"dlimage\">$row['image']</div>";
          echo "<div class=\"dldescription\">$row['description']</div>";
          echo "<div class=\"dllink\">$row['downlink']</div>";
         echo "</div>";
        echo "</div>";
      }
         mysql_close($con);
    ?>
    Once i get this initial download working, i can then set up a loop that will display all the contents that match belong to a specific "pid" and either match a "models" value of "all" or one that has been selected by the user.

    If anyone could point me in the right direction here, i would really appreciate the input!!!

    Thanks.

  2. #2
    SitePoint Wizard GoldFire's Avatar
    Join Date
    Oct 2002
    Location
    Oklahoma City, OK
    Posts
    1,517
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    PHP Code:
    <?php
    $con 
    mysql_connect("test","test","test");
    if (!
    $con) die('Could not connect: ' mysql_error());

    mysql_select_db("test"$con);

    $result mysql_query("SELECT * FROM `content` WHERE pid = '2' AND models = 'all' OR models = $chosen");

    while(
    $row mysql_fetch_array($result)) {
        echo 
    "<div class=\"dlcontainer\">";
         echo 
    "<div class=\"dlitem\">";
          echo 
    "<div class=\"dltitle\">{$row['title']}</div>";
          echo 
    "<div class=\"dlimage\">{$row['image']}</div>";
          echo 
    "<div class=\"dldescription\">{$row['description']}</div>";
          echo 
    "<div class=\"dllink\">{$row['downlink']}</div>";
         echo 
    "</div>";
        echo 
    "</div>";
    }
    mysql_close($con);
    ?>

  3. #3
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is the correct method, a bit less sloppy:

    PHP Code:
    <?php
    /*
        These 6 lines should be included in a
        separate script for security and scalability.
    */
    $dbname 'DATABASE NAME';
    $dbuser     'DATABASE USER';
    $dbpass     'DATABASE PASSWORD';
    $dbhost     'DATABASE SERVER'// localhost should suffice
    $conn mysql_connect($dbhost$dbuser$dbpass) or exit(mysql_error());
    mysql_select_db($dbname$conn) or exit(mysql_error());

    $loopResult ''// leave blank to start var for loop
    $result mysql_query('SELECT * FROM `content` WHERE (`pid` = "2" && `models`="all") || models="'.$chosen.'"');
    while(
    $row mysql_fetch_assoc($result)) {
        
    $loopResult '
            <div class="dlcontainer">
            <div class="dlitem">
            <div class="dltitle">'
    .$row['title'].'</div>
            <div class="dlimage">'
    .$row['image'].'</div>
            <div class="dldescription">'
    .$row['description'].'</div>
            <div class="dllink">'
    .$row['downlink'].'</div>
            </div>
            </div>
        '
    ;
    }
    echo 
    $loopResult;
    ?>
    Notes:

    1. do not call mysql_close(), it already closes at the end of the script.

    2. Do not wrap strings in double quotes, kills performance and looks like crap.

    3. Note that I enclosed the && comparison in parenthesis to separate it from the || comparison. This is the correct method of doing this.

    4. DO NOT use mysql_fetch_assoc() without a logical reason, it uses double the resources to generate. This creates both a numeric and associative array. You only are using an associative, so you use mysql_fetch_assoc() instead. For numeric, use mysql_fetch_row().

  4. #4
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,496
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by blackberryfan View Post
    which also does not seem to work:
    What does 'not work' mean? An empty page? An error? Output you didn't expect/want?

    And let's take a look at this query.
    Code:
    SELECT * 
    FROM `content` 
    WHERE pid = '2' 
    AND models = 'all' 
    OR models = $chosen
    When you have AND's and OR's, you'd better use parentheses to make sure the query does what you want. Because
    Code:
    SELECT * 
    FROM `content` 
    WHERE pid = '2' 
    AND   (   models = 'all' 
            OR models = $chosen )
    is not the same as

    Code:
    SELECT * 
    FROM `content` 
    WHERE (   pid = '2' 
           AND models = 'all' )
    OR    models = $chosen
    and I for one never remember what MySQL's default behaviour is when you don't use parentheses.

  5. #5
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    (`pid` = "2" && `models`="all") || models="'.$chosen.'" 
    says if pid and models are what they should be or models is x do this.


    PHP Code:
    `pid` = "2" && `models`="all" || models="'.$chosen.'" 
    says if pid is this or models is x or models is x and pid is x. This is too generic and too much margin for error.


    So, to decide if you need parentheses, decide if pid should always be 2. If pid always should be 2, then you actually need:

    PHP Code:
    `pid` = "2" && (`models`="all" || models="'.$chosen.'"
    It is identical to using parentheses in equations, what is in the parentheses is decided first and grouped togther before making any comparisons outside of the parentheses.

  6. #6
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by LinuxFreelancer View Post
    Here is the correct method, a bit less sloppy:

    PHP Code:
    <?php
    /*
        These 6 lines should be included in a
        separate script for security and scalability.
    */
    $dbname 'DATABASE NAME';
    $dbuser     'DATABASE USER';
    $dbpass     'DATABASE PASSWORD';
    $dbhost     'DATABASE SERVER'// localhost should suffice
    $conn mysql_connect($dbhost$dbuser$dbpass) or exit(mysql_error());
    mysql_select_db($dbname$conn) or exit(mysql_error());

    $loopResult ''// leave blank to start var for loop
    $result mysql_query('SELECT * FROM `content` WHERE (`pid` = "2" && `models`="all") || models="'.$chosen.'"');
    while(
    $row mysql_fetch_assoc($result)) {
        
    $loopResult '
            <div class="dlcontainer">
            <div class="dlitem">
            <div class="dltitle">'
    .$row['title'].'</div>
            <div class="dlimage">'
    .$row['image'].'</div>
            <div class="dldescription">'
    .$row['description'].'</div>
            <div class="dllink">'
    .$row['downlink'].'</div>
            </div>
            </div>
        '
    ;
    }
    echo 
    $loopResult;
    ?>
    Notes:

    1. do not call mysql_close(), it already closes at the end of the script.

    2. Do not wrap strings in double quotes, kills performance and looks like crap.

    3. Note that I enclosed the && comparison in parenthesis to separate it from the || comparison. This is the correct method of doing this.

    4. DO NOT use mysql_fetch_assoc() without a logical reason, it uses double the resources to generate. This creates both a numeric and associative array. You only are using an associative, so you use mysql_fetch_assoc() instead. For numeric, use mysql_fetch_row().
    Woooow!!!! That is so guru!!!

    Thank you so much man, you have no idea how much that makes sense, and helps too!

    I ended up last night before i passed out thinking about this subject with this:

    Code:
    <?php
    // Make a MySQL Connection
    mysql_connect("test", "test", "test") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());
    
    // Retrieve all the data from the "example" table
    $result = mysql_query("SELECT * FROM content")
    or die(mysql_error());  
    
    // store the record of the "example" table into $row
    $row = mysql_fetch_array( $result );
    // Print out the contents of the entry 
    
    echo "<div class=\"dlcontainer\">";
    echo "<div class=\"dlitem\">";
    echo "<div class=\"dltitle\">".$row['title']."</div>";
    echo "<div class=\"dlimage\">".$row['image']."</div>";
    echo "<div class=\"dldesc\">".$row['description']."</div>";
    echo "<div class=\"dllink\">".$row['downlink']."</div>";
    echo "</div>";
    echo "</div>";
    
    ?>
    It does work the way i wanted it to, but in no means is it as useful as what you have posted for me.

    I do understand that the connection info needs to be stored in a seperate file, but my example was just the beginning of my design so it is what i was working with on my test page.

    I was scratching my head about the double quoting issue i had and my solution was messy to say the least.

    As for deciding whether pid is always a set value, well the way i see it... Its a yes because I am going to have 3 pages, one for each type of download. I am going to add a list of models that run down the left of the page, under my menu bar, once a user selects a model, this value will become "$chosen". For instance, the apps page will only display rows in my database that MUST contain a pid of "2" and either have a model value of all, or a model value of "$chosen".

    So i guess this one applies to me:

    Code:
    `pid` = "2" && (`models`="all" || models="'.$chosen.'")
    A bit confused about that loop you added in there, will that display each row in that set of divs until there are none left to show? Also, would i be able to create a paging option, as in, e.g. 10 rows in the database = 1 page?

    In anycase though, thank you SO much! I really appreciate the input!

    @GoldFire - Your idea put me on the right track, thanks alot!!

    @guido2004 - Thanks for the thoughts, it has got me thinking about how little i know about php, i just bought sitepoints book on database driven websites with php and mysql! Bottom line though, Thank you!!

    Anyone else reading this, do you have any input on how i plan on designing my download section? Do you think my idea is too complicated?

    (please keep in mind that my site is a blackberry phone fansite, using a bare minimum of javascript; as to avoid issues with the display on the blackberry mobile browser)

    I am trying to think of a logical way to display the data and what i said earlier about the layout seems ideal, i think!
    Last edited by blackberryfan; Jun 17, 2011 at 11:46. Reason: typo

  7. #7
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    $loopresult is just a variable containing everything that was going to be echoed. I'll add page numbers in a bit, going outside with my kids before it starts raining

    You are quite welcome and best of luck!

  8. #8
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by LinuxFreelancer View Post
    $loopresult is just a variable containing everything that was going to be echoed. I'll add page numbers in a bit, going outside with my kids before it starts raining

    You are quite welcome and best of luck!
    Ah man, you are really such a LEGEND! Yes that makes perfect sense now.

    I am busy reading up on page numbering at the moment, i might just beat you to it, ha (im really kidding its actually like chinese to me)

    Anyways, thanks alot for your input, and enjoy that moment... lucky...

    Speaking of that though, thank you, it appears that I do need it!

  9. #9
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did not test this, just chucked it together real fast for you but aside from a missing character or soemthing it should work with minumal debugging. I added a bit to it, you seem willing to learn so why not put extra in thee for you

    I attached the script in a zip file too, let me know if something doesn't work right. Don't forget to find all instances of scriptname.php and change to the name of your script.


    PHP Code:
    <?php
    /*
     These 6 lines should be included in a separate script for security and scalability.
    */
    $dbname 'DATABASE NAME';
    $dbuser 'DATABASE USER';
    $dbpass 'DATABASE PASSWORD';
    $dbhost 'DATABASE SERVER'// localhost should suffice
    $conn   mysql_connect($dbhost$dbuser$dbpass) or exit(mysql_error());
    mysql_select_db($dbname$conn) or exit(mysql_error());
     
    if (!
    function_exists('vdata')) {
     function 
    vdata($value) {
      if (
    isNaturalNumber($value)) {
       return 
    $value;
      }
      
    /*
       Function: vdata()
       Coder site: http://crackfeed.com/
       Purpose: sterilizes string prior to sql injection
       Example: mysql_query('SELECT `email` FROM `users` WHERE `username`="' . vdata($username) . '"');
      */
      
    if (!function_exists('clean')) {
       
    /*
        called from within vdata() only, I clean
        and format data pre-injection into sql
       */
       
    function clean($value) {
              
    $value htmlspecialchars(strip_tags(utf8_decode($value)));
              
    $value mysql_real_escape_string(trim($value));
        return 
    $value;
       }
      }
      
    $value safeStripslashes($value);
      
    $value clean($value);
      return 
    $value;
     }
    }
    if (!
    function_exists('sqlquery')) {
     function 
    sqlquery($query) {
      
    $sql mysql_query($query) or die(mysql_error());
      if (!
    $sql) {
       return 
    false;
      }
      return 
    $sql;
     }
    }
    if (!
    function_exists('sqlassoc')) {
     function 
    sqlassoc($query) {
      
    $sql sqlquery($query) or die(mysql_error());
      if (
    mysql_num_rows($sql) == 0) {
       return 
    false;
      }
      return 
    mysql_fetch_assoc($sql);
     }
    }
    if (!
    function_exists('sqlres')) {
     function 
    sqlres($query) {
      
    $sql sqlquery($query) or die(mysql_error());
      
    $r mysql_result($sql00);
      if (
    $r == 0) {
       return 
    '0';
      } else {
       return 
    $r;
      }
     }
    }
    if (!
    function_exists('isNaturalNumber')) {
     
    /*
      because is_numeric allows hexidecimal numbers
      so lets make sure it is a natural number.
     */
     
    function isNaturalNumber($val$acceptzero false) {
       if (empty(
    $val) || $val==null || $val=='' || $val==0) {
        return 
    FALSE;
       }
      
    $return = ((string)$val === (string)(int)$val);
      if (
    $acceptzero)
       
    $base 0;
      else
       
    $base 1;
      if (
    $return && intval($val) < $base)
       
    $return FALSE;
      return 
    $return;
     }
    }
     
     
    /*
     what page number?
    */
    if(empty($_REQUEST['p']) || !isNaturalNumber($_REQUEST['p'])) { 
     
    $page 1
    } else { 
     
    $page = (int)$_REQUEST['p'];
     if(
    $_REQUEST['p'] == 0) { 
      
    $page 1;
     }
    }
     
     
    /*
     calculate what page to ask the DB for
    */
    $from = (($page $max_results) - $max_results);
     
     
    /*
     Show all models or specific ?
     Let's count the results now since we need this value
     for page number calculation later anyway.
    */
    if (!empty($_REQUEST['chosen'])) {
     
    $chosen vdata(urldecode($_REQUEST['chosen']));
           
    $query 'SELECT COUNT(*) FROM `content` WHERE `pid`="2" && `models`="' $chosen '"';
    } else {
           
    $query 'SELECT COUNT(*) FROM `content` WHERE `pid`="2" && `models`="all")';
    }
    $total_results sqlres($query);
    if (
    $total_results == 0) {
     die(
    'No results to show.');
    } else {
     
    $total_pages ceil($total_results $max_results);
    }
     
     
    /*
     now get and process teh actual data now that
     we know it exists.
    */
    $loopResult '';
    if (!empty(
    $chosen)) {
     
    $query2 'SELECT * FROM `content` WHERE `pid` = "2" && `models`="'.$chosen.'" ORDER BY `title` ASC LIMIT ' $from ', ' $max_results;
     
    $addSelection '&chosen=' urlencode(stripslashes($chosen));
    } else {
     
    $query2 'SELECT * FROM `content` WHERE `pid` = "2" && `models`="all" ORDER BY `title` ASC LIMIT ' $from ', ' $max_results;
     
    $addSelection '';
    }
    $result sqlassoc($query2);
    while(
    $row $result) {
     
    $loopResult '
      <div class="dlcontainer">
       <div class="dlitem">
        <div class="dltitle">'
    .$row['title'].'</div>
        <div class="dlimage">'
    .$row['image'].'</div>
        <div class="dldescription">'
    .$row['description'].'</div>
        <div class="dllink">'
    .$row['downlink'].'</div>
       </div>
      </div>
     '
    ;
    }
     
     
    /*
     Move on to page numbers...
    */
    if ($total_pages 1) { 
     
    $max_links 10// how many page numbers to show
     
    $h=1;
     
    $pagenums='<div class="pageNums">'// container for page numbers
     
    if($page>$max_links){ 
      
    $h=(($h+$page)-$max_links); 
     } 
     if(
    $page>=1){ 
      
    $max_links $max_links+($page-1); 
     } 
     if(
    $max_links>$total_pages){ 
      
    $max_links=$total_pages+1
     } 
     if(
    $page>1){
      
    $pagenums .= '<a href="'.$path_to.'">First</a>&nbsp;&nbsp;';
      
    $pagenums .= '<a href="scriptname.php?page=' . ($page-1) . $addSelection.'">Previous</a>&nbsp;&nbsp;';
     } 
     if(
    $total_pages!=1){ 
      for (
    $i=$h;$i<$max_links;$i++){
       if(
    $i==$page){ 
        
    $pagenums .= '<a href="scriptname.php?page=' $page $addSelection '">'.$i.'</a>&nbsp;&nbsp;'
       } elseif (
    $i==$total_pages){
        if (
    $i == 1) {
         
    $pagenums .= '<a href="scriptname.php?page=1' $addSelection.'">First</a>&nbsp;&nbsp;';
        } else {
         
    $pagenums .= '<a href="scriptname.php?page=' $i $addSelection.'">'.$i.'</a>&nbsp;&nbsp;';
        } 
       } else { 
        if (
    $i == 1) {
         
    $pagenums .= '<a href="scriptname.php?page=1' $addSelection.'">First</a>&nbsp;&nbsp;';
        } else {
         
    $pagenums .= '<a href="scriptname.php?page=' $i $addSelection.'">'.$i.'</a>&nbsp;&nbsp;';
        }
       } 
      } 
     } 
     if((
    $page >="1")&&($page!=$total_pages)){ 
      
    $pagenums .= '<a href="scriptname.php?page=' . ($page+1) . $addSelection.'">Next</a>&nbsp;&nbsp;&nbsp;';
      
    $pagenums .= '<a href="scriptname.php?page=' $total_pages $addSelection.'">Last</a>';
     } 
     
    $pagenums .= '</div>';
    } else {
     
    $pagenums '';
    }
     
    // echo the results
    echo $pagenums $loopResult $pagenums;
    ?>
    Attached Files Attached Files

  10. #10
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well I have to say that is one of the most interesting, yet mind boggling things I have ever read. I have this intense need to reread it all until I actually really understand what you're saying.

    But from the looks of it, its precisely what i was just scratching my head about, just a short while ago... Haha, you're something else completely man! You should write books cause i'd buy em.

    And I hope that you guys at sitepoint read this and approve his script quickly, the man is !GURU!, you should like promote him alot

    In anycase though, I do have a slight knowledge of php so what you've given me actually does make sense. I can gaurentee you that it is untold amounts better than anything I could have concieved in a matter of minutes... And im going to study then re-study it all tomorrow when I get back from work, its so exciting I wish i had a fast forward button!!

    Thank you so much, seriously!! This is going to help me like you wouldnt believe!

  11. #11
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, that is high praise, thanks brother.

    Well, I'm not to good with writing books but I am hoping to start posting more on my blog, fell out of it once summer came lol.

    One addition you can do with this is to cache the page output at the end, in other words before the echo statement have it write the output to a text file based on what the value of $chosen is. At the beginning of the script, check if there is a cached file and if so, stop processing the script and display the contents of the text file instead.

    I would not worry about doing that unless the page sees a lot of traffic though.

  12. #12
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It may be, but I must give credit where credit is due!

    And its true because my idea is so much brighter now that I have the understanding I have come to possess via this thread.

    Pity about those book writing skills though... But I did take a look at your blog and I guess that the predicament you're in what with your guru sized intelligence level causing your chain of thought to move faster than the body will actually allow you to type, I mean... I guess i can kind of identify with your whole theory on not being good with writing as a result because I could say i suffer from the same dilema, only its my spoken words that seem to stuggle playing catch up with where my thoughts are at

    I have to add too, that ecart script your have on there looks like its pretty pimped! Very impressive!

    Well one more thing too, your reasoning behind your chosen domain name is... Freaking classic! haha! (for real)

    On a more serious note though, I have been studying this script of yours. There are a few things that confuse me, and yes it is very slightly buggy, but it really looks rock solid, im sure im just missing something here... I say this because, okay. I added it to my page, but it came has a mysql error, let me see.

    "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1"

    Now, I eventually realised that this error was caused by this line:

    Code:
    $query = 'SELECT COUNT(*) FROM `content` WHERE `pid`="2" && `models`="all")';
    So i took out the unneeded(?) bracket. Now im stuck on this error:

    "Warning: Division by zero in /blah/server/path/test3.php on line 157
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"

    This is a tad confusing because I assume that the line one its referring to is the first line of some sql query after the point where i took out the bracket. I have no idea why its warning me about the division by zero, but i am assuming this has something to do with my db only having 3 content entries? In anycase, line 157 is this line which appears a few lines after the line I corrected.

    Code:
    $total_pages = ceil($total_results / $max_results);
    So it got that far and got stuck, that I understand, but the reason why? hmm... lets see, there are 4 references to '', they are:

    Code:
    if (empty($val) || $val==null || $val=='' || $val==0) {
    This one appears before it got stuck previously so i am assuming, but not so sure that it has nothing to do with this, that leaves us with these:

    Code:
    $loopResult = '';
    Code:
    $addSelection = '';
    Code:
    $pagenums = '';
    Hmm, thats where i am stuck because looking at the bits of sql 'near' there i really dont see anything a miss, which leads me to think that i simply do not know enough about the information I am looking at to understand the issue here

    Which brings me back to what I was thinking orignally, but found myself not so sure about... And that is that the current error has something (im not sure what yet) to do with that vdata function? Either that or it has something to do with the way this peice of code ends:

    Code:
    $query = 'SELECT COUNT(*) FROM `content` WHERE `pid`="2" && `models`="all"';
    Ofcourse it could actually have nothing to do with the " '' " symbols but hey, thats as far as I am here.

    Besides that, I have another question. From what I can tell, this script will display all rows with a pid of 2 and models = chosen, or ones that have a pid of 2 and models = all. Now im a bit confused because i'd want any row with a pid of 2 and a models value of all or $chosen.

    So essentially i should have this instead?:

    Code:
    /*
     now get and process teh actual data now that
     we know it exists.
    */
    $loopResult = '';
    if (!empty($chosen)) {
     $query2 = 'SELECT * FROM `content` WHERE `pid` = "2" && (`models`="all" || models="'.$chosen.'") ORDER BY `title` ASC LIMIT ' . $from . ', ' . $max_results;
     $addSelection = '&chosen=' . urlencode(stripslashes($chosen));
    } 
    $result = sqlassoc($query2);
    while($row = $result) {
     $loopResult = '
      <div class="dlcontainer">
       <div class="dlitem">
        <div class="dltitle">'.$row['title'].'</div>
        <div class="dlimage">'.$row['image'].'</div>
        <div class="dldescription">'.$row['description'].'</div>
        <div class="dllink">'.$row['downlink'].'</div>
       </div>
      </div>
     ';
    }
    No 'else'?

    I wouldnt want it to show only items that have a value of $chosen, or only items that show all. I'd like the $chosen to suppliment the default data showed, which would be all rows with the value of all.

    All would be any download that would operate on any phone model, additionally some downloads would only be available to certain models.

    But looking at that code again, i think im just confused because the else does need to be there and this script would operate in the same way I am describing?

    O well, looks like I need to look harder!

  13. #13
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So after some thinking, I am pretty certain it has something to do with that vdata function and the way its cleaning the data? Im pretty stumped though, time to scratch my head and think some more =] This is a very interesting puzzle you have given me, I must say again, thank you!

  14. #14
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, vdata() should be fine. I forgot to define this at the beginning of the script:

    PHP Code:
    $max_results 30
    Since that is not set, you get division by zero.

    Also change:

    PHP Code:
    if ($total_results == 0) { 
    to:

    PHP Code:
    if ($total_results == '0') { 
    because I have the function returning zero as a string instead of zero, so it can be used to display a zero if needed.


    *******************************************************


    Lastly,

    the $var = 'blah blah blah ' . $var . ' blah blah blah'; is how to define a variable without putting inside double quotes. The purpose is simple:

    When you wrap a string and a variable in double quotes, you double the work PHP is doing. Becuase, it has to figure out what part is the string and what part is the variable.

    However, wrapping as I do, php knows imediately what is a string and what is a variable.

    Example one:

    PHP Code:
    $var "My name is $name"
    That is a string and variable thrown together. Not good for performance and just plain lazy coding.

    But now take:

    PHP Code:
    $var 'My name is ' $name
    and PHP knows what the string is and what the variable is imediately, so less processing. this method keeps you from putting ugly and annoying backslashes for double quotes too:

    PHP Code:
     
    $var 
    '...and then she asked, "When are you going to clean the gutters?". I answered with a shrug and walked away.'
    But the double quote encapsulation looks like this and is buttt ugly:


    PHP Code:
     
    $var 
    "...and then she asked, \"When are you going to clean the gutters?\". I answered with a shrug and walked away."

    If you want, I can take a look at it when I get a chance, just PM me or email me with the script or login to the script and I will debug it, like I said, I just chucked it together real fast for example's sake.

  15. #15
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There is an else, because one query shows ALL results and the other shows "chosen" results.

    PHP Code:
    if (!empty($chosen)) {
     
    $query2 'SELECT * FROM `content` WHERE `pid` = "2"
     && `models`="'
    .$chosen.'" ORDER BY `title` ASC LIMIT ' $from ', ' $max_results;
     
    $addSelection '&chosen=' urlencode(stripslashes($chosen));
    } else {
     
    $query2 'SELECT * FROM `content` WHERE `pid` = "2"
     && `models`="all" ORDER BY `title` ASC LIMIT ' 
    $from ', ' $max_results;
     
    $addSelection '';


    Btw, I already have a script like this. lol I will PM you a demo url

  16. #16
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I was just thinking it had something to do with if ($total_results == 0) { a few more minutes and i would have had it, im telling you!! But with such detail... Never, no really that is just legend.

    I for the first time, have a crystal clear understanding about those two ways of defining variables. As you said, the way i was origianlly doing things was a pain too! That is one peice of knownledge i do believe i will keep. So thanks for that quality post!

    As for for the 2 queries, I think i get it now, you need both bits of information in order to output it as a whole depending on whether chosen has a value assigned or not?

    I have sent you a pm, and about your site, that is really cool. A question, where did you find all those model images?

  17. #17
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is this correct? :

    Code:
    $loopResult = ''; // leave blank to start var for loop
    $result = mysql_query('SELECT * FROM `content` WHERE `pid` = "2" && (`models`="all" || models="'.$chosen.'")');
    while($row = mysql_fetch_assoc($result)) {
    	$loopResult = ' 
            <div id='.$row['id'].' class="dlitem">
             <div id='.$row['titleid'].' class="dltitle">'.$row['title'].'</div>
             <div id='.$row['imageid'].' class="dlimage">'.$row['image'].'</div>
             <div id='.$row['descriptionid']. ' class="dldesc">'.$row['description'].'</div>
             <div id='.$row['downlinkid'].' class="dllink">'.$row['downlink'].'</div>
            </div>
        ';
    }
    echo $loopResult;

  18. #18
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    71 Post(s)
    Tagged
    0 Thread(s)
    Side note - SELECT * bad!

  19. #19
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by StarLion View Post
    Side note - SELECT * bad!
    It is not bad, not not always wise. If every column is being used, it is quite good. For example, many benchmarks show it faster to use COUNT(*) than COUNT(colName). Also, due to size restrictions of INDEXES, sometimes it is the best choice.

    But do try to say the reason why something is bad when you jump in like that.

    He/she is right, calling only the cols you need and creating an INDEX with those cols will increase performance.

  20. #20
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    True that! And I learnt this today too. Going to take some time to get used to I guess, but I was referring to the way I added the I'd that contains a variable to those div's? Is that the right way to do it?

    Edit: ahhh!!! Now I'm confused, so in my case using SELECT * and not (*) is the better option as I am using all columns?

  21. #21
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Change it to:

    Code:
    'SELECT `downlink`,`description`,`image`,`title`,`pid,`models` FROM `content`......
    Then in phpmyadmin, I am guessing that is the tool you are using, check each of those columns and click the INDEX link below the table row list.

    Added in edit:

    Example: http://crackfeed.com/ex1346.png

    Mine, I used fulltext, you want INDEX.... the one I circled. Check the boxes for the fields I listed above and then click the INDEX button.

  22. #22
    SitePoint Zealot LinuxFreelancer's Avatar
    Join Date
    Jun 2011
    Location
    Boston, Ma, Usa
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by blackberryfan View Post
    True that! And I learnt this today too. Going to take some time to get used to I guess, but I was referring to the way I added the I'd that contains a variable to those div's? Is that the right way to do it?

    Edit: ahhh!!! Now I'm confused, so in my case using SELECT * and not (*) is the better option as I am using all columns?
    Not (*), he said *

    But then I said COUNT(*) which is used to count the results, not part of your code.

  23. #23
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay I think i understand what you two are saying. By selecting everything im basically creating extra (unneeded) work. By selecting only the columns that are needed, I get from point a to point b quicker and with less margin for error i guess?

  24. #24
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    71 Post(s)
    Tagged
    0 Thread(s)
    It's not margin of error... think of it this way.

    You've got a bowl of fruit (your row).
    Your friend asks you for a banana (a field in that row).
    Which is going to take more effort (data transfer time/memory allocation)? Lifting the single banana (SELECT banana), or lifting the entire fruit bowl (SELECT *)?

    Now, if your friend asks you for all the fruit in the bowl, then there is no difference. (And your friend is a hog, but that's another story.)

  25. #25
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    lmao!! Okay thank you, i get it. Just a matter of saving time and effort, which i suppose adds up to alot when you have 100 friends all wanting a banana at once!


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
  •