PHP - Changing Mysql Items With Checkboxes
I currently have a page where I have each row in my table listed using:
Code: [Select] $getinfo="SELECT * FROM tablename WHERE Closed='n'"; $result=mysql_query($getinfo); while ($row=mysql_fetch_array($result)){ ... // list of user information } That successfully displays my content. What I am trying to do is have a checkbox next to each user (row) that when I check them and hit submit at the bottom, it will change the value of each row on the 'Closed' column to 'y' so it will not be displayed when the page is refreshed. I want to be able to select multiple items to "close". And I would like it to come back to this page. I think I can use this page as the form action and have the code above my while loop to change the Closed column so it then would not be displayed when the while loop is called... is that right? How do I set this up? Not sure where to start the form tag and where to end it, and not sure how to...well...do any of it. Similar Tutorialshaving a small issue setting up a search, trying to use check boxes, here is my form code <form action="workorder_index.php" method="POST"> <input type="checkbox" name="wos_0" <? if($wos_0 != NULL) { echo "checked"; }?>>0 - Active <input type="checkbox" name="wos_1" <? if($wos_1 != NULL) { echo "checked"; }?>>1 - Completed awaiting pickup <input type="checkbox" name="wos_2" <? if($wos_2 != NULL) { echo "checked"; }?>>2 - Completed and out the door <input type="checkbox" name="wos_3" <? if($wos_3 != NULL) { echo "checked"; }?>>3 - Waiting call back <input type="checkbox" name="wos_4" <? if($wos_4 != NULL) { echo "checked"; }?>>4 - Waiting for parts<br> <input type="checkbox" name="wos_5" <? if($wos_5 != NULL) { echo "checked"; }?>>5 - Parts in waiting for completion <input type="checkbox" name="wos_6" <? if($wos_6 != NULL) { echo "checked"; }?>>6 - not used <input type="checkbox" name="wos_7" <? if($wos_7 != NULL) { echo "checked"; }?>>7 - Overdue for pickup <input type="checkbox" name="wos_8" <? if($wos_8 != NULL) { echo "checked"; }?>>8 - Scrapped per customer <input type="checkbox" name="wos_9" <? if($wos_9 != NULL) { echo "checked"; }?>>9 - Scrapped by overdue<br><br> <input type="hidden" value="1" name="customsearch"> <input type="Submit" value="Update"> </form> here is my handling code $wos_0=$_POST[wos_0]; $wos_1=$_POST[wos_1]; $wos_2=$_POST[wos_2]; $wos_3=$_POST[wos_3]; $wos_4=$_POST[wos_4]; $wos_5=$_POST[wos_5]; $wos_6=$_POST[wos_6]; $wos_7=$_POST[wos_7]; $wos_8=$_POST[wos_8]; $wos_9=$_POST[wos_9]; if(isset($_POST['customsearch'])) { $str=''; if($wos_0 != NULL) { $str.= "'0'"; } if($wos_1 != NULL) { $str.= ",'1'"; } if($wos_2 != NULL) { $str.= ",'2'"; } if($wos_3 != NULL) { $str.= ",'3'"; } if($wos_4 != NULL) { $str.= ",'4'"; } if($wos_5 != NULL) { $str.= ",'5'"; } if($wos_6 != NULL) { $str.= ",'6'"; } if($wos_7 != NULL) { $str.= ",'7'"; } if($wos_8 != NULL) { $str.= ",'8'"; } if($wos_9 != NULL) { $str.= ",'9'"; } $query="SELECT * FROM workorders a INNER JOIN customers b ON a.customer_id = b.customer_id WHERE a.workorder_status IN (".$str.") ORDER BY a.workorder_id"; } everything works as intended as long as the first check box remains checked, the others can be checked or not, if the first box gets unchecked I get this error Quote SELECT * FROM workorders a INNER JOIN customers b ON a.customer_id = b.customer_id WHERE a.workorder_status IN (,'1','2','3','4','5','6','7','8','9') ORDER BY a.workorder_id Warning: mysql_numrows() expects parameter 1 to be resource, boolean given in workorder_index.php on line 84 basically I can't get the commas right, ...? any help is much appreciated I was fiddling around with php and concerning data in a mysql database. All I was wanting to understand was being able to remove values with cheking multiple items in outputted html list. One that reads a set of values from a database, then displays a check box allowing the user to delete such values, that's it basically, here is my script I used to do it: Code: [Select] <?php function deleteRow($value) { $sql = "DELETE FROM checkbox WHERE value LIKE '$value'"; $result = mysql_query($sql); } if(array_key_exists('delete', $_POST)){ if(isset($_POST['value'])) { $count = count($_POST['value']); $connect = mysql_connect('localhost', 'jeremy', 's56pj989'); if($connect) { $select_db = mysql_select_db('test'); if($select_db) { for($i=0; $i<$count; $i++){ // print 'This is item = '.$_POST['value'][$i]; // outputs fine if(strlen($_POST['value'][$i]) > 0) { deleteRow($_POST['value'][$i]); } } } } } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title></title> </head> <body> <form id="myform" name="myform" action="<?=$_SERVER['PHP_SELF']; ?>" method="post"> <?php if($_SERVER['REMOTE_ADDR'] == '192.168.0.2') { // printf("<p>Yes you have connected to this script successfully!</p>"); $connect = mysql_connect('localhost', 'mydbuser', 'mydatabasepassword'); if($connect) { // printf("<p>You have now connected to the database, well done!</p>"); $select_db = mysql_select_db('test'); if($select_db) { // printf("<p>Selected database now</p>"); $sql = 'SELECT * FROM checkbox'; $result = mysql_query($sql); if($result) { if(mysql_num_rows($result)>0){ while($row = mysql_fetch_assoc($result)) { printf("%s <input type=\"checkbox\" name=\"value[]\" value=\"%s\">\n<br />\n", $row['value'], $row['value']); } } else { printf("<p>No rows in system!</p>"); } } } } } ?> <input type="submit" id="delete" name="delete" value="Delete" /> </form> </body> </html> There must be a better way shouldn't there? I am not too concerned with error checking, ie if result of removing the values doesnt work, since I will just use this as an example of how to do this. Going on from that, how would I allow it to update a set of say changed values, just purely out of interest, pretty happy since it works though this script. But I was also wondering if there's some easy way of updating a set of values perhaps? Hmm good though and I look forward to any replies, Jeremy. Hey everyone. [= I don't have much time to read through all of the forums, because I'm on a time crunch and I'll be putting this certain project behind a couple others while I wait for some answers. This project is confusing me a bit, because I haven't worked much with arrays and the good ol' checkbox, so I need some help getting this to work. This project requires me to set-up a checkbox next to each order that was pulled off a database. You are allowed to select as many checkboxes as you'd like, and then click on the "process receipts" for all of the orders that were selected. I need to be able to have the form send me straight to a new page that pulls a loop of receipts one after another. I have the receipts built, and I can access a receipt one at a time based off the ID of a certain order, and I can easily build a loop that presents the receipts. I'm just having a problem pulling the information off the database based from the checkbox array. If you can give me some ideas on where to start with this, I'd greatly appreciate it. Note: Example is inside a hidden administrative page. Can't really give you something to play with, sorry! QQ Thanks! Alex D.A. Designing Hey all... I'm running into a problem here. If you take a look at the code for this, you'll see it's to enter "horses" into a "class." It's all fine and dandy except I'm trying to get the way the horses are selected to have a different option. Right now they exist as a drop down/select option where you have to choose one at a time and enter submit. My goal is to have checkboxes that users can toggle and submit them all at once (with the rest of the eligibility checks etc still applicable). I've looked it up and the problem is, each user has a different amount of horses, so I can't account for all of them manually. Could someone help me out? On DaniWeb a user was trying to help me with an implode option, but I have zero idea how to work with that. I will literally need my hand to be held through this one. Thank you in advance - I have been trying to do this myself for a good chunk of the day, but my PHP skills are quite limited. Code: [Select] <?php session_start(); // Maintain session state header("Cache-control: private"); // Fixes IE6's back button problem. $page_title = "Class Information"; include('header.php'); $class_id = $_GET['id']; $enter = $_POST['enter_horse']; $enter_check = $_POST['check']; $horse_id = $_POST['horse_id']; //general show information $result = @mysql_query("SELECT s.show_id, s.player_id, s.type, s.name, DATEDIFF(s.run_date, NOW()) AS datedif, c.class_id, s.entry_fee FROM classes c, shows s WHERE c.class_id='$class_id' AND c.show_id=s.show_id LIMIT 1")or die("Cannot find class! " . mysql_error()); $row = @mysql_fetch_array($result); $show_id = $row['show_id']; $show_name = $row['name']; $runs_in = $row['datedif']; $species = $row['species']; $type = $row['type']; $owner_id = $row['player_id']; if(!$row['class_id']){myError("Invalid class!");include('footer.php');} $entry_fee = $row['entry_fee']; $num_entries = @mysql_num_rows(@mysql_query("SELECT horse_id FROM horses_entered WHERE class_id='$class_id'")); $runs_in = "$runs_in day[s]"; if($enter){ //ensure horse is eligible to enter $good = @mysql_num_rows(@mysql_query("SELECT horse_id FROM horses WHERE horse_id='$horse_id' AND player_id='$player_id' AND age>=2 AND age<=20")); $exists = @mysql_num_rows(@mysql_query("SELECT horse_id FROM horses_entered WHERE horse_id='$horse_id' AND class_id='$class_id' LIMIT 1")); if($my_money < $entry_fee){myError("You cannot afford the entry fee.", 1);} if(!$good){myError("Are you sure you own the horse and it is between 3 and 20 years of age?"); }elseif($exists){myError("That horse is already entered in this class!"); }else{ @mysql_query("INSERT INTO horses_entered(horse_id, class_id) VALUES('$horse_id', '$class_id')")or die("Cannot create entry!"); if($type == 1 AND $entry_fee){@mysql_query("UPDATE players SET money=money+'$entry_fee' WHERE player_id='$owner_id' LIMIT 1")or die("Cannot update player money!"); $points=1; }elseif($type == 2 AND $entry_fee){@mysql_query("UPDATE clubs SET money=money+'$entry_fee' WHERE president='$owner_id' LIMIT 1")or die("Cannot update player money2!"); $points=2;} @mysql_query("UPDATE players SET money=money-'$entry_fee', points=points+'$points' WHERE player_id='$player_id' LIMIT 1")or die("Cannot update player money3! " . @mysql_error()); @mysql_query("UPDATE horses SET points=points+'$points' WHERE horse_id='$horse_id' LIMIT 1")or die("Cannot update horse points!"); myError("Class entered!"); } } //display the show information echo "<table> <tr><td><b>Class:</td><td>#$class_id</td></tr> <tr><td><b>Show:</td><td><a href='shows.php?id=$show_id'>$show_name (#$show_id)</a></td></tr> <tr><td><b>Runs:</td><td>$runs_in</td></tr> <tr><td><b>Entry Fee:</td><td>$$entry_fee</td></tr> <tr><td><b>Total Entrants:</td><td>$num_entries</td></tr> <tr><td valign=top><b>Your Horses:</td><td> <form action='classes.php?id=$class_id' method=POST> <select name='horse_id'> "; $result = @mysql_query("SELECT horse_name, breed, horse_id FROM horses WHERE player_id='$player_id' AND age>2 AND age<=20 ORDER BY horse_name ASC")or die("Cannot find horses! " . mysql_error()); while($row = @mysql_fetch_array($result)): $horse_id = $row['horse_id']; $horse_name = stripslashes($row['horse_name']); $breed = $row['breed']; echo "<option value='$horse_id'>$horse_name (#$horse_id), $breed</option>\n"; $prev_species = $species; endwhile; if(!$horse_id){echo "<option value=0>No eligible horses!";} echo " </select> <input type=submit name='enter_horse' value='Enter Horse!'></td></tr></form> <tr><td valign=top><b>Entrants:</td><td> "; $query = "SELECT h.horse_name, h.horse_id, h.breed FROM horses_entered he LEFT JOIN horses h ON he.horse_id=h.horse_id WHERE he.class_id='$class_id' ORDER BY h.horse_name ASC"; $result = @mysql_query($query)or die(mysql_error()); while($row = @mysql_fetch_array($result)): $name = $row['horse_name']; $aid = $row['horse_id']; $breed = $row['breed']; $page = "horses.php"; echo "<a href='$page?id=$aid'>$name (#$aid)</a>, $breed<br>\n"; endwhile; if(!$aid){echo "<i>No entrants.";} echo "</td></tr> </table>"; include('footer.php'); ?> I built a series of insertion forms to put entries into a mysql database. Everything is working fine, except that I just now realized my checkboxes don't put any entry in. It's just leaving it's respective smallint field as a default "0". Being new, I've must've overlooked how to handle these. The form's checkboxes have a bit of code in the value that remembers what users chose in case they have to backtrack and redo their form. How would I solve the problem and keep this code? Here's what all the checkboxes are written like: Code: [Select] <input type="checkbox" name="green_leaf" value="<?php if(isset($_POST['1'])) echo $_POST['1']; ?>" > green I have figured out far enough to loop through my table and return a list of check boxes that will be matched to a product. My issue now, is i cannot figure out the proper way to loop through them after they are selected and return them as checked/unchecked for the given product. Thought there is some MySQL involved, that part isn't the problem, I know how to insert into a database or update...when the product is selected from a drop down, I need to be able to populate the checkboxes. Here is the code i am using to initially display all of the categories to choose from... <ul class="categories"> <?php $query = "SELECT * FROM products"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_assoc($result)) { $category = $row['category']; $catId = $row['id']; echo "<li><input class='catCheck' type='checkbox' name='p_cat[]' value='$catId' /> $category</li>"; } ?> </ul> Thanks guys.... Hi people. I have a form which inputs into a database. Here is the code that inserts a yes no option... Code: [Select] <select name = "consent"> <option value = "Yes" <?php if ($_POST['consent'] == 'Yes') { echo 'selected="selected"'; } ?>>Yes</option> <option value = "No" <?php if ($_POST['consent'] == 'No') { echo 'selected="selected"'; } ?>>No</option> </select> However, I have been asked if I can make it a yes or no checkbox instead. Please can you tell me how I need to code it so that the "yes" or "no" is recorded in the DB. At the moment I just have this Code: [Select] <input name="consent" type="checkbox" value="Yes" />Yes<br /> <input name="consent" type="checkbox" value="No" />No<br /> Thanks in advance VinceG I have a table in a mysql database with 5 columns, id, Name, Wifi, Bluetooth, GPS, with rows that are for example 1, Galaxy S2, yes, yes, yes. So basically i want to build a form that has check boxes (3 checkboxes for wifi bluetooth and GPS respectively) that once selected will query the database depending on which check boxes are selected. I have made the form but need to know what to put in the filter.php to make the results be displayed accordingly. Ideally if anyone knows how i would want it so the results were shown on the same page which i believe u need to use ajax to happen but any help on how to show the results will be greatful. the code for the form i have made is as follows: Code: [Select] <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title> </head> <body> <form action="filter.php" method="post"> <INPUT TYPE=CHECKBOX NAME="option[]" VALUE="Wifi" id="r1">Wifi <INPUT TYPE=CHECKBOX NAME="option[]" VALUE="Bluetooth" id="b1">Bluetooth <INPUT TYPE=CHECKBOX NAME="option[]" VALUE="GPS" id="g1">GPS <input type="submit" name="formSubmit" value="Submit" /> </form> </body> </html> im not sure on how to make the filter.php page but i do have this code for displaying the all the data but i want to kno how to make it only display the data from the choices on the checkboxes Code: [Select] <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>pls work</title> </head> <body> <?php function h($s) { echo htmlspecialchars($s); } mysql_connect("localhost", "root", "") or die (mysql_error()); mysql_select_db("project") or die (mysql_error()); $result= mysql_query('SELECT * FROM test') or die('Error, query failed'); ?> <?php if (mysql_num_rows($result)==0) { ?> Database is empty <br/> <?php } else { ?> <table> <tr> <th></th> <th>Name</th> <th>Wifi</th> <th>Bluetooth</th> <th>GPS</th> </tr> <?php while ($row= mysql_fetch_assoc($result)) { ?> <tr> <td> <a href="uploaded-images/<?php h($row['Name']); ?>.jpg"> <img src="uploaded-images/<?php h($row['Name']); ?>.jpg" alt="test"/> </a> </td> <td><a href="textonly.html"><?php h($row['Name']); ?></a></td> <td><?php h($row['Wifi']); ?></td> <td><?php h($row['Bluetooth']); ?></td> <td><?php h($row['GPS']); ?></td> </tr> <?php } ?> </table> <?php } ?> </body> </html> Hello, In my Mysql database, it has a datetime field. and I have created a $today = date('Y-m-d H:i:s'); <- today's date and time How do I write a query to run in PHP in order to get all today's items by comparing datetime field and $today? Thanks! This is probably some obvious error I have made, but I cannot figure it out. I have made a few pages and now I am debugging them. My first page is called insert_purchase_order.php; on this page a person will enter some data in fields and hit the insert button. Then, the data is passed to another page, but when I try to insert into mysql it does not give me any errors, but I have no new rows either. The code for my 2nd page: Code: [Select] <?php session_start(); $action=$_GET[action]; if ($action==insert){ $randid=$_POST['randid']; $vendor=$_POST["vendor"]; $purchase_order_date=$_POST["purchase_order_date"]; $ship=$_POST["ship"]; $fob=$_POST["fob"]; $terms=$_POST["terms"]; $buyer=$_POST["buyer"]; $freight=$_POST["freight"]; $req_date=$_POST["req_date"]; $confirming_to=$_POST["confirming_to"]; $remarks=$_POST["remarks"]; $tax=$_POST["tax"]; $con = mysql_connect("localhost","root","pass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("main", $con); mysql_query("INSERT INTO purchase_order (randid, vendor, purchase_order, ship, fob, terms, buyer, freight, req_date, confirming_to, remarks, tax) VALUES ($randid, $vendor,$purchase_order_date,$ship, $fob, $terms, $buyer, $freight, $req_date, $confirming_to, $remarks, $tax)"); mysql_close($con); echo 'Data Accepted...'; echo '<br/>'; echo 'P.O. Inserted Successfully'; }else{ echo 'Error... Please Contact Bruce.'; echo 'Bruce, no data was passed from the insert_purchase_order.php page.'; } ?> <a href="http://localhost/insert_purchase_order_items.php?po= <?php echo $randid; ?>">Insert Purchase Order Items</a> I have permissions and everything. Thanks Hi, I am having difficulty deleting rows in my table using check boxes. I have all the check boxes displaying for each row and a delete button below the table. However when i click on the delete button it isnt deleting the checked rows, i have displayed the code below that i am using; Code: [Select] <?php $result = mysql_query("SELECT * FROM contact ORDER BY msg_id ASC"); echo "<table border='1'> <tr> <th>Delete</th> <th>Message ID</th> <th>Name</th> <th>Email</th> <th>Message</th> </tr>"; while($row = mysql_fetch_array($result)) { ?> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['del_id']; ?>"></td> <?php echo "<td>" . $row['msg_id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['msg'] . "</td>"; echo "</tr>"; } echo "</table>"; ?> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <?php // Check if delete button active, start this if(isset($_GET['delete'])) { for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM contact WHERE id=".$_GET['del_id']; $result = mysql_query($sql); } // if successful redirect to delete_multiple.php if($result){ } } mysql_close(); ?> Please help Thank you how to cross reference $_POST array 'checkboxes[]' with mysql field I have a form that is submitted so the user can select which results to print. but I am having problems getting the results to show correctly. how do I correctly cross reference the form data with the mysql Code: [Select] $getRequests = mysql_query("SELECT * FROM requests WHERE `customer_email`='{$_SESSION['FM_user']}'"); while($request = mysql_fetch_assoc($getRequests)) { if (!in_array($request['request_id'],array($_POST[request]))) { echo '<li style="font-size:10px; border-bottom: 0.1em solid #D0D0D0"> <div class="leftfloat"> <input type="checkbox" name="request[]" value="',$request['request_id'],'"> </div> <div class="leftfloat"> <em>',$request['request_id'],'</em> </div><div class="leftfloat"> | </div> <div class="leftfloat"> <em>',$request['customer_name'],'</em> </div><div class="leftfloat"> | </div> <br style="clear:both"> </li>'; } } I've been playing around with this code from http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart Objective: I'm trying to make the scripts work but without pulling the data from MySQL Database. Instead, I created an array and inserted some info there and trying to replicate the same results but getting confused. For example, on the Index.php file, I made the following changes: <?php // Start the session session_start(); // Include functions require_once('inc/functions.inc.php'); // Products multidimensional Array $products = array("book" => array( 'id' => '1', 'title' => 'Learn Your ABC\'s', 'author' => 'John Doe', 'price' => '14.95'), "video" => array('id' => '2', 'title' => 'Visual Guide to learn', 'author' => 'Adam Smith', 'price' => '21.38'), "puzzle" => array('id' => '3', 'title' => 'Can You Solve?', 'author' => 'Sara Brown', 'price' => '9.41'), "exam" => array('id' => '4', 'title' => 'Test Your Knowledge', 'author' => 'Kim Carver', 'price' => '11.15')); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php /* $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); */ ?> <?php $output[] = '<ul>'; foreach ($products as $product => $product_item) { // $flavor is the key and $piece is the value foreach ($product_item as $item => $piece) { if ($item == "id") { # Conditional logic defined to map specific keys to specified name value $row['id'] = $piece; // echo "The id is ". $id."<br />"; // set just to confirm value correct for variable } elseif ($item == "title") { # Conditional logic defined to map 1st key to price value $row['title'] = $piece; // echo "The title is ". $title."<br />"; // set just to confirm value correct for variable } elseif ($item == "author") { # Conditional logic defined to map 1st key to price value $row['author'] = $piece; // echo "The author is ". $author."<br />"; // set just to confirm value correct for variable } elseif ($item == "price") { # Conditional logic defined to map 1st key to shipping value $row['price'] = $piece; // echo "Price: ". $price."<br /><br />"; // set just to confirm value correct for variable } $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; $output[] = '</ul>'; echo join('',$output); } } ?> </div> </body> </html> And here's the original index.php before my edits which show the sql query to the db: <?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(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> </div> </body> </html> Also, I included the zipped file of the entire script setup. Again, I'm trying to figure out how to make the cart work with using an array for the product instead of MySQL database. My goal is to remove ALL SQL statements from the scripts but stuck with the looping portion to display the title, author, and price from the array as shown above. 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 Guys,
Been trying to make it that when I insert into Mysql at the moment it inserts like dd-mm-yy, however cause I'm in the UK i need it to do it in the UK way of dd-mm-yy I checked out some topics and found the STR_DATE_DATE however I've tried to use it in my mysql but cannot get it to work. Can someone help
$query="INSERT INTO job_scheduled (startdate, enddate, job_title, job_reference, job_description, job_postcode, job_city, customername, customer_email, status) VALUES ('".STR_TO_DATE($_SESSION["startdate"],'%d-%m-%y')."', '".$_SESSION["enddate"]."', '".$_SESSION["job_title"]."', '".$_SESSION["job_reference"]."', '".$_SESSION["job_description"]."', '".$_SESSION["job_postcode"]."', '".$_SESSION["job_city"]."', '".$_SESSION["customername"]."', '".$_SESSION["customer_email"]."', 'Provisional')"; I have a prepared statement class for MYSQL, since in PHP 5 this is now changing to mysqli; I'm looking for some help in changing the code from my existing class to the new mysqli.
I have done some research online about changing from mysql to mysqli but the changes I made seems to only cause issues with connecting to the database.
After many hours of changing the existing file using the research online, I've decided to start again and ask others if they would be ever so kind to help this noob out and point out which parts of the script needs to be changed.
Thank you for reading.
<?php class Database { private $host; private $user; private $pass; private $name; private $link; private $error; private $errno; private $query; function __construct($host, $user, $pass, $name = "", $conn = 1) { $this -> host = $host; $this -> user = $user; $this -> pass = $pass; if (!empty($name)) $this -> name = $name; if ($conn == 1) $this -> connect(); } function __destruct() { @mysql_close($this->link); } public function connect() { if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass, TRUE)) { if (!empty($this -> name)) { if (!mysql_select_db($this -> name, $this->link)) $this -> exception("Could not connect to the database!"); } } else { $this -> exception("Could not create database connection!"); } } public function close() { @mysql_close($this->link); } public function query($sql) { if ($this->query = @mysql_query($sql, $this->link)) { return $this->query; } else { $this->exception("Could not query database!"); return false; } } public function num_rows($qid) { if (empty($qid)) { $this->exception("Could not get number of rows because no query id was supplied!"); return false; } else { return mysql_num_rows($qid); } } public function fetch_array($qid) { if (empty($qid)) { $this->exception("Could not fetch array because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid); } return $data; } public function fetch_array_assoc($qid) { if (empty($qid)) { $this->exception("Could not fetch array assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid, MYSQL_ASSOC); } return $data; } public function fetch_object($qid) { if (empty($qid)) { $this->exception("Could not fetch object assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_object($qid); } return $data; } public function fetch_all_array($sql, $assoc = true) { $data = array(); if ($qid = $this->query($sql)) { if ($assoc) { while ($row = $this->fetch_array_assoc($qid)) { $data[] = $row; } } else { while ($row = $this->fetch_array($qid)) { $data[] = $row; } } } else { return false; } return $data; } public function last_id() { if ($id = mysql_insert_id()) { return $id; } else { return false; } } private function exception($message) { if ($this->link) { $this->error = mysql_error($this->link); $this->errno = mysql_errno($this->link); } else { $this->error = mysql_error(); $this->errno = mysql_errno(); } if (PHP_SAPI !== 'cli') { ?> <div class="alert-bad"> <div> Database Error </div> <div> Message: <?php echo $message; ?> </div> <?php if (strlen($this->error) > 0): ?> <div> <?php echo $this->error; ?> </div> <?php endif; ?> <div> Script: <?php echo @$_SERVER['REQUEST_URI']; ?> </div> <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?> <div> <?php echo @$_SERVER['HTTP_REFERER']; ?> </div> <?php endif; ?> </div> <?php } else { echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n"; }; } } ?> Hi, I have a script that dumps the information from one of my MySQL tables into a CSV. The script works great, but in the result, the names of the MySQL columns are shown as-is. In other words, I have a column named "field4" that shows up as "field4" in the CSV. How can I modify the columns to more descriptive names without modifying the database itself? Here's my code: Code: [Select] <?php $host = "*********"; $user = "*********"; $pass = "*********"; $db = "database_name"; $table = "table"; $file = "member_information"; $link = mysql_connect($host, $user, $pass) or die("Cannot connect." . mysql_error()); mysql_select_db($db) or die("Cannot connect."); $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].","; $i++;} } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } $filename = $file."_".date("m.d.y"); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("m.d.y") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?> The CSV it spits out looks like this: Code: [Select] field1 field2 field3 field 4 info info info info I want it to look like this: Code: [Select] Name Email Location Age info info info info Thanks in advance! Hi, my PHP code currently outputs the results from a users search by querying a backend postgresql database. As result/row is retuned to the user i would like to be able to detect whether or not they have checked a checkbox at the end of each rown in which case multiple rows can then be deleted from the database upon the user clicking a 'delete multiple records' button. I have no problem in being able to display the checkboxes on the webpage but i am a little unsure as to how to refernce them and detect which ones the user has checked. Given my database stores hostnames/IP addresses would it be best to name each checkbox to reflect the hostname or name the value it returns when checked to reflect the hostname. Given the above and that I also store the results of a users search in a $_SESSION['hosts'][][] array how can I then tie the two together? Thanks for reading. Hey guys. Me again... Essentially what i am doing is pulling data from a MySQL database about the number of thumbnails on a page. The user can then change this using a <select> dropdown menu. How ever, i want the <select> to default to the amount already specified by the Database. I know i can do this by inserting a Selected attribute to one of the <options> but what is the best way of doing this? Heres my code.. $NumberOfThumbnails = mysql_result($data, 0,"NumberOfThumbnails"); <select name="numberofthumbnails"> <option value="0">None</option> <option value="2">2</option> <option value="4">4</option> <option value="6">6</option> <option value="8">8</option> <option value="10">10</option> <option value="12">12</option> <option value="14">14</option> <option value="16">16</option> <option value="18">18</option> <option value="20">20</option> <option value="22">22</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> </select> Thanks - Danny how would i get checkboxes to work. I have tried: $JobCategories = ($_GET['JobCategories[]']) ? $_GET['JobCategories[]'] : $_POST['JobCategories[]']; html looks like: <li><input name="JobCategories[]" type="checkbox" value="Admin" /> Admin</li> <li><input name="JoCategories[]" type="checkbox" value="Campaigning" /> Campaigning</li> |