Jump to content

Drongo_III

Members
  • Posts

    579
  • Joined

  • Last visited

Posts posted by Drongo_III

  1. Sorry to jump in on this one. What does the modulus evaluate to in your if statement?

     

    Is it looking for a division by four that has no remainder and if it finds it the statement is true?

     

     

     

     

    For this effect you use the modulus operator along with a counter

     

    Example, using part of your code

    $count = 0;
    while($tir = mysql_fetch_array($tiquery)) {
    $tiid = $tir['itemid'];
    $tin = $tir['name'];
    $tiim = $tir['image'];
    $tid = $tir['description'];
    
    echo "<img src=/images/items/$tiim>";
    if($count % 4) echo "<br />\n";
    
    $count++;
    }
    

  2. Does this line in your code work?

     

     	
    
    $degree_id_query = "SELECT degree_id FROM degree WHERE degree_type ='".$degree_Array[$i]."'";
    

     

    Surely if you wrap a double quoted variable in single quotes it will be taken as a literal and not the value it represents?

     

     

     

     

    Gosh, i just figured it out. 

     

    $user_degree_insert_query = "INSERT INTO `user-degree`(

     

    user-degree didn't have the surrounding  ``.   

     

    Why is it that sometimes it seems i need these and sometimes not.

  3. The ^ character defines the start of the pattern and $ defines the end.

     

     preg_match("/^[a-zA-Z0-9]+$/") 

     

    Not sure if it makes a difference but i would always put the ^ outside of the square brackets.

     

    For your logic don't you want:

     

    
    If (pregmatch(blah blah))   //i.e. if the prematch satisfies what you want from the username grab query
    
    {
    grab database stuff
    }
    
    else {
    invalid user
    
    }
    

     

    Thanks alot for the help

    bare with me im a huge noob :)

     

    Ya i couldnt figure out why the ^ was in there i just removed that.

    I think it is working cause when I log in it says Invalid Username. So that means its working right i just have the double negitive in there?

     

    so to fix this I would need to put the else statement on the other side of $query-------------------

    is the reason its a double negitive is cause im now using preg_match instead of the ereg?

     

    Thanks

     

    <?php

    if(isset($_POST['Login'])) {

     

    if(!preg_match('[A-Za-z0-9]',$_POST['name'])){ // before we fetch anything from the database we want to see if the user name is in the correct format.

            echo "Invalid  Username.";

    }else{

     

    $query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";

    $result = mysql_query($query) or die(mysql_error());

    $row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.

  4. So besides my dubious logic inside the trim function (thanks for explaining that bit) it's ok to call a function from a while loop like this?

     

     

    array_walk_recursive is recursive for arrays. The function definition that you pass it will never receive an array as data, so you don't need the extra is_array logic inside the trim_all function.

  5. Thank Btellez

     

    Explored a bit more into headers after your suggestion and got it working along what you said

     

      
    header("Content-type: text/csv");
    		header("Content-Disposition: attachment; filename=file.csv");
    		header("Pragma: no-cache");
    		header("Expires: 0");
    
    		echo  $header . "\n" . $mydata;
    
    

     

     

    One thing I wanted to clarify.  Is it ok to called functions from within while loops.  For instance in my script I call a function from the while loop to trim the data - is that ok or do you think it's bad practice as it'll consume resources?

     

    Drongo

  6. Yeah agree with miko that what i've suggested is a dirty way of doing it and concentrating on proper structure in your tables is the preferable route to go down. It was just the simplest way of doing it imo if the task is a small one but if your database is likely to grow a lot then yes, contentrate on table structure and let the database do the processing.

     

    :)

     

     

     

     

  7. Hi Guys

     

    Another noob question.

     

    I have written a script to create a csv file from a mysql query. Bread and butter you might think...

     

    The script i've written (based on reading a few bits and a few bits there) creates the csv file in the same directory as the php script. I don't really want this to happen because the data it's pulling is a little sensitive.

     

    So  my questions:

     

    [*]How can i stop the csv from storing itself locally?

    [*]How can i output the csv directly to the browser - i.e. to initiate a download automatically

    [*]You'll notice that in the code I have a while loop within which i run a function to trim the data results as they are pulled down before placing them in the csv. I suspect that recursively calling this function is probably not the most efficient way of doing it. Any suggestions on how this should be done? I don't expect you to code it (unless you really want to) just an explanation to point me in the right direction would be fab.

     

    Any help would be very appreciated.

     

    Drongo

     

    
    
    <?php


    require_once("config.php");



    $select = "SELECT * FROM members"; 

    $export = mysql_query ( $select )
    or die ( "Sql error : " . mysql_error( ) ); 


    $fields = mysql_num_fields ( $export ); 

    for ( $i = 0; $i < $fields; $i++ )

    {   
    $header .= mysql_field_name( $export , $i ) . ","; }


    echo $header;

    $headings = explode(",", $header);


    //Set headers in first line of csv.

    $fp = fopen('test.csv', 'w');

        fputcsv($fp, $headings);
    fclose($fp);








    // Function to trim all values. Remember the pass by reference to change original value.

    function trim_all(&$value)
    {
      if (is_array($value))
      { 
    array_walk_recursive($value, 'trim_all');
      }
      else
      { 
    $value = trim(str_replace("\r\n", "\n", $value));
      }
    }





    //open file for writing
    $dp = fopen('test.csv', 'a+');
                                     
                                  // ignore this line
    mysql_data_seek($export, 0);

    // while loop runs trim on data and stores each array as csv row
    while($rows = mysql_fetch_row($export))
      {
      array_walk_recursive($rows, 'trim_all');
      print_r($rows);
      fputcsv($dp, $rows);
      }
     
    fclose($dp);



    ?>

  8. Then you can probably do this a simpler way if that's all you need to achieve.

     

    So you very simply change the link to be

     

     
    <a href="YouScript.php?inc=1"  id=""> Your Link </a>
    

     

     

    All you're doing here is sending the user to your script page and we've tacked on a little query string on the end of the link to act as a flag to the script (query string is the ?inc=1 bit) so you know the person clicked this link and didn't just  type in the uri.

     

    The scrip then runs your db query and send the user to the facebook link.

     

    Then on your script page you just do

     

      
    <?php
    
    
    if(isset ($_GET['inc'])){
         //Check to see if the inc var is set to be sure someone has clicked the link
        // Run database query to increment your counter. Can you do this?
        
        //Once you have run all database stuff successfully then change
       // header location to redirect the user
        header('Location: http://www.facebook.com/ShareSomething');
        
        
    }
    else {
       //If the inc variable isn't set then send them back to your site
        header('Location: http://www.BackToYourSite');
    }
        
    

     

     

    I assume you can work out the database bit?

     

    Drongo

     

     

     

     

    for example look:

     

    I had this link: <a href="http://www.facebook.com/ShareSomething">Click here to Share</a>

    So when the user clicks on that to share an item, then I need to increments the shares by 1 ,& direct him to the page.

  9. Hi Mate

     

    By the way - you can download the jquery library from jquery.com

     

    What exactly are you trying to achieve? If they click a link what is meant to be updated?

     

     

    Also, when the user click on the link the php script will be called which will update the database & the user will be directed to the requested URL

    thanks for your support :)

  10. You need to download jquery and save it in a file with .js extension. You can get it from the jquery website.

     

    The ajax obviously won't work without the jquery library. Sorry probably should have made that clearer.

     

    Drongo

     

     

    I had the html in a file and ajax.php now when I click on the link, I can't see it working.

    where the javascript file that is included in the html file?

    Thanks

  11. Hi

     

    I'm not 100% following what you're trying to acheive but... If you want to store multiple values in the same database record from an array, and you want it to be easily readable, you could implode your array before storing it.

     

    $comma_separated = implode(",", $your_array_name_here);
    

     

    The delimter in this case is the comma. So you could add additional records stright to the database by just adding a comma.

     

    Then when you pull the record from the database again you can just use the explode function to separate it backout into array values.

     

    Probably not the most sophisticated way of doing it but a possible solution :)

     

    Drongo

     

  12. That would likely be best achieved using jquery mate because it's not really dynamic - you're just shuffling data that's already been generated and not actually pulling new data.

     

    At any rate checkout jquery http://api.jquery.com.

     

    I think there are probably a few ways to acheive what your example does. One would be an ajax call to a script that reproduces the table based on what has been clicked. Or a less resource intensive method would be to create a jquery script to pull out the table values into an array and remake the table based on the desired sort option - though that would need some thought to pull off correctly. Hope that helps a little...

     

     

    Drongo

     

    Sorry...this is want I want to do

    http://www.dynamictable.com/

  13. Hi mate

     

    To be more helpful :)

     

    This represents your page with the link:

     

    
    <!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            
            <script type="text/javascript" src="jquery.js" ></script>
            
        </head>
        <body>
            
            
            <script type="text/javascript">        
                $(document).ready(function() {
                    $("#a").click(function() {
                        
                        $.ajax({
                            type: "POST",
                            url: "ajax.php",
                            data: "name=John&location=Boston"
                        }).done(function( msg ) {
                            alert( "Data Saved: " + msg );
                        });
                                       
                    });
                });
            </script>     
            
    <!-- YOUR TEST LINK -->
       <a href="#"  id="a"> TEST LINK </a>      
        </body>
    </html>
    
    

     

     

    Ajax bit explained

     

    The type: POST - simulates posting the data - just like posting from a html form.

    URL: This is the php script you want to send the data to.

    Data: This is the data you want to send to the script. This is hardcoded below but could be represented by variables.

    Done function : This is the function that will be executed once your ajax call has been successful and it will return whatever you send from the php script. So you can do anything to your page here.

     

     

    PHP Script - ajax.php

     

     
    <?php
    
    $name = $_POST['name'];  //access the post data you send via the ajax script
    
    echo "$name";  // whatver you echo or return will be sent back to the callback (Done function).
    
    
    
    ?>
    

     

    That php script obviously just illustrates simply how it works. But you could do a switch statement to see what variable is being sent in by the ajax and that can then make a call to a specific function to perform an action relative to the link clicked.

     

    Hope that helps.

     

    If you need any more clarification just shout :)

     

    Drongo

     

     

     

    [/code]

     

    is there any example related to my requirements.

    thanks

  14.  

    Hi mate

     

    This would need to be an ajax call.

     

    Easiest way to do it is with jquery.

     

    Check out this link for info http://api.jquery.com/jQuery.ajax/

     

    Drongo

     

     

     

     

     

    Hello,

    I had a web page which had sharing (share issue on facebook, twitter....) and I want to record what each user had shared. So, they will click on alink to share it. I want to call a php function when the user click on a link, whats the best method to do this?

    Thanks in advance

  15. Thanks for your replies guys.

     

    I think it's a hard thing to wrap your head around at first but your examples have helped me understand it a bit better - especially where you've mentioned setting private variables.  What i wasn't taking into account is the logic you put into the methods which makes them infinitely more useful.

     

    I guess this can help make your code a lot more secure if you write your __get/__set correctly.

     

    Thanks a lot for taking the time to respond chaps.

     

    Drongo

  16. Does that happen on the flat html file or just when you use an include?

     

    To be honest, and some may disagree here, but if you're using a strict Doc Type you're going to have to be a lot more sharp in your coding.  I generally always use a transitional doc type - i.e.:

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    

     

    You may find it more forgiving. Let me know if that works :)

     

    Drongo

     

    For some reason doctype removes my css effects (only on IE)

  17. Hi PFM

     

    Thanks for the spots there. I will sort the issues with the loop now and starting getting into the habit of turning all errors on too.

     

    I found an unnecessary fix for the problem in using:

     

    mysql_data_seek($export, 0) ;

     

    And after you mentioned the code before is likely causing the issue i had a realisation! I had already called mysql_fetch_row further up in my code. So i am guessing that was pushing the database pointer on one record which is why the first record was always getting missed by the loop. For some reason i assumed that a new call to the fetch the row would reset the pointer but thinking about it that would probably be very silly indeed! 

     

    Thanks for your advice. Very grateful.

     

    Drongo

     

     

     

    Best guess is that in the code that is before the code you did post, you are fetching and discarding the first row from the result set. Posting all the code from the query through to the end of your loop is the best way of getting the quickest solution.

     

    The code you did post is also producing errors on the last pass through the loop because of the equal comparison in the loop condition (and that you are starting the loop at zero.) You should only be using less-than <

     

    You should also have php's error_reporting set to E_ALL and display_errors set to ON so that php will help you by reporting and displaying all the errors it detects.

  18. I am trying to recursively pull records from a database to write to a csv.

     

    There are three test rows of data in my table (and no not including the table headers).

     

    The only issue is i can’t seem to get my for loop to display all the records – it only displays the last 2 rows so  i’m very confused.

    Anyone suggest why this isn’t working?

    $num_rows = mysql_num_rows($export);
    
    		for ($i=0; $i <= $num_rows; $i++ ) {
    
    		$row = mysql_fetch_row($export);
    		echo $row[1] . $row[2] . $row[3] . $row[4] . $row[5] .  $row[6] ."<br/>";
    		echo $i;
    
    
    
    		}

     

    Incidentally the query is just a fetch all from datasbase.

     

    Anyone see where i'm going wrong?

     

    Thanks,

     

    drongo

  19. Anyone able to help me on this one?  :confused:

     

    Hi Guys

     

    I’m trying to get my head around the magic functions __get and __set and property overloading.  From what I’ve read this sounds like a really useful thing to learn/use in the right scenario but the examples I have seen have all confused me greatly because I can’t see that the code is actually doing anything.

     

    Take the snippet below (an example of Devshed). I can follow the logic of the get set bit.

     

    
    class User
    {
    // constructor (not implemented)
    public function _construct(){}
    
    // set undeclared property
    function __set($property, $value)
    {
    $this->$property = $value;
    }
    
    // get defined property
    function __get($property)
    {
    if (isset($this->$property))
    {
    return $this->$property;
    }
    }
    
    
    
    
    // example of usage of 'User' class with property overloading
    $user = new User();
    $user->fname = 'Alejandro';
    $user->lname = 'Gervasio';
    $user->email = '[email protected]';
    $user->address = 'My address 1234';
    
    // display user data
    echo 'First Name: ' . $user->fname . ' Last Name: ' . $user->lname . ' Email: ' . $user->email . ' Address: ' . $user->address;
    /*
    displays the following
    First Name: Alejandro Last Name: Gervasio Email: [email protected] Address: My address 1234
    */
    }

     

     

     

    The part I don’t understand is where you assign something to a variable i.e.

     

    $user->fname = 'Alejandro';
    

    Because even if I wiped out everything in the class (so there is no __get __set functions) and then just did

    $user->fname = 'Alejandro';
    echo $user->fname;
    

    It still shows "Alejandro" in the browser. So I can’t see that the __get __set is actually doing anything at all.

     

    So am I missing the point and doing something wrong (likely)?

     

    Or is this just a bad example?

     

    Can someone help me to understand please :(

     

    Drongo

  20. Thanks Kicken

     

    That really helps a lot to understand it's use.

     

    I suppose part of it is understanding how php will interpret the syntax and what it interprets first - and thinking in that way.  I can see much more clearly that the curly braces allow for some very handy flexibility. I was trying all sorts to make that function call work without using curly braces and nothing did the trick.

     

    Think this is one to etch on the noggin! - or in english, 'remember'.

     

    Thank you so much for your help. This forum has helped me learn so much it's amazing :)

     

     

     

     

    The complex notation can be used around any variable in about any situation.  It's generally not required however, except in instances where your variable name may be ambiguous or contains characters not normally allowed in a name.

     

    In your original case, without the braces:

    $controller->$url[1]();
    

     

    That code could mean two things:

    1) Find the variable $url and get it's value.  Use that value as the name on $controller, get it's [1]'th element then call it as a function.

    -or-

    2) Find the variable $url and get it's [1]th element, use that as the name of a method on $controller and call it

     

    The author wants the latter,  and the braces tell PHP to do exactly that.

     

    Other cases my be something like if your putting a variable in a string next to some text, eg maybe:

    $hiliFront = '<strong style="background: yellow;"><em>';
    $hiliBack='</em></strong>';
    
    echo "Welcome {$hiliFront}Kicken{$hiliBack}, how are you today";
    //Without the braces, PHP would see the first var as $hiliFrontKicken instead of $hiliFront
    

     

    Or if a property on an object contains invalid characters, such as say:

    $sql = 'SELECT COUNT(*) FROM bleh';
    $obj = mysql_fetch_object(mysql_query($sql));
    
    echo $obj->{'COUNT(*)'}; //Though a better solution is to alias the column name
    

  21. Thanks guys

     

    That really helps a lot. I had not come across this way of calling a function in a class before and i can't bring myself to just accept that it works without understanding it as its obviously not the best way to learn. So thank you very much for setting me straight. :)

     

    Drongo

     

     

     

     

    To be more verbose...

     

    You can call a function in two ways:

    1) 

    $someClass->myFunction();

     

    2) 

    $functionName = 'myFunction';

    $someClass->{$functionName}();

     

    What you are seeing in this code is an array of strings, one of which is being used as a function name.

     

    (There are actually many more ways to call functions, I'm just trying not to break your brain).

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.