PHP - Adding Items To Sessions And Retieving Results
Hi,
Im trying to learn how to build a shopping cart system, im have a few problems and im not sure where im going wrong, it looks as though im getting an item into the session, but it looks like when i add another it over writing the first one, and im having trouble trying to echo it out. Here is what i have atm Code: [Select] session_start(); include('functions.php'); $pid = $_GET['product']; $q = $_GET['qty']; if($_GET['function']=="add") { echo "add " . $_GET['product']; $_SESSION['cart']=array(); $_SESSION['cart']['productid']=$pid; $_SESSION['cart']['qty']=$q; } print_r($_SESSION['cart']); echo showCart(); Am i way off on my code? regardless of how many things i try to add to session, all i can print out is the last one i entered. Cheers Similar TutorialsI have an array of products. The array has an ID and price. I'd like to know the most efficient way of adding up all the same ID fields in the array. Code: [Select] <?php $items[] = array( 'id' => 1, 'price' => 5.99, ); $items[] = array( 'id' => 2, 'price' => 1.99, ); $items[] = array( 'id' => 3, 'price' => 2.40, ); $items[] = array( 'id' => 2, 'price' => 6.99, ); $items[] = array( 'id' => 4, 'price' => 8, ); $items[] = array( 'id' => 2, 'price' => 3, ); $items[] = array( 'id' => 3, 'price' => 1, ); function add_like_items($items) { //manipulation return $sums; } //$sums would be an array like //$sum[1] = 5.99 //$sum[2] = 11.98 //$sum[3] = 3.40 //$sum[4] = 8 ?> Anybody have suggestions on the best way to go about doing this? Hi. I will try and explain simply.
I have a list of item codes eg.
size1 Acolor1
size1 Bcolor3
size1 Bcolor1
size1 Acolor3
size1 Acolor4
size2 Acolor1
size3 Bcolor1
size3 Bcolor2
size3 Bcolor2
size3 Acolor1
I want to take these and split them into parts:
size1 Acolor2
size1 Bcolor3
etc.
Then I want to create a form with 2 dropdowns. The first option would just have all unique sizes so:
size1
size2
size3
Then when one is selected, option 2 would show the colours available in that size.
Is there a standard way of doing this? Can I use PHP to create the array and then jquery to display and hide the options?
I'm totally stuck and i'm not just looking for somebody to code it all for me. any help would be greatly appreciated
thanks
Sam
Hi I have an array of items that I am currently displaying a foreach loop What I'm looking to do, is add a string, to all of items, a part from the last 4: foreach ($pager->getResults() as $items => $item) { echo $item->getName(); //need to add a string to this for the all but the last 4 } Thanks hello all, I was hoping someone could help me figure out how to add sizes to my shopping cart. Right now the items add just fine. The site sells shirts and I'm having trouble displaying the sizes once selected and added to the cart. It will post the size selected, but if the customer tries to add another shirt the size will overwrite the last. Any help is appreciated. Heres how I add items to the cart... Code: [Select] session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'empty': if($cart) { unset($cart); } break; case 'add': if ($cart) { $cart .= ','.$_GET['product_id']; } else { $cart = $_GET['product_id']; } break; The form with the size selection and add to cart button.. Code: [Select] <form action="cart.php?action=add&product_id=<?php echo $row_rs_products['product_id'] ?>" method="POST" name="addcart" id="addcart"> <table width="300" border="0"> <tr> <td><label for="sizes"></label> <select name="product_size" id="product_size" title="<?php echo $row_rs_products['product_size']; ?>"> <?php do { ?> <?php } while ($row_rs_sizes = mysql_fetch_assoc($rs_sizes)); $rows = mysql_num_rows($rs_sizes); if($rows > 0) { mysql_data_seek($rs_sizes, 0); $row_rs_sizes = mysql_fetch_assoc($rs_sizes); } ?> </select></td> <td><input type="submit" name="submit" id="submit" value="add to cart"> function displaying the cart.. Code: [Select] 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>'; // start div $output[] = '<div id="cart_table">'; // $output[] = '<tr>'; $output[] = '<td><h4>Product</h4></td>'; $output[] = '<td><h4>Item No.</h4></td>'; $output[] = '<td><h4>Price</h4></td>'; $output[] = '<td><h4>Size</h4></td>'; $output[] = '<td><h4>Quantity</h4></td>'; $output[] = '<td><h4>Price Total</h4></td>'; $output[] = '<td><h4> </h4></td>'; $output[] = '</tr>'; //new row foreach ($contents as $product_id=>$qty) { $sql = 'SELECT * FROM products WHERE product_id = '.$product_id; $result = $db->query($sql); $row = $result->fetch(); extract($row); // $output[] = '<tr>'; $output[] = '<td><a href="product.php?product_id='.$product_id.'">'.$product_title.'</a></td>'; $output[] = '<td>'.$product_plu.'</td>'; $output[] = '<td>$'.$product_price.'</td>'; // //$output[] = '<td>'.$product_size.'</td>'; $output[] = '<td>'.$_POST['product_size'].'</td>'; // $output[] = '<td><input type="text" name="qty'.$product_id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>X $'.($product_price * $qty).'</td>'; $total += $product_price * $qty; $output[] = '<td><a href="cart.php?action=delete&product_id='.$product_id.'" class="r">Remove</a> </td>'; $output[] = '</tr>'; //end div $output[] = '</div>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>'; $output[] = '<div class="float-right"><button type="submit">Update cart</button>'; $output[] = '</form>'; Hello, I have a database that contains a column with a int value for number of slots reserved, and what I want to do is fetch the value of each column and add them together to create one whole number. For example, in my database under preserved I have two separate values of 2 and 4.. I would like to take those two values and add them up into 6 through php... here is what I have so far: $slots = mysql_query("SELECT * FROM treservations WHERE reservation_date='$reservation_date' AND reservation_hour='$reservation_hour'") or die(mysql_error()); while ($row = mysql_fetch_assoc($slots)) { $row["preserved"]; } mysql_free_result($slots); Any help would be GREATLY appreciated.. if I need to add additional code please let me know. Thank you! If ($_GET['CODE'] == '1') { $ThreadID = mysql_escape_string($_GET['threadid']); $ForumID = mysql_result(mysql_query("SELECT forum_id FROM ".FORUM_THREADS." WHERE thread_id='{$ThreadID}'", $db), 0, 'forum_id'); $PostText = mysql_escape_string($_POST['replytext']); $IP = $_SERVER['REMOTE_ADDR']; $PostQuery = "INSERT INTO ".FORUM_POSTS." (`user_id`, `thread_id`, `post_text`, `forum_id`, `ip_address`, `timestamp`) VALUES ('{$memid}', '{$ThreadID}', '{$PostText}', '{$ForumID}', '{$IP}' , CURRENT_TIMESTAMP)"; $PostRes = mysql_query($PostQuery, $db); For some reason whenever this query goes through, it also adds a blank result using all the same information but without any $PostTest so essentially it does query: Code: [Select] INSERT INTO ".FORUM_POSTS." (`user_id`, `thread_id`, `post_text`, `forum_id`, `ip_address`, `timestamp`) VALUES ('{$memid}', '{$ThreadID}', '', '{$ForumID}', '{$IP}' , CURRENT_TIMESTAMP) This is the only query that does this part of the code and I can't see why it is adding 2 queries. FORUM_POSTS = constant containing table name. Greetings, I need a bit of php coding help. I have a query that gives me results. What I need to do is take those results and, I think, use php to compare the results and add a 1 to the correct section. Example: 3 tables table name- retail_sales id sales_id amount week table name- online_sales id sales_id amount week table name- sales_person sales_id name I have the query that breaks down results by week: week 1 | retail_sales.amount | online_sales.amount What I need is some php code that will then compare the two together and: if retail_sales.amount > online_sales.amount +1 to retail OR if retail_sales.amount < online_sales.amount +1 to online so you would end up with a result like a sports record (6-2) Any ideas Thank you for any help I added a search form on my site but I cannot figure out how to add links to the search results.
The results are being posted as the item name and the item pages look like this used-product.php?Item=102
I am not understanding how I can have that url match up with my item name.
Here is my results.php code
In the header
<?php include_once('mysql_connect.php'); if (!isset($_POST['search'])) { header ("Location:index.php"); } $search_sql="SELECT * FROM new_equip WHERE itemname LIKE '% " .$_POST ['search'] . " %'"; $search_query=mysql_query($search_sql); if(mysql_num_rows($search_query)!=0) { $search_rs=mysql_fetch_assoc($search_query); } ?>and where the results are being displayed <?phpif (mysql_num_rows($search_query)!=0){ do {?> <p><a href="new-product.php?Item=<?php echo $eid; ?>"><?php echo $search_rs ['itemname']?></a></p> <?php } while ($search_rs=mysql_fetch_assoc($search_query)) ; } else { echo "No Results Found"; } ?>I have been on this and trying to figure out another issue I am having and I cannot figure out either of them. (The other is deleting a row from a table with the click of a link) Any help on this would be greatly appreciated it. I have looked and trial and error all day and I cannot seem to get it. If there are two DataTime's which are exactly X seconds apart and the difference between those two DateTime's is added to a third DateTime, then the third DataTime's timestamp would change by exactly X seconds, true? Then why doesn't the second test below show those results, but is off by 1 day? <?php function test(string $start, string $end, string $newStart) { $startDt = new \DateTime($start); $endDt = new \DateTime($end); $intervalDt=$startDt->diff($endDt); $startSeconds=$startDt->getTimestamp(); $endSeconds=$endDt->getTimestamp(); $seconds = $endSeconds - $startSeconds; $dt = new \DateTime($newStart); $newStartSeconds=$dt->getTimestamp(); $dt->add($intervalDt); $newEndSeconds=$dt->getTimestamp(); $newSeconds = $newEndSeconds - $newStartSeconds; $newEnd = $dt->format(\DateTime::RFC3339); echo("original: $start => $end $endSeconds - $startSeconds = $seconds seconds<br>"); echo("new: $newStart => $newEnd $newEndSeconds - $newStartSeconds = $newSeconds seconds<br>"); echo("Error: seconds - newSeconds = ".($seconds - $newSeconds)); } test("2017-06-26T00:00:00Z", "2017-07-09T00:00:00Z", "2018-03-05T00:00:00Z"); echo('<br><br>'); test("2017-12-08T00:00:00Z", "2018-02-15T00:00:00Z", "2018-03-05T00:00:00Z");Quote
original: 2017-06-26T00:00:00Z => 2017-07-09T00:00:00Z 1499558400 - 1498435200 = 1123200 seconds
Hey again, Still on the same project but now doing the cart page. I've been bringing my skills up to date a lot doing this project, however, having said that I now can't figure out why my cart is not adding the items to the cart, i've checked the post data and the quantity is set to 1. Would really appreciate someone having a look at it and hopefully can see what i'm missing. you can see what it should look like (well so far lol) at here in my sandbox site. thanks again. (p.s. The parts are all over the place on the page, so thought better put whole page, sorry if shouldn't have done that) <?php // Initialize the session session_start(); // Include config file require_once "dbcontroller.php"; $db_handle = new DBController(); if(!empty($_GET["action"])) { switch($_GET["action"]) { case "add": if(!empty($_POST["quantity"])) { $productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_code='" . $_GET["product_code"] . "'"); $itemArray = array($productByCode[0]["product_code"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_code'=>$productByCode[0]["product_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["img1"])); if(!empty($_SESSION["cart_item"])) { if(in_array($productByCode[0]["product_code"],array_keys($_SESSION["cart_item"]))) { foreach($_SESSION["cart_item"] as $k => $v) { if($productByCode[0]["product_code"] == $k) { if(empty($_SESSION["cart_item"][$k]["quantity"])) { $_SESSION["cart_item"][$k]["quantity"] = 0; } $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"]; } } } else { $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); } } else { $_SESSION["cart_item"] = $itemArray; } } break; case "remove": if(!empty($_SESSION["cart_item"])) { foreach($_SESSION["cart_item"] as $k => $v) { if($_GET["product_code"] == $k) unset($_SESSION["cart_item"][$k]); if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } break; case "empty": unset($_SESSION["cart_item"]); break; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>LeaversHoodies.ie</title> <!-- Bootstrap --> <link href="css/bootstrap-4.4.1.css" rel="stylesheet"> <link href="css/accordian.css" rel="stylesheet"> </head> <body> <?php include 'header_student.php'; ?> <br /> <?php $school_page = "ravenswell"; $sql = "SELECT * FROM schools WHERE school_page = '$school_page'"; if($result = mysqli_query($conn, $sql)) while($row = mysqli_fetch_array($result)) { ?> <h3 class="text-center">Student Ordering Page For</h3> <h2 class="text-center" style="text-transform:uppercase;"><?php echo $row['school_name']; ?></h2> <hr style="width: 50%; text-align:center; border: 2px solid #00aeef; border-radius: 5px; margin: 0 auto;"> <br /> <div class="container"> <div class="row"> <div class="col"> <?php $path = "images/schools/"; $file = $row["logo"]; if(!empty($row['logo'])) { echo '<img src="'.$path.$file.'" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } else { echo '<img src="images/schools/140x140.gif" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } ?></div> <div class="col-6"> <h5>These are the garments your school has choosen :</h5><br /> <?php $school_id = $row["school_id"]; } var_dump($_SESSION); var_dump($_POST); $product_array = $db_handle->runQuery("SELECT * FROM choices INNER JOIN products USING (product_code) INNER JOIN colours USING (colour_id) WHERE school_id = '$school_id'"); if (!empty($product_array)) { foreach($product_array as $key=>$value){ ?> <div class="container"> <div class="row"> <div class="col-5" style="text-align:left;"> <img src="images/products/<?php echo $product_array[$key]["img1"]; ?>" alt="<?php echo $product_array[$key]["product_code"]; ?>" style="position:relative; top:0; width:200px; display:block;"> </div> <div class="col-7"> <h5><?php echo $product_array[$key]["product_name"]; ?></h5><p> in <?php echo $product_array[$key]["colour_name"]; ?></p> <p style="font-size:12px;"><?php echo $product_array[$key]["description"]; ?></p> <?php $comment = $product_array[$key]["comment"]; if (empty($comment)) { echo ""; } else { ?> <p style="font-size:12px;"><b>A note from your teacher:</b> <br /> <?php echo $product_array[$key]["comment"]; ?></p> <?php }; ?> <form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]["product_code"]; ?>" method="post"> <?php $product = $product_array[$key]["product_code"]; ?> Please select your size : <select id="size" name="size"> <?php $sql1 = "SELECT DISTINCT * FROM sizes WHERE product_code = '$product'"; if($result1 = mysqli_query($conn, $sql1)) while($row3 = mysqli_fetch_array($result1)){ echo "<option value='" . $row3['size'] . "'>" . $row3['size'] . "</option>"; } else { echo "nothing to see here"; } ?> </select> <br /><br /> <div class="number">How many do you want: <input type="number" style="font-size:12px;" id="quantity" name="quantity" value="1" min="1" max="5"><br /> Price : <?php echo "€".$product_array[$key]["price"]; ?> </div> <input type="hidden" id="product_code" value="<?php echo $product; ?>"><br /> <input type="submit" style="font-size:12px;" value="Add to Order" class="btnAddAction"> </form> </div> </div> <br /><hr style="width: 90%; text-align:center; border: 1px solid #00aeef; border-radius: 5px; margin: 0 auto;"><br /> </div> <?php } } else { echo "No Schools by that name registered."; } ?> </div> <div class="col-3"> <div style="border: 1px solid #d3d3d3; padding: 10px; border-radius: 5px; margin-top:30px;"> Your Order: </div> </div> </div> <div class="txt-heading">Shopping Cart</div> <a id="btnEmpty" href="student_order.php?schoolname=<?php echo $school_page; ?>?action=empty">Empty Cart</a> <?php if(isset($_SESSION["cart_item"])){ $total_quantity = 0; $total_price = 0; ?> <table class="tbl-cart" cellpadding="10" cellspacing="1"> <tbody> <tr> <th style="text-align:left;">Name</th> <th style="text-align:left;">Code</th> <th style="text-align:right;" width="5%">Quantity</th> <th style="text-align:right;" width="10%">Unit Price</th> <th style="text-align:right;" width="10%">Price</th> <th style="text-align:center;" width="5%">Remove</th> </tr> <?php foreach ($_SESSION["cart_item"] as $item){ $item_price = $item["quantity"]*$item["price"]; ?> <tr> <td><img src="images/products/<?php echo $item["img1"]; ?>" class="cart-item-image" /><?php echo $item["product_name"]; ?></td> <td><?php echo $item["product_code"]; ?></td> <td style="text-align:right;"><?php echo $item["quantity"]; ?></td> <td style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td> <td style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td> <td style="text-align:center;"><a href="student_order.php?schoolname=<?php echo $school_page; ?>?action=remove&product_code=<?php echo $item["product_code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td> </tr> <?php $total_quantity += $item["quantity"]; $total_price += ($item["price"]*$item["quantity"]); } ?> <tr> <td colspan="2" align="right">Total:</td> <td align="right"><?php echo $total_quantity; ?></td> <td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td> <td></td> </tr> </tbody> </table> <?php } else { ?> <div class="no-records">Your Cart is Empty</div> <?php } ?> </div> </div> <br /><br /> <?php include 'footer_student.php'; ?> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery-3.4.1.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/popper.min.js"></script> <script src="js/bootstrap-4.4.1.js"></script> </body> </html>
I have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that Hi all, What is the best practice when using Sessions for guest users? Hello, I would like to make a session which saves the input. To make this easier to understand i will explain my whole problem. I will have that image uploader: HTML: <input type="file" /......> <input type="submit".....> and some php behind it to upload the image. When the file will be uploaded, there will be the text if you want to continue to next page (other php file) to edit uploaded file. Now what i am asking you is: If the user clicks yes, i want the session to save name of uploaded image without extension and save it as variable, so i can use it on that another page and print it out. Thank you I have this (display_items.php) script which should not be accessed directly . user will be directed to a login page, the login checked by a check_login.php file then successful authentication will direct the user to the display_items.php page. it works perfectly on windows server but not on linux. the display_items.php script can be accessed directly on the linux server. It may have something to do with sessions but i cannot pin point the issue at the moment . i have attaced the php script files. Grateful if someone could point me in the right direction
check_login.txt display_items.txt login.txt Hi, I thought it was easier to open a new thread on a different topic. I have a css file that works fine with PHP, SQL and Sessions but this file affects my users by logging them out after a few clicks when a session is in the file due to it sometimes not recognizing the $_SESSION['identity'] where it gets undelcared. The session is the only way I can get it working from all my tests. <?php header("Content-type: text/css; charset: UTF-8"); header('Cache-control: must-revalidate'); mySessionFunction(); $identity = $_SESSION['identity']; $startquery = "SELECT `id` FROM `user_table` WHERE `identity` = :identity LIMIT 1"; $start1 = $connecting->prepare($startquery); $start1->execute(array(':identity' => $identity)); while ($start_row = $start1->fetch(PDO::FETCH_ASSOC)) { $id = $start_row['id']; $querySelect = "SELECT `car_id`, `progress` FROM `cars` WHERE `member_id` = :id LIMIT 1"; $query = $connecting->prepare($querySelect); $query->execute(array(':id' => $id)); $num = $query->rowCount(); if ($num !== 0) { while ($row = $query->fetch(PDO::FETCH_ASSOC)) { $car_id = $row['car_id']; $progress = $row['progress']; echo '.progressed'.$car_id.'{width: '.$progress.'%;}'; if ($progress === 0) { $hidden_progress = '100'; } else { $progress1 = $progress; $hidden_progress = 100 - $progress1; } echo '.hiddenprogressed'.$car_id.'{width: '.$hidden_progress.'%;}'; } } } ?> What I am looking for is how can I get this to work in a different way but to accept the id and progress into the css file. Each user will have different data, so this is why I am doing it this way. Maybe there is a better way outside of css but inline css is not allowed.
Im makigna simple login system for a sight but i only want them to have to login if they want to go to the shopping cart i have t implement a session_start() on every page before the cart page so the home page products page etc etc and then on the cart page ive a simple function that checks if their logged in if not then it will direct them to the login page if they are they should just continue is this the correct way to do it ? thanx Kind of a n00b here. on my main table (users) i named a column as "id", set it to auto-increment and as the primary key and created it like this: CREATE TABLE `users` ( `id` int(20) NOT NULL auto_increment, `full_name` varchar(200) collate latin1_general_ci NOT NULL default '', `user_name` varchar(200) collate latin1_general_ci NOT NULL default '', `user_pwd` varchar(200) collate latin1_general_ci NOT NULL default '', `user_email` varchar(200) collate latin1_general_ci NOT NULL default '', `activation_code` int(10) NOT NULL default '0', `joined` date NOT NULL default '0000-00-00', `country` varchar(100) collate latin1_general_ci NOT NULL default '', `user_activated` int(1) NOT NULL default '0', PRIMARY KEY (`id`) ) On the second table i created it like this: CREATE TABLE about_me ( about_id int NOT NULL, nick_name varchar(255), descript varchar(255), aim varchar(255), cell varchar(255), school varchar(255), music varchar(255), aspire varchar(255), City varchar(255), id int, PRIMARY KEY (about_id), FOREIGN KEY (id) REFERENCES users(id) ) I believe i imported the key correctly into my new table (about_me). Well I expected the id column to cascade down into this new table automatically which it didn't. RIght now if you log into my site and use the about me form, it posts to the new table "about_me" but it doesn't identify the user on the table with the primary key assigned to him from the first table (users). How do I use PHP sessions to identify the user by his/her id from the primary key in the table. I attached the whole site. The php for the log in is a prefab and I'm attempting to do the about me part on my own, I'm having alot of trouble with the whole sessions thing. I'm not really sure if I'm doing this correctly. so yeah any point in the right direction would be awesome! -Mike How do you set a time limit on a session? i have two files in php both have the same code and the file is Code: [Select] <?php session_start(); $con = mysql_connect("l","root",""); // here localhost and password will be filled accordingly if (!$con) { die('Connection failu ' . mysql_error()); } mysql_select_db("student",$con); $fetch=mysql_query("SELECT * from student1") or die(mysql_error()); $row = mysql_fetch_array($fetch) or die(mysql_error()); sleep(10); echo "Name: ".$row[0]."</br>"; echo " Age: ".$row[1]."</br>"; echo " Address: ".$row[2]; mysql_close($con); ?> Now i have another file which has the same code as above except there is no sleep function used in it . Now when i run the file which is wothout sleep it displyas results in seconds however the file with sleep function takes it time. Now the problem is if i load the file woth sleep function first then its delayed nature is reflected in another file which is without sleep() i.e now the file without sleep is taking longer time to open. please explain all this and possible solution to this problem the other file is Code: [Select] <?php session_start(); $con = mysql_connect("localhost","root","instablogs"); if (!$con) { die('Connection failu ' . mysql_error()); } mysql_select_db("student",$con); $fetch=mysql_query("SELECT * from student1") or die(mysql_error()); $row = mysql_fetch_array($fetch) or die(mysql_error()); echo "Name: ".$row[0]."</br>"; echo " Age: ".$row[1]."</br>"; echo " Address: ".$row[2]."</br>"; mysql_close($con); ?> I there. I am making a small game, either you or the computer win depending on who's life hit 0 first I am using sessions to hold the health values, however I need a little bit of help. How do I make it actually go down after each move until one hits 0? Here is my script and thanks in advance... Code: [Select] <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Fighting Game</title> </head> <body> <form action="fighting_game.php" method="post"> <select name='move_choice' id='move_choice'> <option value='punch'>Punch</option> <option value='kick'>Kick</option> </select> <input type='submit' name='submitbtn' value='Continue' id='submitbtn'> </form> <div id='matchdiv'> <?php $_SESSION['ai_health'] = 100; $_SESSION['player_health'] = 100; $moves_ai = array("Computer punches you in the face!","Computer kicks you in the gut!"); $moves_player = array("You punch Computer in the face!","You kick computer in the gut!"); $move_damage = array(2,10); $move_dam_multiplier_player = array(rand(1,5),rand(5,10)); $move_dam_multiplier_ai = array(rand(1,5),rand(5,10)); if($_POST['submitbtn']){ $choice = $_POST['move_choice']; } if($choice == "punch"){ $total_dam_ai=($move_damage[0]*$move_dam_multiplier_ai[0]); $total_dam_player=($move_damage[0]*$move_dam_multiplier_player[0]); echo"$moves_player[1]"." Causing ".$total_dam_player." damage!<br>"; echo"Computers current health is ". ($_SESSION['ai_health']-$move_damage[0]*$move_dam_multiplier_player[0]); echo"<br>$moves_ai[1]"." Causing ".$total_dam_ai." damage!<br>"; echo"Your current health is ". ($_SESSION['player_health']-$move_damage[0]*$move_dam_multiplier_ai[0]); } elseif($choice == "kick"){ $total_dam_ai=($move_damage[1]*$move_dam_multiplier_ai[1]); $total_dam_player=($move_damage[1]*$move_dam_multiplier_player[1]); echo"$moves_player[1]"." Causing ".$total_dam_player." damage!<br>"; echo"Computers current health is ". ($_SESSION['ai_health']-$move_damage[1]*$move_dam_multiplier_player[1]); echo"<br>$moves_ai[1]"." Causing ".$total_dam_ai." damage!<br>"; echo"Your current health is ". $new_player_health=($_SESSION['player_health']-$move_damage[1]*$move_dam_multiplier_ai[1]); } if($_SESSION['ai_health']<=0 && $_SESSION['player_health']>=0){ echo"<br>Computer falls to the ground! He is knocked out! You win!"; } if($_SESSION['player_health']<=0 && $_SESSION['ai_health'] >= 0){ echo"<br>You fall to the ground! You are knocked out! You lose!"; } if($_SESSION['player_health']<=0 && $_SESSION['ai_health'] <=0){ echo"<br>You both fall to the ground! You are both knocked out! It's a draw!"; } ?> </div> </body> </html> |