Jump to content

menios

Members
  • Posts

    55
  • Joined

  • Last visited

    Never

Posts posted by menios

  1. Hey guys.

     

    I hope someone can help me on this very irritating problem i cant seem to solve. Heres the brief of what i have to do:

     

    Design and implement a program that accepts three integer values from the user and then evaluates them to see if they would correspond to an equilateral, isosceles, or scalene triangle. (An equilateral triangle has three sides of equal length, an isosceles triangle has two sides of equal length, and a scalene triangle has no sides of equal length.) The result of the evaluation is then revealed to the user.

     

    *Note -

    you got to make use of the javax.swing class JOptionPane for all user interaction.

     

    two classes (in two files): the first being a “MyApplication” class that contains a main() method which instantiates an instance of a Triangle; and a second, separate class “Triangle”, that encapsulates the methods and data of a Triangle.

     

    Ok so basically from this, i have come up with this:

     

    
    package Triangle;
    
    /*
    * MyApplication.java
    */
    
    import javax.swing.JOptionPane;
    
    public class MyApplication {
    
    /** Creates a new instance of myApplication */
    public MyApplication() {
    }
    
    public static void main(String[] args  )
    {
    String message = "The Triangle Problem";
    JOptionPane.showMessageDialog( null, message );
    
    // obtain three integer values representing side lengths
    int[ ] intArray = new int[ 3 ];
    for( int i = 0; i < intArray.length; i++ )
    {
    message = "Enter an integer value for triangle side "
    + ( i + 1 ) + ":";
    
            // gather integer value representing side here…
            String input = JOptionPane.showInputDialog(null, message );
            intArray[i] = Integer.parseInt(input);
    }
            // construct and evaluate the triangle
            Triangle Triangle = new Triangle(intArray[0], intArray[1], intArray[2]);
            String outcome = Triangle.evaluate( );
    
              intArray[0] = Side1; //or s1,s2,s3 don't work either  here
              intArray[1] = Side2; 
              intArray[2] = Side3;
              Triangle Triangle = new Triangle(intArray);
              Triangle.evaluate();
    
    // present the outcome to the user
    JOptionPane.showMessageDialog( null, outcome );
    }
    }
    

     

    &

     

    package Triangle;
    /**
    * Triangle.java
    */
    import javax.swing.JOptionPane;
    
    
    public class Triangle
    {
       	private static int Side1, Side2, Side3;
    
          
            
            public Triangle (int s1 ,int s2, int s3)
    {
         Side1 = s1; 
         Side2 = s2;
         Side3 = s3;
    }
            
        	
            private static void acceptThreeIntegers( )
        {
        	String strSide1 = JOptionPane.showInputDialog( "Enter side 1: ");
            Side1 = Integer.parseInt( strSide1 );
            
        	String strSide2 = JOptionPane.showInputDialog( "Enter Side 2: ");
            Side2 = Integer.parseInt( strSide2 );
            
        	String strSide3 = JOptionPane.showInputDialog( "Enter Side 3: ");
            Side3 = Integer.parseInt( strSide3 );
        }
        
            private static void useMethod( )
        {
        	if( checkForNegatives( ) == false )
        	{
        		if (checkForTriangle() == true)
        		{    
           			String result = evaluate( );
           			JOptionPane.showMessageDialog( null, result );
        		}
        		else
           		JOptionPane.showMessageDialog( null, "Impossible", "Results", JOptionPane.PLAIN_MESSAGE );   
        	}
       		else
           	JOptionPane.showMessageDialog( null, "Impossible", "Results", JOptionPane.PLAIN_MESSAGE  );   
        	
       	}
       	private static boolean checkForNegatives( )
        {
        if (Side1 <=0 || Side2 <=0 || Side3 <=0)
           return true;
        else return false; 
        }
        
    /** evaluate if a triangle is physically possible*/
        private static boolean checkForTriangle( )
        {
        if (Side1 + Side2 - Side3 <=0 ||
            Side1 + Side3 - Side2 <=0 ||
            Side2 + Side3 - Side1 <=0)
        return false;
        else return true;
        }
    
    
        public static String evaluate( )
        {
        if (Side1 == Side2 && Side2 == Side3)
        {
        return "Equilateral";
        }
        if (Side1 == Side2 && Side2 != Side3 ||
            Side1 == Side3 && Side2 != Side3 ||
            Side2 == Side3 && Side1 != Side2)
        {
        return "Isosceles ";
        }
        if (Side1 != Side2 && Side2 != Side3 ||
            Side1 != Side2 && Side1 != Side3)
        {
        return "Scalene";
        }
        return "test value";
        }
        
        public static void main (String[] args)
        {
        	acceptThreeIntegers( );
        	useMethod( );
        }
      
        public static void Triangle (int[]intArray) {
            Side1 = intArray[0] ;
            Side2 = intArray[1] ;
            Side3 = intArray[2] ;
        }
    
    }
        

     

     

     

    I m not good at Java so  im not 100% sure on setting the values into an array and then passing it to the triangle class would work.

     

    I tried something like this:

    intArray[0] = side1 intArray[1] = side2 etc...then call the triangle using New Triangle = triangle1(intArray) then Triangle.evaluate().

    but this didnt work. I seem to have problems with the constructor i think.

     

    So yes, please can someone help me out, ive been trying and trying and i really wanna get this to work.

     

    Many thanks

  2. I m building a computer for a friend of mine with an intel 2 duo E2160 on gigabyte (ga-p31-ds3l) motherboard 2 gig ddr2 ocz memory

    i happen to have a basic anteq 350W psu. My question is the psu enough or should i use a minimum 550w psu?

    thanks in advance

  3. I have a simple cart that works with sessions when checkout is clicked the user is prompted with a form to fill with his details. I managed to do  the validation and to insert the data from the form but how can i extract the items froms my session and link them with my form?

  4. This is the Code for my cart.All works fine but one details spoils everything and i can't figure the mistake.When a new item is added to the cart there are 2 buttons next to it add and remove.All fine here but when i try to add a second item in the cart the add and remove buttons appear but my add button actually works as a remove.

    Any suggestions on what i m doing wrong?

    This is my functions

    [hr]<?php
    function writeShoppingCart() {
    $cart = $_SESSION['cart'];
    if (!$cart) {
    	return '<p>Your Cart is Empty</p>';
    } else {
    	// Parse the cart session variable
    	$items = explode(',',$cart);
    	$s = (count($items) > 1) ? 's':'';
    	return '<p>Your Cart contains <a href="cart.php">'.count($items).' book'.$s.' </a></p>';
    }
    }
    
    function showCart() {
    global $db;
    $cart = $_SESSION['cart'];
    if ($cart) {
    	$items = explode(',',$cart);
    	$contents = array();
    	foreach ($items as $item) {
    		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
    	}
    	$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
    	$output[] = '<table  border="0">';
    	$output[] = '<tr>';
    	$output[] = '<th bgcolor=#62aac4><strong>Book</strong></th>';
    	$output[] = '<th bgcolor=#62aac4>Price</th>';
    	$output[] = '<th bgcolor=#62aac4>Quantity</th>';
    	$output[] = '<th bgcolor=#62aac4 colspan=3> </th>';
    
    	$output[] = '</tr>';
    	foreach ($contents as $pd_id=>$qty) {
    		$sql = 'SELECT * FROM tbl_product WHERE pd_id = '.$pd_id;
    		$result = $db->query($sql);
    		$row = $result->fetch();
    		extract($row);
    		$output[] = '<tr>';
    					$output[] = '<td align=center><strong>'.$pd_name.'</strong></td>';
    		$output[] = '<td align=center>£'.$pd_price.'</td>';
    		$output[] = '<td align=right ><input type="text" name="qty'.$pd_id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
    		$output[] = '<td align=right><i>£'.($pd_price * $qty).'</i></td>';
    		$total += $pd_price * $qty;
    		$output[] = '<td align=center><button type="submit">Add</button></td>';
    		$output[] = '</form>';
    		$output[] = '<form action="cart.php?action=delete&pd_id='.$pd_id.'" method="post" id="cart">';
    		$output[] = '<td align=center><button type="submit" class="r">Remove</button></td>';
    		$output[] = '</tr>';
    	}
    	$output[] = '</table>';
    	$output[] = '<p><pre><strong><i>                             Total: <big></i>£'.$total.'</strong></big></pre></p>';
    
    	$output[] = '</form>';
    	$output[] = '<pre>                                <a href="testform/forma.php" target="_top">Checkout</a></pre>';
    } else {
    	$output[] = '<p>Your Cart is empty.</p>';
    }
    return join('',$output);
    }
    ?>
    

    And this is the cart

    [hr]<?php
    // Include MySQL class
    require_once('inc/mysql.class.php');
    // Include database connection
    require_once('inc/cartcon.php');
    // Include functions
    require_once('inc/functions.inc.php');
    // Start the session
    session_start();
    // Process actions
    $cart = $_SESSION['cart'];
    $action = $_GET['action'];
    switch ($action) {
    case 'add':
    	if ($cart) {
    		$cart .= ','.$_GET['pd_id'];
    	} else {
    		$cart = $_GET['pd_id'];
    	}
    	break;
    case 'delete':
    	if ($cart) {
    		$items = explode(',',$cart);
    		$newcart = '';
    		foreach ($items as $item) {
    			if ($_GET['pd_id'] != $item) {
    				if ($newcart != '') {
    					$newcart .= ','.$item;
    				} else {
    					$newcart = $item;
    				}
    			}
    		}
    		$cart = $newcart;
    	}
    	break;
    case 'update':
    if ($cart) {
    	$newcart = '';
    	foreach ($_POST as $key=>$value) {
    		if (stristr($key,'qty')) {
    			$pd_id = str_replace('qty','',$key);
    			$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
    			$newcart = '';
    			foreach ($items as $item) {
    				if ($id != $item) {
    					if ($newcart != '') {
    						$newcart .= ','.$item;
    					} else {
    						$newcart = $item;
    					}
    				}
    			}
    			for ($i=1;$i<=$value;$i++) {
    				if ($newcart != '') {
    					$newcart .= ','.$pd_id;
    				} else {
    					$newcart = $pd_id;
    				}
    			}
    		}
    	}
    }
    $cart = $newcart;
    break;
    }
    $_SESSION['cart'] = $cart;
    ?>
    <html>
    <head>
    <title></title>
    <link rel="stylesheet" href="css/styles.css">
    </head>
    
    <body>
    
    <div id="contents">
    <h1>Your Shopping Cart</h1>
    <?php
    echo writeShoppingCart();
    echo showCart();
    ?>
    <p><a href="iframe.html" target="display">Continue Shopping</a></p>
    
    </div>
    
    </body>
    </html>

  5. well i need to validate my page before submiting it to the database

    The question is how to submit it after vlidating it?

     

    The code for the form quite simple

    <?php
    // Create an empty array to hold the error messages.
    $arrErrors = array();
    $pattern = "/^[A-z0-9\._-]+"
             . "@"
             . "[A-z0-9][A-z0-9-]*"
             . "(\.[A-z0-9_-]+)*"
             . "\.([A-z]{2,6})$/";
    //Only validate if the Submit button was clicked.
    if (!empty($_POST['Submit'])) {
        // Each time there's an error, add an error message to the error array
        // using the field name as the key.
        if (!preg_match ("/^[a-zA-Z\-\'\ ]+$/u", $_POST['firstname']))
        $arrErrors['fname']= 'Please provide your First Name.';
    if (!preg_match("/^[a-zA-Z\-\'\ ]+$/u", $_POST['lastname']))
        $arrErrors['lname']= 'Please provide your Last Name.';
    if (!preg_match("/^[\w\ \+\-\'\"]+$/",$_POST['address']))
        $arrErrors['address_format']= 'Please provide your Address.';
    if (!preg_match ("/^[a-zA-Z\-\'\ ]+$/u", $_POST['town']))
        $arrErrors['town']= 'Please provide your Town.';
        if (!preg_match ("/^[a-zA-Z\-\'\ ]+$/u", $_POST['county']))
        $arrErrors['county']= 'Please provide your County.';
        if (!preg_match ("/^[a-zA-Z0-9_]{6}$/", $_POST['postcode']))
        $arrErrors['postcode']= 'Please provide your Post Code.';
    if (!preg_match ("/^[0-9_]{10}$/", $_POST['phone']))
        $arrErrors['phone']= 'Please provide your Phone Number.';		
    	if (!preg_match($pattern, $_POST['email'])) 
            $arrErrors['email_format'] = 'A valid email format is required.';
    
        if (count($arrErrors) == 0) {
            // If the error array is empty, there were no errors.
            // Insert form processing here.
        } else {
            // The error array had something in it. There was an error.
            // Start adding error text to an error string.
            $strError = '<div class="formerror1"><p><h4><img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt="">Please check the following and try again:</p></h4>';       
        }
    }
    ?>
    
    
    
    <?php echo $strError; ?>
    <!--
    For every form field, we do the following...
    
    Check to see if there's an error message for this form field. If there is, 
    add the formerror class to the surrounding paragraph block. The formerror
    class contains the highlighted box.
    
    Insert the contents of what the user submitted bak into the form field.
    
    Check again to see if this field has an error message. If it does, show
    the error icon and the error message next to the field.
    -->
    <form method="post" action="<?php echo $PHP_SELF; ?>" onreset="return confirm('Do you want to reset the form?')">
    <tr ><td width="20%"> </td><td ><p<?php if (!empty($arrErrors['fname'])) echo ' class="formerror"'; ?>>
        <label for="firstname">First Name:</label>
        <input name="firstname" type="text" id="firstname" size="30" maxlength="50" value="<?php echo $_POST['firstname'] ?>">
        <?php if (!empty($arrErrors['fname'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['fname'].'</span>'; ?></td> <td width="20%"> </td></tr>
    </p><br>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['lname'])) echo ' class="formerror"'; ?>>
        <label for="lastname">Last Name:</label>
        <input name="lastname" type="text" id="lastname" size="30" maxlength="50" value="<?php echo $_POST['lastname'] ?>">
        <?php if (!empty($arrErrors['lname'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['lname'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['address_format'])) echo ' class="formerror"'; ?>>
        <label for="address"> Address:</label>
        <input name="address" type="text" id="address" size="40" maxlength="70" value="<?php echo $_POST['address'] ?>">
        <?php if (!empty($arrErrors['address_format'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['address_format'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['town'])) echo ' class="formerror"'; ?>>
        <label for="town"> Town:</label>
        <input name="town" type="text" id="town" size="30" maxlength="32" value="<?php echo $_POST['town'] ?>">
        <?php if (!empty($arrErrors['town'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['town'].'</span>'; ?></td> <td width="20%"> </td></tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['county'])) echo ' class="formerror"'; ?>>
        <label for="county"> County:</label>
        <input name="county" type="text" id="county" size="30" maxlength="32" value="<?php echo $_POST['county'] ?>">
        <?php if (!empty($arrErrors['county'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['county'].'</span>'; ?></td> <td width="20%"> </td></tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['postcode'])) echo ' class="formerror"'; ?>>
        <label for="postcode"> Post Code:</label>
        <input name="postcode" type="text" id="postcode"size="10" maxlength="10" value="<?php echo $_POST['postcode'] ?>">
        <?php if (!empty($arrErrors['postcode'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['postcode'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['phone'])) echo ' class="formerror"'; ?>>
        <label for="phone">Phone:</label>
        <input name="phone" type="text" id="phone" value="<?php echo $_POST['phone'] ?>">
        <?php if (!empty($arrErrors['phone'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['phone'].'</span>'; ?></tr><td width="20%"> </td></tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['email_format'])) echo ' class="formerror"'; ?>>
        <label for="email">Email:</label>
        <input name="email" type="text" id="email" size="40" maxlength="80" value="<?php echo $_POST['email'] ?>">
        <?php if (!empty($arrErrors['email_format'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['email_format'].'</span>'; ?></tr><td width="20%"> </td></tr>
    </p>
    
    <p>
       <tr><td colspan="2" align="right"> <input  id="reset"  type="reset"  value="Reset"> <input  type="submit" name="Submit" value="Submit"></tr></td>
    </p>
    </form>

     

    and for inserting the data to the db

    <?php
    require_once('../inc/global.inc.php');
    if (!$conn)
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("test", $conn); // MySQL DB Name
    $firstname=mysql_real_escape_string($_POST['firstname']); //This value has to be the same as in the HTML form file
    $lastname=mysql_real_escape_string($_POST['lastname']);
    $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file
    $phone=mysql_real_escape_string($_POST['phone']);
    $town=mysql_real_escape_string($_POST['town']);
    $address=mysql_real_escape_string($_POST['address']);
    $postcode=mysql_real_escape_string($_POST['postcode']);
    $county=mysql_real_escape_string($_POST['county']);
    $sql="INSERT INTO tbl_order (firstname,lastname,email,phone,town,county,address,postcode) VALUES ('$firstname','$lastname','$email','$phone','$town','$county','$address','$postcode')"; /*Customers is the name of the MySQL table where the form data will be saved.*/
    if (!mysql_query($sql,$conn)) {
    die('Error: ' . mysql_error());
    }
    echo  "Your Details have been succesfully added to our System.";
    header("Refresh:200; url=index.php");
    echo  ("If You are not redirected automatically press here");
    mysql_close($con);
    ?> 

    hope this helps

    Thanks mate

  6. My form uses php_self to validate, i also have the query to add the content of the form to my database but how can i add it when the user hits submit and the form is validated ???

    <form method="post" action="<?php echo $PHP_SELF; ?>">
    code..
    <input  type="submit" name="Submit" value="Submit">
    </form>

  7. what do i need to add to stop users from entering any special symbols and accept only letters??

    The syntax for characters only is "/[a-zA-Z]/" if im not mistaken.

    But if the user adds any of special characters (*&^#;/\) next to a letter it gets accepted.

    How can i stop this?

  8. I just changed this

    <?php
    
    if ($_POST['email']=='')
       $arrErrors['email'] = 'A valid email address is required.';
    
    

    to this and it works so i ll do sth similar for the rest.

    if (!preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $_POST['email'])) 
       $arrErrors['email_format'] = 'A valid email format is required.';
    
    ?>
    

     

    Thanks for the tips :):)

  9. My form checks for empty cases and displays an error next to the wrong field, now  how can i add  regular expressions to the existing code to check for simple things like only letters, numbers and the email. I found the expressions but i can't manage to integrade them to my code. Any help would be really appreciated

    Here is my form.

    [size=10pt]<table cellpadding="5" align="center"  border="0" width="95%">
    <th bgcolor="#3795bc" colspan="3"><h2>Shipping & Payment Info</h2></th>
    <?php
    // Create an empty array to hold the error messages.
    $arrErrors = array();
    //Only validate if the Submit button was clicked.
    if (!empty($_POST['Submit'])) {
        // Each time there's an error, add an error message to the error array
        // using the field name as the key.
        if ($_POST['firstname']=='')
            $arrErrors['fname'] = 'Please provide your First Name.';
    if ($_POST['lastname']=='')
            $arrErrors['lname'] = 'Please provide your Last Name.';	
    if ($_POST['address1']=='')
            $arrErrors['addressa'] = 'Please provide your Address1.';	
    if ($_POST['address2']=='')
            $arrErrors['addressb'] = 'Please provide your Address2.';
    if ($_POST['town']=='')
            $arrErrors['town'] = 'Please provide your Town.';
    if ($_POST['county']=='')
            $arrErrors['county'] = 'Please provide your County.';
        if ($_POST['postcode']=='')
            $arrErrors['postcode'] = 'Please provide your Post Code.';		
    if ($_POST['phone']=='')
        $arrErrors['phone'] = 'Please provide your phone number.';
        if ($_POST['email']=='')
            $arrErrors['email'] = 'A valid email address is required.';
        if (count($arrErrors) == 0) {
            // If the error array is empty, there were no errors.
            // Insert form processing here.
        } else {
            // The error array had something in it. There was an error.
            // Start adding error text to an error string.
            $strError = '<div class="formerror1"><p><h4><img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt="">Please check the following and try again:</p></h4>';     
        }
    }
    ?>
    
    
    
    <?php echo $strError; ?><!--
    For every form field, we do the following...
    
    Check to see if there's an error message for this form field. If there is, 
    add the formerror class to the surrounding paragraph block. The formerror
    class contains the highlighted box.
    
    Insert the contents of what the user submitted bak into the form field.
    
    Check again to see if this field has an error message. If it does, show
    the error icon and the error message next to the field.
    -->
    <form method="post" action="<?php echo $PHP_SELF; ?>" onreset="return confirm('Do you want to reset the form?')">
    <tr ><td width="20%"> </td><td ><p<?php if (!empty($arrErrors['fname'])) echo ' class="formerror"'; ?>>
        <label for="firstname">First Name:</label>
        <input name="firstname" type="text" id="firstname" value="<?php echo $_POST['firstname'] ?>">
        <?php if (!empty($arrErrors['fname'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['fname'].'</span>'; ?></td> <td width="20%"> </td></tr>
    </p><br>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['lname'])) echo ' class="formerror"'; ?>>
        <label for="lastname">Last Name:</label>
        <input name="lastname" type="text" id="lastname" value="<?php echo $_POST['lastname'] ?>">
        <?php if (!empty($arrErrors['lname'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['lname'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['addressa'])) echo ' class="formerror"'; ?>>
        <label for="address1"> Address1:</label>
        <input name="address1" type="text" id="address1" value="<?php echo $_POST['address1'] ?>">
        <?php if (!empty($arrErrors['addressa'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['addressa'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['addressb'])) echo ' class="formerror"'; ?>>
        <label for="address2"> Address2:</label>
        <input name="address2" type="text" id="address1" value="<?php echo $_POST['address2'] ?>">
        <?php if (!empty($arrErrors['addressb'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['addressb'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['town'])) echo ' class="formerror"'; ?>>
        <label for="town"> Town:</label>
        <input name="town" type="text" id="town" value="<?php echo $_POST['town'] ?>">
        <?php if (!empty($arrErrors['town'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['town'].'</span>'; ?></td> <td width="20%"> </td></tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['county'])) echo ' class="formerror"'; ?>>
        <label for="county"> County:</label>
        <input name="county" type="text" id="county" value="<?php echo $_POST['county'] ?>">
        <?php if (!empty($arrErrors['county'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['county'].'</span>'; ?></td> <td width="20%"> </td></tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['postcode'])) echo ' class="formerror"'; ?>>
        <label for="postcode"> Post Code:</label>
        <input name="postcode" type="text" id="postcode" value="<?php echo $_POST['postcode'] ?>">
        <?php if (!empty($arrErrors['postcode'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['postcode'].'</span>'; ?></td><td width="20%"> </td> </tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['phone'])) echo ' class="formerror"'; ?>>
        <label for="phone">Phone:</label>
        <input name="phone" type="text" id="phone" value="<?php echo $_POST['phone'] ?>">
        <?php if (!empty($arrErrors['phone'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['phone'].'</span>'; ?></tr><td width="20%"> </td></tr>
    </p>
    <tr><td width="20%"> </td><td><p<?php if (!empty($arrErrors['email'])) echo ' class="formerror"'; ?>>
        <label for="email">Email:</label>
        <input name="email" type="text" id="email" value="<?php echo $_POST['email'] ?>">
        <?php if (!empty($arrErrors['email'])) echo '<img src="../images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><br /><span class="errortext">'.$arrErrors['email'].'</span>'; ?></tr><td width="20%"> </td></tr>
    </p>
    
    <p>
       <tr><td colspan="2" align="right"> <input  id="reset"  type="reset"  value="Reset"> <input  type="submit" name="Submit" value="Submit"></tr></td>
    </p>
    </form>[/size]

  10.  

    This example is used to valid the form data by using php with attractive error message by coloring the text

    The tutorial was found here http://www.weberdev.com/get_example-4396.html

    But the result is a bunch of code as if there is a missing bracket but thats not the case.

    Any help appreciated

     

    [hr]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <html> 
    <head> 
    <title>Form Validation</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
    </head> 
    
    <body> 
    <? 
    function error_bool($error, $field) { 
             if($error[$field]) { 
                 print("<td style=color:red>"); 
             } 
            else { 
                print("<td>"); 
            } 
        } 
    
    function show_form() { 
    global $HTTP_POST_VARS, $print_again, $error; 
    ?> 
    
    <form action="" method="post"> 
      <table width="400" border="1" cellspacing="0" cellpadding="0"> 
        <tr> 
         <?php error_bool($error, "name"); ?> Name </td> 
          <td><input name="name" type="text" id="name" value="<? echo $_POST["name"]; ?>"></td> 
        </tr> 
        <tr> 
          <?php error_bool($error, "email"); ?> Email </td> 
          <td><input name="email" type="text" id="email" value="<? echo $_POST["email"]; ?>"></td> 
        </tr> 
    
        <tr> 
          <td><input type="submit" name="Submit" value="Submit"></td> 
          <td> </td> 
        </tr> 
      </table> 
    </form> 
    <? 
    } 
    if(isset($_POST["Submit"])) { 
        check_form(); 
    } else { 
        show_form(); 
    } 
    
    function check_email_address($email) { 
      // First, we check that there's one @ symbol, and that the lengths are right 
      if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { 
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. 
        return false; 
      } 
      // Split it into sections to make life easier 
      $email_array = explode("@", $email); 
      $local_array = explode(".", $email_array[0]); 
      for ($i = 0; $i < sizeof($local_array); $i++) { 
         if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { 
          return false; 
        } 
      } 
      if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name 
        $domain_array = explode(".", $email_array[1]); 
        if (sizeof($domain_array) < 2) { 
            return false; // Not enough parts to domain 
        } 
        for ($i = 0; $i < sizeof($domain_array); $i++) { 
          if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { 
            return false; 
          } 
        } 
      } 
      return true; 
    } 
    
    
    function check_form() 
    { 
    global $HTTP_POST_VARS, $error, $print_again; 
    $error['name'] = false; 
        if($_POST["name"]=="") { 
            $error['name'] = true; 
             $print_again = true; 
            $message="The name field is empty<br>"; 
        } 
        if(!check_email_address($_POST['email'])) { 
            $error['email'] = true; 
             $print_again = true; 
            $message.="Either Field Empty or Invalid Email ID <br>"; 
        } 
         if($print_again) { 
             show_form(); 
            
           } else { 
            show_form(); 
               $message="All Fields are valid <br> 
            Now, In this way you can validate the other textfield as well<br> 
            You can insert data into table"; 
           } 
       echo "$message"; 
    } 
    
    ?> 
    
    </body> 
    </html>

  11. I ve created the form also and added  <?php $_SESSION['cart'] = $cart;?> so this will import the cart details if i m not mistaken ??? <-- IS this correct?

    so now i ll need to do the form validation and then insert everything in the database.

     

  12. I ve an iframe as my main diplay area.So the user browse, add some items to their cart view their cart and all this happens in the iframe now when the user is ready to procceed to checkout they are prompted to fill a form with their details.

    but when i add <a href="form.php">Procceed</a> the form is displayed in the iframe.I would like my link to link to the form directly not throught the iframe.How can i do this?

  13. I ve managed to setup my supersimple shopping cart it works up to the point of storring the items and quantities the user has selected.

    Its based on sessions.What i want to do next is when the user hits the procceed button to be prompted to fill a from with his/her details and then store those items in the DB. my knowledge is limited on how to do that.

    Can i have some help pls?

    Heres is my code in case it helps.

    cart.php

     

    [hr]<?php
    // Include MySQL class
    require_once('inc/mysql.class.php');
    // Include database connection
    require_once('inc/global.inc.php');
    // Include functions
    require_once('inc/functions.inc.php');
    // Start the session
    session_start();
    // Process actions
    $cart = $_SESSION['cart'];
    $action = $_GET['action'];
    switch ($action) {
    case 'add':
    	if ($cart) {
    		$cart .= ','.$_GET['pd_id'];
    	} else {
    		$cart = $_GET['pd_id'];
    	}
    	break;
    case 'delete':
    	if ($cart) {
    		$items = explode(',',$cart);
    		$newcart = '';
    		foreach ($items as $item) {
    			if ($_GET['pd_id'] != $item) {
    				if ($newcart != '') {
    					$newcart .= ','.$item;
    				} else {
    					$newcart = $item;
    				}
    			}
    		}
    		$cart = $newcart;
    	}
    	break;
    case 'update':
    if ($cart) {
    	$newcart = '';
    	foreach ($_POST as $key=>$value) {
    		if (stristr($key,'qty')) {
    			$pd_id = str_replace('qty','',$key);
    			$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
    			$newcart = '';
    			foreach ($items as $item) {
    				if ($id != $item) {
    					if ($newcart != '') {
    						$newcart .= ','.$item;
    					} else {
    						$newcart = $item;
    					}
    				}
    			}
    			for ($i=1;$i<=$value;$i++) {
    				if ($newcart != '') {
    					$newcart .= ','.$pd_id;
    				} else {
    					$newcart = $pd_id;
    				}
    			}
    		}
    	}
    }
    $cart = $newcart;
    break;
    }
    $_SESSION['cart'] = $cart;
    ?>
    <html>
    <head>
    <title></title>
    <link rel="stylesheet" href="css/styles.css">
    </head>
    
    <body>
    
    <div id="contents">
    <h1>Your Shopping Cart</h1>
    <?php
    echo writeShoppingCart();
    echo showCart();
    ?>
    <p><a href="iframe.html" target="display">Continue Shopping</a></p>
    
    </div>
    
    </body>
    </html>

     

     

    And Functions.php

     

     

    [hr]<?php
    function writeShoppingCart() {
    $cart = $_SESSION['cart'];
    if (!$cart) {
    	return '<p>Your Cart is Empty</p>';
    } else {
    	// Parse the cart session variable
    	$items = explode(',',$cart);
    	$s = (count($items) > 1) ? 's':'';
    	return '<p>Your Cart contains <a href="cart.php">'.count($items).' book'.$s.' </a></p>';
    }
    }
    
    function showCart() {
    global $db;
    $cart = $_SESSION['cart'];
    if ($cart) {
    	$items = explode(',',$cart);
    	$contents = array();
    	foreach ($items as $item) {
    		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
    	}
    	$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
    	$output[] = '<table  border="0">';
    	$output[] = '<tr>';
    	$output[] = '<th bgcolor=#62aac4><strong>Book</strong></th>';
    	$output[] = '<th bgcolor=#62aac4>Price</th>';
    	$output[] = '<th bgcolor=#62aac4>Quantity</th>';
    	$output[] = '<th bgcolor=#62aac4 colspan=3> </th>';
    
    	$output[] = '</tr>';
    	foreach ($contents as $pd_id=>$qty) {
    		$sql = 'SELECT * FROM tbl_product WHERE pd_id = '.$pd_id;
    		$result = $db->query($sql);
    		$row = $result->fetch();
    		extract($row);
    		$output[] = '<tr>';
    					$output[] = '<td align=center><strong>'.$pd_name.'</strong></td>';
    		$output[] = '<td align=center>£'.$pd_price.'</td>';
    		$output[] = '<td align=right ><input type="text" name="qty'.$pd_id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
    		$output[] = '<td align=right><i>£'.($pd_price * $qty).'</i></td>';
    		$total += $pd_price * $qty;
    		$output[] = '<td align=center><button type="submit">Add</button></td>';
    		$output[] = '</form>';
    		$output[] = '<form action="cart.php?action=delete&pd_id='.$pd_id.'" method="post" id="cart">';
    		$output[] = '<td align=center><button type="submit" class="r">Remove</button></td>';
    		$output[] = '</tr>';
    	}
    	$output[] = '</table>';
    	$output[] = '<p><pre><strong><i>                             Total: <big></i>£'.$total.'</strong></big></pre></p>';
    
    	$output[] = '</form>';
    	$output[] = '<pre>                                <button id="checkout" type="submit">Checkout</button></pre>';
    } else {
    	$output[] = '<p>Your Cart is empty.</p>';
    }
    return join('',$output);
    }
    ?>
    

  14. Hi I want my cart to have to buttons for adding and removing.I currently have one form and the submit button is ADD

    I also use an <a> for my remove.I would like to change it ot a button but how can i add 2 actions to the form so i can change my <a> tag to a <button>  tag?

     

  15. Sorry for the short description i ve experimenting with php and mysql, and i m quite new to this so please bear with me.

    I have a main index.html page that links to some .php files  for returning results to an iframe from my database when the according button (my buttons are nested lists) is pressed.

    I managed to display the items i want from the db but it's just a view.What i ve been trying to do is make each result clickable and when clicked to move to a detailed view of an items.

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