Jump to content

Coreinsanity

Member
  • Posts

    16
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by Coreinsanity

  1. column Name: secondgirld

    Datatype:date

     

    To echo the date in "d-m-Y" format i am using the below code

    echo date("d-m-Y", strtotime($row['secondgirld']));

     

    There is no problem when secondgirld is not equal to empty (secondgirld!='')

     

    when secondgirld field is empty (that is:secondgirld=='') it stores value as 0000-00-00 in mysql.

    But echo date("d-m-Y", strtotime($row['secondgirld']));

    shows 01-01-1970.

     

    please help to fix this problem.

    I just want to display a blank field or 00-00-0000

     

     

    strtotime returns boolean false when '0000-00-00' is passed to it. When false is provided as the second parameter in date() it returns 01-01-1970.

     

    If I were you, I would do something like:

    if ($row['secondgirld'] == '0000-00-00')
    {
     echo '';
    } else
    {
     echo date('m-d-Y', strtotime($row['secondgirld']));
    }
    

  2. That is actually no use for me.

     

    I would like to know how to put threads to the top when someone comments in the thread.

     

    I have actually thought about making my own forum, for the practice, for a while. I'm actually waiting for a friend of mine to pick up PHP, though. That way we can collaborate ideas and theories on how to do things a lot better.

     

    Getting to your question:

     

    Assuming this style of database layout:

     

    • threads table - This table would contain the thread name / Poster ID / whatever else is related to that specific thread specifically.
       
    • thread_replies table- This table would contain the post information (The various replies to the thread, containing the thread ID of the thread they belong to.)

     

    Example fields for the table `threads` (Because that's the one you'll need to focus on for this):

     

    threads:

    • thread_id (Auto-Incremented Thread ID)
    • op_id (The Original Poster's (OP) user/account ID)
    • thread_title
    • start_date (MySQL DATETIME of the date the thread was created.)

     

    Then, I would add a field `last_post_time` as either MySQL DATETIME or an INT containing the time() ( http://us3.php.net/manual/en/function.time.php ) timestamp of the latest post (Update it every time some one replies). Then in the section that lists the threads (not the replies, just the threads like you mentioned), do an:

     

    ORDER BY `last_post_time` DESC
    

     

    At the end, making the whole query something like (Just guessing, since I don't have your code I don't know the exact query or database structure you use):

     

    SELECT * FROM `threads` ORDER BY `last_post_time` DESC
    

     

    And it will return a list of threads ordering the latest post times at the top.

     

     

    Hope that helps :)

     

    Edit: Reading this post I'm not really sure if you have made a forum or a comment section on a blog post like thing (And are in fact wanting the comments to go to the top).

     

    Either way, I will leave this here. It's easily adaptable to whatever you might need it for. The main point is the DATETIME / Timestamp storage and then ordering by it descending.

  3. Hi Ben, first of all great thanks to you for this script and it is going to help me a lot at work. I was actually setting it up with our own database and added all the row names and so on. Editing, adding, viewing results works just fine. But the only problem I dealing with is when I try to delete any existing record. I believe that whenever I change

     

    DELETE FROM content WHERE id_number=$id_number

     

    in delete.php file ($id_number is the row in my custom database so had to change it), it shows different error each time. Right now if I have it like that then I get an error saying

     

     

     

    But then If I change mysql_query to

     

    DELETE FROM content WHERE id_number='$id_number'

     

    then it will not delete that file but will redirect me to listed location. Would you please help me figure out the problem?

    Here is the whole delete.php here if you need to go through it:

     

    <?php
    /* 
    DELETE.PHP
    Deletes a specific entry from the 'content' table
    */
    
    // connect to the database
    include('connect-db.php');
    
    // check if the 'id' variable is set in URL, and check that it is valid
    if (isset($_GET['id_number']) && is_numeric($_GET['id_number']))
    {
    // get id value
    $id = $_GET['id_number'];
    
    // delete the entry
    $result = mysql_query("DELETE FROM content WHERE id_number='$id_number'")
    or die(mysql_error()); 
    
    // redirect back to the view page
    header("Location: view-paginated.php?page=4");
    }
    else
    // if id isn't set, or isn't valid, redirect back to view page
    {
    header("Location: view-paginated.php?page=4");
    }
    
    ?>

     

    Thank you in advance Mr. Falk.

     

     

    I don't actually see $id_number defined in your code on that file. Are you sure you don't mean $id instead? Because I see:

    $id = $_GET['id'];

  4. Unless the properties aren't public (eg: Private and I believe protected) then you should be able to do either:

     

    $object->$object_properties['prop_name'];

     

    or

     

    $object->{$object_properties['prop_name']};

     

    Both appear to work equally for me:

     

    <?php
    class someclass {
    public $something = 356;
    
    public function __construct()
    {}
    }
    
    $c = new someclass();
    $obj_props['prop_name'] = 'something';
    
    echo $c->$obj_props['prop_name'];
    ?>
    

  5. it gets rid of the code at the top of page

     

     

    but it also gets rid of the date that usually shows in the inventory list section for the product list

     

    (if that makes sense).

     

    can not seem to win at the moment!

     

    sorry

     

     

    Can you paste the code you have so far? I will look at it more.

  6. there is no returned error

     

    just this appears at the top of the page when viewed through browser

     

     

    array

    0 => string '9' (length=1)

    'id' => string '9' (length=1)

    1 => string 'hat' (length=3)

    'product_name' => string 'hat' (length=3)

    2 => string '10' (length=2)

    'price' => string '10' (length=2)

    3 => string 'brill' (length=5)

    'details' => string 'brill' (length=5)

    4 => string 'Clothing' (length=8)

    'category' => string 'Clothing' (length=8)

    5 => string 'Hats' (length=4)

    'subcategory' => string 'Hats' (length=4)

    6 => string '2011-09-28' (length=10)

    'date_Added' => string '2011-09-28' (length=10)

     

    I think I might see your problem.

     

    First off, the var_dump helps you debug your application, in this case it might have pointed something out that could be the problem.

     

    mysql_fetch_array() by default does MYSQL_BOTH for return (Both numeric and associative arrays). So stripping out the numeric and leaving the associative ones for readability we come up with:

    (Note: If you don't know what I'm talking about with the MYSQL_BOTH, numeric and associative array stuff read: http://us.php.net/manual/en/function.mysql-fetch-array.php )

     

    array (
    'id' => string '9' (length=1)
    'product_name' => string 'hat' (length=3)
    'price' => string '10' (length=2)
    'details' => string 'brill' (length=5)
    'category' => string 'Clothing' (length=8)
    'subcategory' => string 'Hats' (length=4)
    'date_Added' => string '2011-09-28' (length=10) 
    )
    

     

    If you look at the last one, the field appears to be named

    date_Added // Notice the upper case A in Added
    

     

    and not

     

    date_added // lower case a in added
    

     

     

    So then your code for displaying the date should be:

    <?php
    //This block grabs the whole list for viewing
    $product_list = "";
    $sql = mysql_query("SELECT * FROM products");
    $productCount = mysql_num_rows($sql);//count the the output ammount
    if ($productCount > 0){
    while($row = mysql_fetch_array($sql)){
    $id = $row["id"];
    $price = $row["price"];
    $product_name = $row["product_name"];
    $date_added = strftime("%b %d, %Y", strtotime($row["date_Added"])); // Notice here how we changed it from _added to _Added
    $product_list .= "$id-$product_name    <a href='#'>edit</a> •<a href='#'>  delete</a><br/>";
    }
    
    }else{
    $product_list = "You have no products listed in your store Yet";
    }
    ?>
    

     

     

     

    Also, var_dump basically prints out the contents and variable type. So something like

    <?php
    $somevar = 10;
    vardump($somevar);
    ?>
    

     

    would print out something like:

    int(10)

     

     

    To learn more about var_dump I would recommend reading: http://us.php.net/manual/en/function.var-dump.php I find it very useful for debugging some stuff.

     

     

    Try that and see if it helps :)

  7. ia m unsure how to or where to with this code

     

    while($row = mysql_fetch_array($sql)){

    echo '<pre>';

    var_dump($row);

    echo '</pre>';

    }

     

     

    //This block grabs the whole list for viewing
    $product_list = "";
    $sql = mysql_query("SELECT * FROM products");
    $productCount = mysql_num_rows($sql);//count the the output ammount
    if ($productCount > 0){
    while($row = mysql_fetch_array($sql)){
    echo '<pre>';
    var_dump($row);
    echo '</pre>';
    }
    
    }else{
    $product_list = "You have no products listed in your store Yet";
    }
    

     

    Also to clarify something, you were on the right track doing

    $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
    

     

    As doing

     

    $date_added = strftime("%b %d, %Y", strtotime($date_added));
    

     

    is accessing $date_added before it exists.

     

    The date_added field is going to be just like any of the other fields in your database (id, product_name, etc).

  8. Maybe you should var_dump the $row variable:

     

    while($row = mysql_fetch_array($sql)){
    echo '<pre>';
    var_dump($row);
    echo '</pre>';
    }
    

     

    Because if you are doing

    $price = $row["price"];
    

     

    Then the variable $price should at least exist.

     

    Also, please put your code in the code tags. Look here for a reference on them: http://www.killersites.com/community/index.php?app=forums&module=extras&section=legends&do=bbcode (Scroll down until you see the bold and green "Code" section. It should be near the top).

     

    It would make it a heck of a lot easier to read.

    • Upvote 1
  9. I looked at your code, I had to clean it up a little in notepad++ to read it though.

     

     

    The problem is you are accessing variables that aren't created. If you look here:

    if (isset($_POST['product_name'])) {
    $product_name = mysql_real_escape_string($_POST['product_name']);
    $price = mysql_real_escape_string($_POST['price']);
    $category = mysql_real_escape_string($_POST['category']);
    $subcategory = mysql_real_escape_string($_POST['subcategory']);
    $details = mysql_real_escape_string($_POST['details']);
    // See if that product name is an identical match to another product in the system
    $sql = mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
    $productMatch = mysql_num_rows($sql); // count the output amount
    if ($productMatch > 0) {
    	echo 'Sorry you tried to place a duplicate "Product Name" into the system, <a href="inventory_list.php">click here</a>';
    	exit();
    }
    // Add this product into the database now
    $sql = mysql_query("INSERT INTO products (product_name, price, details, category, subcategory, date_added)
    VALUES('$product_name','$price','$details','$category','$subcategory',now())") or die (mysql_error()); //now adds todays date to whatever you are doing
    $pid = mysql_insert_id();
    // Place image in the folder
    $newname = "$pid.jpg";
    move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
    header("location: inventory_list.php");
    exit();
    }
    

     

    That is the only place you set $price, and you don't even define $date_added anywhere. And that spot redirects to inventory_list.php

     

    Now look at this:

    //This block grabs the whole list for viewing
    $product_list = "";
    $sql = mysql_query("SELECT * FROM products");
    $productCount = mysql_num_rows($sql); //count the output ammount
    if ($productCount > 0) {
    while($row =mysql_fetch_array($sql)) {//loops will interate over an array of data
    	$id = $row["id"];
    	$product_name = $row["product_name"];
    	$product_list .= "Product ID: $id - <strong>$product_name</strong> - $price - <em>Added $date_added</em>       <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
    }
    } else {
    $product_list = "You have no products listed in your store yet";
    }
    

     

    In here you do a mysql_fetch_array putting the result in $row. What you need to do is make the two variables in that while loop, just like you did $product_name and $id.

     

    Like so, assuming I am correctly looking at how your database and all that are layed out.

    while($row =mysql_fetch_array($sql)) {//loops will interate over an array of data
    $id = $row["id"];
    $product_name = $row["product_name"];
    $date_added = $row["date_added"];
    $price = $row["price"];
    $product_list .= "Product ID: $id - <strong>$product_name</strong> - $$price - <em>Added $date_added</em>       <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
    }
    

     

    Like Ben said, the error you were experiencing was due to a variable being called that didn't exist. You can't attempt to get the value of something that doesn't exist. If you note the one place you do set price is around line 32 I believe, and that looks to just be when you add the item. At the end of that if block of code it hits a header() which redirects the browser in tern destroying all of those variables you set in that if block.

     

     

    As far as I can tell, that is the problem you mentioned anyway.

  10. You get this error twice because you most likely have error messages turned on within your hosting. You can disable this with this line:

     

    Yeah, that's what I was saying (or intended to, anyway). Most tutorials don't go over (or ever say) to look into that. Thus, most people who I talked to who learned PHP from them simply think it's normal.

     

    ini_set( "display_errors", 0);

     

    or by manually updating your php.ini file (which probably isn't possible on a shared host, though perhaps the host could handle that for you. As a general rule, I've heard that it's best to disable display_errors on a live site, so you don't accidentally give away database/server details that might expose security holes. You can learn a bit more about this here: http://php.net/manual/en/function.error-reporting.php

     

    For this reason, I generally handle my own errors.

     

     

    In regards to using "@" for error suppression, my impression is that is generally frowned upon, and it should be used as minimally as possible.

     

    I would agree. I was mostly wondering what the reasoning behind not using it here was. (Thanks for answering, btw).

     

    To summarize others, it seems like the main reasons are:

    -- the "@" causes performance issues

     

    That is one reason. It's like I said in my post, disables error reporting - runs the code - sets error reporting to what it was:

     

    error_reporting(E_NONE);
    mysql_connect() ...
    error_reporting(whatever it was before);
    

     

    since this essentially turns one statement into 3, I can see how it would effect performance if used widely.

     

    -- Parts of the application may fail silently, and using the "@" means it is harder to tell what is going on

     

    True. With display_errors you can enable/disable them globally as you please, depending on if you're in the development environment or live.

     

    -- If you have users that are using the application and something goes wrong, giving them a "white screen of death" when something fails silently is infinitely more frustrating than at least providing an error message they can pass on to support.

     

    Never would actually plan on doing that (Though, that is why in my example I said 'Could not connect to DB')

     

    Generally, I have a nice error page setup for displaying them so that it's build into the template.

     

     

     

    For more info, see:

    http://php.net/manual/en/language.operators.errorcontrol.php

    http://stackoverflow.com/questions/136899/suppress-error-with-operator-in-php

     

    Searching for "php error suppression" will probably give you some other results as well. I'm not saying errors shouldn't be suppressed -- they should, to avoid security issues -- but you then need to provide an interface that gives the user an idea of what is failing and what is going on without showing database/server details.

     

    Yeah, leaving the errors displaying enabled by default is bad for a non-development environment. Though I always recommend logging errors (displayed or not) with some environment conditions (variables, etc, if available), and providing a way for users to report them. This way you can go back and see what happened, when it happened, and some environment stuff durring the time.

     

     

    Anyway, thanks again for your reply :)

  11. Nice tutorial, though I do have a question.

     

    This may be beyond the scope of the tutorial, but I have seen it done a lot in tutorials a friend of mine looks at to learn PHP:

     

    $db = mysql_connect('localhost','wronguser','or_wrongpass') or die (mysql_error());
    

     

    Now, with my wamp configuration (Pretty much default) and my hosting configuration (through a2 hosting) I get (as expected) the MySQL error printed out twice:

     

    > Once for the actual PHP error (due to what the error level is set to

    > And again for the or die (mysql_error());, except this time it's just the error reported from mysql.

     

    As such I have always done

    $db = @mysql_connect('localhost','wronguser','or_wrongpass') or die ('Could not connect to the DB');
    

     

    Utilizing the @ error control operator to ignore the PHP error for this statement and then removing the mysql_error (I don't want my database user printed out).

     

    I am not sure if this is best practice or not, since (to my understanding) @ simply disables error reporting then executes the statement, and returns it to normal.

     

    http://us3.php.net/manual/en/language.operators.errorcontrol.php

    If anyone wants to read up more on it, and doesn't already know about it.

     

     

    So my question, is there any real reason people don't use the @ error control operator (Sparingly, of course) for stuff like this?

  12. Hey,

     

    Sorry for the late reply, been real busy lately and forgot :/

     

    Thanks for the link, was a good read. For now I think I am going to stick with CI, though. Mostly due to how simple and quick it is for me to set up, plus what you said.

     

    After I finish teaching a friend of mine PHP I may check out ZF so both of us can sift through their docs and make sense of it better.

  13. I currently use (and like) CodeIgniter. But I keep hearing a bunch of people (Had a friend, and seen a bunch of videos) that hint that Zend Framework might be better.

     

    I am wanting to know, why? What kind of Pros and Cons are there compared with CodeIgniter?

     

    I am not dead set on using one over the other, as with a lot of things I imagine it depends on your needs.

  14. For anyone who is interested in speeding databases up:

     

    I talked to a friend of mine who is a DBA. He said that what I am doing is basically "Shotgun Indexing" which is fail. Instead, you should make an index that covers the fields in your WHERE and ON clauses (ON being inside of JOINS). He also said you should avoid sub-queries like the plague.

     

    I turned my query into two queries, the original (without sub-queries) and then the sub-query remade in a way that could be run by itself and still get all the information needed in one run. This made it run almost 2x as fast.

     

    Lastly, he also said the default WAMP configuration sucked. So I investigated the configuration files and found that innodb_ settings were commented out, I un-commented innodb_buffer_pool_size and set it to 1000M and now it runs the same query that used to take 70 seconds in about 4 - 16 with 11million entries in the database. Before all of this it took about 3 minutes to run the query with only 3 million things in the database.

     

    Anyway, hopefully some of this can help some one looking to speed up their database.

  15. I am designing a system to assist a friend of mine in keeping track of how much his bills are costing over time, and to help him keep track of what he has and hasn't paid so he can better estimate how much money he will have spare.

     

    Though, this is also mostly for practice and experience designing a system that can handle a large amount of information quickly.

    The database being used is MySQL. This is an export from phpmyadmin edited to remove all but the table generation for the tables in question.

     

    CREATE TABLE IF NOT EXISTS `bills` (
     `bill_id` int(11) NOT NULL AUTO_INCREMENT,
     `user_id` int(11) NOT NULL,
     `starting_balance` double NOT NULL,
     `ending_balance` double NOT NULL,
     `date` date NOT NULL,
     PRIMARY KEY (`bill_id`),
     KEY `date` (`date`),
     KEY `user_id` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
    CREATE TABLE IF NOT EXISTS `payments` (
     `payment_id` int(11) NOT NULL AUTO_INCREMENT,
     `srv_id` int(11) NOT NULL,
     `user_id` int(11) NOT NULL,
     `cost` double NOT NULL,
     `payment_date` date NOT NULL,
     `paid` int(1) NOT NULL DEFAULT '0',
     PRIMARY KEY (`payment_id`),
     KEY `account_id` (`user_id`),
     KEY `date` (`payment_date`),
     KEY `srv_id` (`srv_id`),
     KEY `paid` (`paid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
    CREATE TABLE IF NOT EXISTS `services` (
     `srv_id` int(11) NOT NULL AUTO_INCREMENT,
     `service_name` varchar(255) NOT NULL,
     PRIMARY KEY (`srv_id`),
     UNIQUE KEY `service_name_UNIQUE` (`service_name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
    CREATE TABLE IF NOT EXISTS `users` (
     `user_id` int(11) NOT NULL AUTO_INCREMENT,
     `username` varchar(255) NOT NULL,
     `password` varchar(255) NOT NULL,
     PRIMARY KEY (`user_id`),
     UNIQUE KEY `password_UNIQUE` (`password`),
     UNIQUE KEY `username_UNIQUE` (`username`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
    

     

    To explain the database a little:

     

    > users - Fairly straight forward, user/pass with an auto incremented user_id

    > bills - This is basically what glues the payments together. This holds the date of the bill, total initial balance, ending balance(Though thinking of removing this), the user_id that owns the bill, and an auto incremented ID for that bill.

    > payments - This contains all the payments. They are grouped with bills by having the payments.payment_date matching bills.date.

    So all the bills for 2011-05 will have bills.date LIKE '2011-05%' and all of the payments.payment_date LIKE '2011-05%'

     

    A bill overview/summary is grabbed using 2 pieces of information:

    > The user_id of the currently logged-in user

    > The year provided, which is matched with a LIKE clause.

     

    bills.date = payments.payment_date, so we can group payments with a specific billing month.

    services.srv_id = payments.srv_id so we can get the name of a given service (used in a different query when editing a specific months bill payments)

     

    I am grabbing the following data in a single query (Which I will paste below)

    bills.date,

    bills.starting_balance,

    bills.ending_balance,

    The total cost of a months bill (sum(payments.cost)),

    the min of payments.paid (paid is either 0 or 1 for paid or not),

    And then a sub-query that grabs the sum(payment.cost) where paid = 0, to get the unpaid amount in a single month.

     

    The query now:

    SELECT b.`date`, b.`starting_balance`, b.`ending_balance`, SUM(p.`cost`) as total_paid, MIN(p.`paid`) as all_paid,
          (SELECT IFNULL(SUM(p.`cost`), 0) FROM `payments` AS p WHERE p.`payment_date` = b.`date` AND p.`user_id` = b.`user_id` AND p.`paid` = 0) AS `total_unpaid`
    FROM `bills` AS b
    INNER JOIN `payments` AS p ON p.`payment_date` = b.`date`
    WHERE b.`date` LIKE '2011%'  
    AND b.`user_id` = 1
    GROUP BY b.`date`;
    

     

    Again, this works as intended - it will generate a single months bill information per row, for a general overview page. I am mostly unsure if it is good to grab all of that in one query, or if I should split it up into multiple queries? I am also wondering if I am doing indexes right in the database.

     

    Hopefully I have explained everything needed, but if not I can clarify.

     

    Thanks,

    Thomas

     

    Edit: Also, sorry if this is the wrong section - I didn't see a MySQL specific section.

×
×
  • Create New...