Jump to content

xtopolis

Members
  • Posts

    1,422
  • Joined

Posts posted by xtopolis

  1. Hi,

     

    I have tried googling this with the keywords "inner join", but I think I am mistaken in what I need to use.  I'm using MySQL 5.0.  My table looks like this:

    [pre]char_name      user_id    class_id    job_id    gender    height    region

    bob        8          0          0        0        0        0

    jer        44        0          2        0        0        0

    dave        6          0          0        0        0        1

    brian      17        7          5        1        1        0

    steve      118        0          0        0        0        0

    frank      92        3          3        1        0        1[/pre]

     

    The result I want would group based on class_id and have 2 columns showing the region count.  So if two people with class_id = 0 have different region values, it would show:

    class_id    region0  region1

    0            1          1

     

     

    What I want based on my data:[pre]class_id    region0    region1

    0            3          1

    7            1          0

    3            0          1

    [/pre]

     

    Can anyone help point me in the right direction for this?

     

     

     

    My table:

    CREATE TABLE `accounts` (
      `char_name` varchar(255) collate latin1_german2_ci NOT NULL,
      `user_id` tinyint(5) unsigned NOT NULL,
      `class_id` tinyint(1) unsigned NOT NULL,
      `job_id` tinyint(1) unsigned NOT NULL,
      `gender` tinyint(1) unsigned NOT NULL,
      `height` tinyint(1) unsigned NOT NULL,
      `region` tinyint(1) unsigned NOT NULL,
      UNIQUE KEY `user_id` (`user_id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german2_ci;
    
    -- 
    -- Dumping data for table `accounts`
    -- 
    
    INSERT INTO `accounts` VALUES ('bob', 8, 0, 0, 0, 0, 0);
    INSERT INTO `accounts` VALUES ('jer', 44, 0, 2, 0, 0, 0);
    INSERT INTO `accounts` VALUES ('dave', 6, 0, 0, 0, 0, 1);
    INSERT INTO `accounts` VALUES ('brian', 17, 7, 5, 1, 1, 0);
    INSERT INTO `accounts` VALUES ('steve', 118, 0, 0, 0, 0, 0);
    INSERT INTO `accounts` VALUES ('frank', 92, 3, 3, 1, 0, 1);

  2. Thanks, I was able to get it to recognize the object using your suggestion.  It also brought along another issue, see below.

    //init();
            ...
            link.onclick = this.addTime(this);//onclick

    //addTime();
    dayObject.prototype.addTime = function(objRef) {//I had tried this,placing "this" instead of objRef or w.e inside >.> so close..
            alert(objRef.counter);
    }

     

     

    However, in changing the init() onclick line, it now automatically executes the function on page load.  addTime(this) runs without clicking, etc, and clicking on the link doesn't do anything.  I have had this problem before, but not sure how I fixed it.. any ideas?  I will continue to mess around with it as well.

  3. I don't have any event handler code..  What I provided is exactly what I had up to that point.. The rest of the code that is missing would include creating SELECT and OPTION elements, and appending them to the source element..  I didn't include the addTime() code before because it is reliant on having access to the this.hoursArr variable.

     

    Perhaps I misunderstand your question?

     

    The HTML code is exactly the same.

     

    The full javascript is this:

    var hours = [ "--",1,2,3,4,5,6,7,8,9,10 ];//available hours
    var dayObjTracker = [];
    
    
    //onload bind to divs
    window.onload = function () {
        //get div for each day
        var tz = document.getElementById("timezones");
            var target_divs = tz.getElementsByTagName("div");
        
        //create day object for each day
        for(var i=0;i<target_divs.length;i++)
        {
            dayObjTracker.push( new dayObject(target_divs[i]) );
        }
    }//onload ---------------------------------------------------
    
    
    //dayObject
    function dayObject(mainElement) {
    
        this.src = mainElement;
        this.name = mainElement.className;
        this.hoursArr = hours.slice();
        this.counter = 0;
    
            this.init();
    };//dayObject -----------------------------------------------
    
    
    //init(): add links to the divs
    dayObject.prototype.init = function() {
        //create the link + attributes
        var link = document.createElement("a");
            link.appendChild(document.createTextNode("Add Time"));//link text
            link.setAttribute("href", "#");//null href
            link.onclick = this.addTime;//onclick
        
        //append link to main element
        this.src.appendChild(link);
    }//init -----------------------------------------------------
    
    
    //addTime(): request a new time block
    dayObject.prototype.addTime = function() {
    
        //create paragraph to hold it
        var p = document.createElement("p");
            p.setAttribute("id","timeblock_" + this.counter);
        
        //create "From"
        var fromTxt = document.createElement("span");
            fromTxt.setAttribute("class","fromText");
            fromTxt.appendChild(document.createTextNode("From"));
    
        //create "until"
        var fromTxt = document.createElement("span");
            fromTxt.setAttribute("class","untilText");
            fromTxt.appendChild(document.createTextNode("until"));
    
        //#############
        //create select1: name == day_start/end# (Monday_start0...)
            var startName = this.name + "_" + "start" + this.counter;
            var endName = this.name + "_" + "end" + this.counter;
    
        var select1 = makeSelect(startName, this.hoursArr, endName);
            
            //if its the first one, make it reset all others
            if(this.counter == 0) {
                select1.onchange = function() {
                    alert('ready to remove all');
                    updateOps(select1, endName);//source Element, destination name
                }
            }else{
                select1.onchange = function() {
                    updateOps(select1, endName);
                }
            }//counter == 0?
            
        //create select2
        var select2 = makeSelect(endName, this.hoursArr, "");
        
        
            //put it together
            p.appendChild(fromTxt);
            p.appendChild(select1);
            p.appendChild(untilTxt);
            p.appendChild(select2);
            
            this.src.appendChild(p);
    
    }//addTime --------------------------------------------------
    */
    
    //makeSelect(): create a <select> element
    function makeSelect(name, hoursArr, trgt) {
    
        //create select element
        var select = document.createElement("select");
            select.setAttribute("name", name);
            select.setAttribute("id", name);
            select.setAttribute("trgt",trgt);//trgt is second select in block or null
        
        var opsArr = makeOptions(hoursArr);
            var opsArr_len = opsArr.length;
        
        for(var i=0; i<opsArr_len; i++)
        {
            select.appendChild(opsArr[i]);
        }
        
        return select;//HTML element
    }//makeSelect -----------------------------------------------
    
    
    //makeOptions: create <option> element(s)
    function makeOptions(arr) {
    
        var ops = [];
        var arr_len = arr.length;
        for(var i=0; i<arr_len; i++)
        {
            var o = document.createElement("option");
                o.setAttribute("value", arr[i]);//val
                o.appendChild(document.createTextNode(arr[i]));//innerhtml
            ops.push(o);
        }
        
        return ops;//array
    }//makeOptions ----------------------------------------------
    
    //updateOps: change all elements to be higher than previous select
    function updateOps(src,dest) {
    
        var hrs = hours.slice(src.selectedIndex + 1);
        var trgt = document.getElementById(dest);
            while(trgt.hasChildNodes() && (trgt.childNodes.length >= 1)) {
                trgt.removeChild( trgt.firstChild );
            }
        var o = makeOptions(hrs);
            var o_len = o.length;
        for(var i=0;i<o_len;i++)
        {
            trgt.appendChild(o[i]);
        }
    }//updateOps ------------------------------------------------

  4. I can't figure out why I can't access the object properties in my function addTime().  The object (dayObject) is created with properties: src, name, hoursArr, counter.  (src is the parent element (HTML obj), name (str), hoursArr(array), counter(int).

     

    It calls itself with init(), which is a function that is prototyped to the dayObject.  Inside of dayObject->init(), those properties are still visible (alert(this.name))...  When I later called addTime() (which is an onclick event), it no longer sees those properties (they are undefined..)  Anyone know why?

     

    [if I had to guess what was wrong, I'd say that in the init() function, the binding of link.onclick = this.addTime doesn't provide a reference to the object itself...  I'm not sure how to provide it though, using this coding style (which I'd like to stick with)]

     

    HTML for testing:

    <html><head></head><body>
    <div id="timezones">
        <div class="Monday" id=div_Monday"></div>
        <div class="Tuesday" id="div_Tuesday"></div>
    </div><!-- timezones -->
    <script type="text/javascript" src="times.js"></script>
    </body></html>

     

    relevant Javascript (times.js)

    var hours = [ "--",1,2,3,4,5,6,7,8,9,10 ];//available hours
    var dayObjTracker = [];
    
    
    //onload bind to divs
    window.onload = function () {
        //get div for each day
        var tz = document.getElementById("timezones");
            var target_divs = tz.getElementsByTagName("div");
        
        //create day object for each day
        for(var i=0;i<target_divs.length;i++)
        {
            dayObjTracker.push( new dayObject(target_divs[i]) );
        }
    }//onload ---------------------------------------------------
    
    
    //dayObject
    function dayObject(mainElement) {
    
        this.src = mainElement;
        this.name = mainElement.className;
        this.hoursArr = hours.slice();
        this.counter = 0;
    
            this.init();
    };//dayObject -----------------------------------------------
    
    
    //init(): add links to the divs
    dayObject.prototype.init = function() {
        //create the link + attributes
        var link = document.createElement("a");
            link.appendChild(document.createTextNode("Add Time"));//link text
            link.setAttribute("href", "#");//null href
            link.onclick = this.addTime;//onclick
        
        //append link to main element
        this.src.appendChild(link);
    }//init -----------------------------------------------------
    
    
    //addTime(): request a new time block
    dayObject.prototype.addTime = function() {
        alert(this.counter);  //this comes up as undefined ##
    }

  5. The problem with wiki's is that ANYONE CAN CONTRIBUTE.  It wouldn't be much better than the forum is now IMO.

     

    Then again, I'm not a person who considers the wiki system successful.  Popular?  Sure.  However, it often puts a "educated" face on material that is prone to bias or inaccuracies.  It has succeeded in making people seem more credible than they actually are.

  6. Data Entry Form:

    Change the METHOD to POST, instead of GET.

    -Reason, GET appends the data to the url, the url has a limitation on length.  You might not hit this, but for this type of entry, I recommend using POST.  You will access the variables using $_POST instead of $_GET on the target page

     

    Data "processing" page:

    -Where ever the form points to, first validate the data (empty, valid characters, etc) rather than checking if the file you will be writing to is available.  If the data isn't good or complete, there's no need to check if the file is ready.

     

    -Validate your inputs.  (unless this is not part of the class).  Check that names only contain word characters, phone numbers only #s, and maybe () and -s, streets have #s and letters, etc, zip only #s...  You can use regular expressions if you've learned these.

     

    -Sanitize your inputs.  You have addslashes which is "ok".  There are other methods as well that you might look into: htmlentities, filter_var, [m]strlen[/n] also read this (though it's a bit beyond your scope) by Daniel0

     

    Storing the data

    from what i saw, seems to be ok.. maybe add in all the } { for your if else statements (your preference though) to make it more readable

    -Also, make sure the user data doesn't contain something that would mess up the CSV format.  (ie: including a comma in their name or address - validate that out)

     

    Read the data

    Should probably be on it's own page

    -What you have doesn't fulfill the assignment, but we'll get to that part after you're good on storing the data.

  7. Two things I saw:

    1)

    $time = date("m/d/y");

     

    2)

    $qq = mysql_query("SELECT * FROM ip_table WHERE ip='$_SERVER[REMOTE_ADDR]' AND date='$date'")

     

     

    2)"date" is a reserved word, the query should come up with an error.

    1)if "date" column is a timestamp, I don't expect '$date' to ever match it.

    Timestamps look like: YYYY-MM-DD HH:MM:SS

    $date == MM/DD/YY

     

    How can TIMESTAMP == $date ?

  8. SELECT * FROM moneyin WHERE `Date` BETWEEN 1248152400 and 1248757200

     

    That might work. BUT  Date is a reserved word, and you must enclose it in `backticks` in order for mysql to read it as a column name and not keyword.  You should change the name of the Date column.

     

    You could later add name specifications:

     

    SELECT * FROM moneyin WHERE (`Date` BETWEEN 1248152400 AND 1248757200) AND LName LIKE 'S%'

    or something.. kinda like you have it, but different.

  9. You kinda confused me there with that last post.  I have made a "simple" example.. it's not very clean, but it's to get my point across, and has most of the elements you need I think.

     

    It looks kind of long, but it's not really.  My database is setup as name_id(int), name_person(varchar255), name_data(varchar255).  The page queries back to itself for the ajax (isset($_GET['refine']))...

     

    There is a function in there called "getSelected()" which gets the id values from the listbox.  You could modify that part of it to remove / change / subtract from one box and add to another, etc depending on what you want to do.

     

    Later you see my simple AJAX (get) function.  I pass a url string of CSV values, and get them later.  I didn't bother with any validity checking for the example, but you could handle that on your own.

     

    Anyway, hopefully you can dissect this enough to get the functionality you need.  You should be able to copy paste this and change your database info to match , as long as the column order matches to see it work.  Hope this helps a bit.

     

    <?php
    $mysqli = new mysqli(databaseinfo);
    //main query
        $sql = "SELECT * FROM names WHERE 1 LIMIT 50";
        $result = $mysqli->query($sql);
        
        $select = '';
        while(list($id, $name) = mysqli_fetch_array($result)) {
        
            $select .= "<option value='$id'>$name</option>\n";
        
        }
    
    //sub query
    if(isset($_GET['refine'])){
        
        $ids = substr($_GET['refine'], 0, strlen($_GET['refine']) - 1);
        $sub_sql = "SELECT * FROM names WHERE name_id IN($ids)";
    
        $result = $mysqli->query($sub_sql);
        
        while(list($name,$data) = mysqli_fetch_array($result)) {
        
            print "$name - $data<br />";
        
        }
        exit;
    }
    ?>
    <html>
    <head>
    <script type="text/javascript">
    function loopSelected()
    {
        var txtSelectedValuesObj = document.getElementById('valuesOut');
        var selectedArray = new Array();
        var selectedString = '';
        var selObj = document.getElementById('main');
        var i;
        var count = 0;
        for (i=0; i<selObj.options.length; i++) {
            if (selObj.options[i].selected) {
              selectedArray[count] = selObj.options[i].innerHTML;
              selectedString += selObj.options[i].value + ',';
              count++;
            }
        }
        txtSelectedValuesObj.innerHTML = selectedArray;
        
        getData(selectedString);
    }
    
    //ajax element
    function newXHRO()
    {
      try { return new XMLHttpRequest(); } catch(e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
      alert("XMLHttpRequest not supported");
      return null;
    }
    
    //ajax query
    function getData(values)
    {
    
      var XHRO = new newXHRO();
      
    
      var url = 'test1.php';
        url += '?refine=' + values;
      var x = document.getElementById('dataOut');
        x.innerHTML = '<img src="http://www.xtopolis.com/imgs/loading.gif" alt="Loading..." />';
    
    
      XHRO.open('GET', url, true);
    
    
      XHRO.onreadystatechange=function()
      {
        if(XHRO.readyState==4 && XHRO.status==200)
        {
          x.innerHTML = XHRO.responseText;
        }
      }
      
      XHRO.send(null);
    
      return false;
    }
    
    </script>
    </head>
    <body>
    
        <select id="main" multiple="multiple" size="10">
            <?php echo $select; ?>
        </select>
        <input type="button" value="Get Selected" onclick="loopSelected();" />
    
        <p id="valuesOut"></p>
        
        <p id="dataOut"></p>
    </body>
    </html>

  10. Can you give me coordinate data instead?  Are you hand crafting these maps at a set size, and then randomly placing the player and women, as long as they're not in the X areas?

     

    I can kind of see what you're doing with the strings, but I'd do much better with math values for wall locations, etc I think.  If you put the data into an array, you could EASILY loop through it, and place images in a grid instead of using preg_replace.

  11. As Daniel0 pointed out, it's not a good idea.  I was kind of thinking of saying this in my main post, but I wasn't sure how to articulate it correctly.  A lot of PHP people used to (and still do >.>) store a bunch of settings in a "config" file for central access.  They were doing it because it was easy, and fit in with a procedural way of doing things (as many PHP programmers learned PHP procedurally).

     

    I would think with the "more correct" way of doing things, in OOP, there would be less constants, etc... or at least not a lot of them, and none really being depended upon outside that file (class usually).

  12. Whatever you're trying to do can work,  but I'm just not sure "what" you're doing.  When I asked about the table thing, I was referring to the derived table from your main table.

     

    ex:

    (table from database)

    Name1 - Add

    Name2 - Add

    Name3 - Add

     

    (click Name1 - Add, do your stuff)

    (database table)

    Name2 - Add

    Name3 - Add

     

    (derived table)

    Name1 - Add

     

    --------

    This new table ,"derived" table.. would this be permanent, or kept only for refining your search query?

     

    -There are MANY Ajax tutorials which show you how to get a feel for Ajax and learn the basics.  In essence, it's only getting the Javascript to behave and using the correct methods (POST, GET, and return plaintext or XML) that are the difficult parts.

     

    So let's start from the top.  What do you have?  Where (specifically, one problem at a time) are you stuck?

     

    [Also, referring back the database seems unnecessary IF you pull all records at the beginning.  You could do this all in Javascript for the "refining" portion, and only use Ajax to execute the actual search based on the 'derived' IDs in your new search table.]

     

  13. Turn Right ---->

     

     

     

    But on a serious note, what you want to do can be done easily.  The question I have is about the "selected" table.  How will the table be stored?  Is it temporary, or more permanent?.. that is up to you, but won't be much of an issue anyway.

     

    Anyway.

    -The person clicks the add button, it  can be added to a javascript array.

    -Here you can either way for them to push a button to get the data, or have it update as they click add.  The query will do you something like "SELECT name, data FROM yourTable WHERE ID IN(1,2)" [where 1 and 2 are stored IDs that have been added.

    -On that click "ADD" event, you would have javascript remove the selections from the "ADD" table so that they can't be clicked again

    -While the name,data table is updating, you can either reload the page ( modifying the add table query by making use of $_SESSION, or just use AJAX to redraw the table by doing the same select as above, but modifying it to be ..."WHERE ID NOT IN(1,2)" [again referring the selected IDs]

     

     

    Aside from that, you'll have test it yourself in small steps.  If you can get it to work in PHP first, I'd do that.  It's easy to modify it into javascript later if you already have a working PHP example.

  14. You're going to have to be a little more specific, but the author was probably referring to a "config" (type) file.

     

    The concept behind this is a centralized point to store variables that contain some globally pertinent information, but not having to change the variable across multiple files.  An example of this would be to store database configuration info (host,name,pass,dbname) in a file, then include the file when it's needed, rather than rewriting the database connectivity each time you need in in another script... (not the best example).

×
×
  • 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.