PHP - Problem Updating Database Records
Hello all.
Please I need help to update customer table. I get the texboxes populated with select query no problem. I have html page with a search box and when the user enter their first name or last name and click search it will call up the search.php file here is the file: This code below populate the textboxes to be updated: Code: [Select] <?php if(isset($_POST['submit'])){ if(isset($_GET['go'])){ if(preg_match("^/[A-Za-z]+/", $_POST['name'])){ $name=$_POST['name']; } } else{ echo "<p>Please enter a search query</p>"; } } //connect to the database $con = mysql_connect("localhost","dbusrn","dbpwd"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mydb", $con); $name = $_POST['name']; $result = mysql_query ("select * from Customer_Registration where Firstname like '%$name%' or lastname like '%$name%' "); $row = mysql_fetch_row($result); $cf_uid = $row[0]; $Firstname = $row[6]; $lastname = $row[7]; $Address = $row[8]; $Postcode = $row[9]; $Phone = $row[10]; $Email = $row[11]; $Customer_Type = $row[12]; $Computer_type = $row[13]; $Computer_maker = $row[14]; $Model = $row[15]; $OS = $row[16]; $Appointment_date = $row[17]; $Problem = $row[18]; $Solution = $row[19]; $Comment = $row[20]; ?> <form action="updatecus1.php" method="post"> <table width="100%" border="2" cellspacing="0" cellpadding="8"> <tr><td width="45%" class="FormText">Customer ID:</td> <td width="55%"><?php echo $cf_uid;?></td></tr> <tr><td width="45%" class="FormText">First name:</td> <td width="55%"><input name="Firstname" type="text" value="<?php echo $Firstname;?>"?> </td></tr> <tr><td width="45%" class="FormText">Last name:</td> <td width="55%"><input name="lastname" type="text" value="<?php echo $lastname;?>"?> </td></tr> <tr><td width="45%" class="FormText">Address:</td> <td width="55%"><input name="Address" type="text" value="<?php echo $Address; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Postcode:</td> <td width="55%"><input name="Postcode" type="text" value="<?php echo $Postcode; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Phone:</td> <td width="55%"><input name="Phone" type="text" value="<?php echo $Phone; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Email:</td> <td width="55%"><input name="Email" type="text" value="<?php echo $Email; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Customer:</td> <td width="55%"><input name="Customer_type" type="text" value="<?php echo $Customer_Type; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Computer :</td> <td width="55%"><input name="Computer_type" type="text" value="<?php echo $Computer_type; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Manufactural:</td> <td width="55%"><input name="Computer_maker" type="text" value="<?php echo $Computer_maker; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Model:</td> <td width="55%"><input name="Model" type="text" value="<?php echo $Model; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Operating System:</td> <td width="55%"><input name="First name" type="text" value="<?php echo $OS; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Appointment:</td> <td width="55%"><input name="Operating System" type="text" value="<?php echo $Appointment_date; ?>"?> </td></tr> <tr><td width="45%" class="FormText">Problem:</td> <td width="55%"><textarea name="Problem" rows="10" cols="20" ><?php echo $Problem; ?></textarea></td></tr> <tr><td width="45%" class="FormText">Solution:</td> <td width="55%"><textarea name="Solution" rows="10" cols="20" ><?php echo $Solution; ?></textarea></td></tr> <tr><td width="45%" class="FormText">Comment:</td> <td width="55%"><textarea name="Comment" rows="10" cols="20" ><?php echo $Comment; ?></textarea></td></tr> <td width="55%"><input name="submit" value="submit" type="submit" <br> <input type="Submit" value="Cancel"</br></td> </form> <?php -------------------------------------------------------------------------------------- The update.php file have the following code: Code: [Select] <?php //connect to the database $con = mysql_connect("localhost","dbusrn","dbpwd"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mydb", $con); if (isset($_POST['submit'])) { $cf_uid = $_POST['cf_uid']; $Firstname = $_POST['Firstname']; $lastname = $_POST['lastname']; $Address = $_POST['Address']; $Postcode = $_POST['Postcode']; $Phone = $_POST['Phone']; $Email = $_POST['Email']; $Customer_Type = $_POST['Customer_Type']; $Computer_type = $_POST['Computer_type']; $Computer_maker = $_POST['Computer_maker']; $Model = $_POST['Model']; $OS = $_POST['OS']; $Appointment_date = $_POST['Appointment_date']; $Problem = $_POST['Problem']; $Solution = $_POST['Solution']; $Comment = $_POST['Comment']; $query = "UPDATE Customer SET Firstname='$Firstname',lastname='$lastname',Address='$Address',Postcode='$Postcode',Phone='$Phone',Email='$Email',Customer_Type='$Customer_Type',Computer_type='$Computer_type',Computer_maker='$Computer_maker',Model='$Model',OS='$OS', Appointment_date='$Appointment_date',Problem='$Problem',Solution='$Solution',Comment='$Comment' WHERE cf_uid='$cf_uid '"; mysql_query($query) or die(mysql_error()); mysql_close($con); echo "<p>Congrats Record Updated</p>"; } ?> I got congrats record updated but in actual fact no record are updated. Please help MOD EDIT: code tags added. Similar TutorialsThis is the form that I'm using and it populates just fine but when you make the changes I can't figure out how to get it to update each record in my database. Code: [Select] <table width="100%" cellspacing="1" cellpadding="2" border="0"> <form action="<?php echo $_SERVER["PHP_SELF"] . "?update=1"; ?>" method="post"> <tr> <td><b>Category Name</b></td> <td><b>Category Description</b></td> <td><b>Order</b></td> <td align="right"><input type="submit" value="Update"></td> </tr> <?php read_cat_list($cat); for ($i = 0; $i < $cat["count"]; $i++) { echo "<tr>\n"; echo "<td width=\"30%\" valign=\"top\"><input type=\"text\" name=\"cat_name_" . safe_string($cat[$i]["cat_id"]) . "\" size=\"30\" maxlength=\"250\" value=\"" . safe_string($cat[$i]["cat_name"]) . "\"></td>\n"; echo "<td width=\"36%\" valign=\"top\"><textarea name=\"cat_desc_" . safe_string($cat[$i]["cat_id"]) . "\" rows=\"2\" cols=\"30\">" . safe_string($cat[$i]["cat_desc"]) . "</textarea></td>\n"; echo "<td width=\"10%\" valign=\"top\"><input type=\"text\" name=\"cat_order_" . safe_string($cat[$i]["cat_id"]) . "\" size=\"3\" maxlength=\"3\" value=\"" . safe_string($cat[$i]["cat_order"]) . "\"></td>\n"; echo "<td width=\"24%\" valign=\"top\">[ <a href=\"#\" onmouseover=\"window.status = 'Delete " . safe_string($cat[$i]["cat_name"]) . "'; return true;\" onmouseout=\"window.status = ''; return true;\" onclick=\"javascript:del_cat(" . $cat[$i]["cat_id"] . ", '" . safe_string($cat[$i]["cat_name"]) . "'); return false;\">Delete</a> ]</td>\n"; echo "</tr>\n"; } ?> <tr> <td colspan="4" align="right"><input type="submit" value="Update"></td> </tr> </form> </table> the safe_string function just cleans up the output/input from the database, This next block is my form processor for this form. Code: [Select] <?php function update_cats($vars) { $err = ""; #if ($SESSION["level"] != ADMIN) { # $err = ERR_NOT_ENOUGH_ACCESS; #} else { $temp = array_keys($vars); for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 9) == "cat_name_") { if ($vars[$temp[$i]] == "") { $err = "Category names cannot be blank."; break; } else { $name_query["cat_name"] .= substr($temp[$i], 9) . ", "; } } } for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 9) == "cat_desc_") { $desc_query["cat_desc"] .= substr($temp[$i], 9) . ", "; } } for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 10) == "cat_order_") { if ($vars[$temp[$i]] == "") { $err = "Category orders cannot be blank."; break; } else { $order_query["cat_order"] .= substr($temp[$i], 10) . ", "; } } } #} if (!$err) { if ($name_query["cat_name"]) { $update_name_query = "update category"; $update_name_query .= " set cat_name = '" . $name_query["cat_name"] . "'"; $update_name_query .= " where cat_id in (" . substr($name_query["cat_name"], 0, -2) . ")"; update_db($update_name_query); } if ($desc_query["cat_desc"]) { $update_desc_query = "update category"; $update_desc_query .= " set cat_desc = '" . $name_query["cat_desc"] . "'"; $update_desc_query .= " where cat_id in (" . substr($desc_query["cat_desc"], 0, -2) . ")"; update_db($update_desc_query); } if ($order_query["cat_order"]) { $update_order_query = "update category"; $update_order_query .= " set cat_order = '" . $name_query["cat_order"] . "'"; $update_order_query .= " where cat_id in (" . substr($order_query["cat_order"], 0, -2) . ")"; update_db($update_order_query); } } return $err; } ?> update_db is my database caller, if you need any of the functions that I use that are not here please post back and tell me. now when I process the form all my fields change to this: cat_name: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, cat_desc: cat_id: 0 for all the records in the database table, I'm just trying to update each record with the values it needs Here is my database table with the data. Code: [Select] CREATE TABLE `category` ( `cat_id` int(11) NOT NULL AUTO_INCREMENT, `cat_name` varchar(255) NOT NULL, `cat_desc` text NOT NULL, `cat_order` int(11) NOT NULL, PRIMARY KEY (`cat_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; -- -- Dumping data for table `category` -- INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(1, 'Hand Tossed Pizza', '', 1); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(2, 'Hand Tossed Specialty Pizzas', '', 2); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(3, 'Chicago Style Deep Dish', '', 3); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(4, 'Specialty Chicago Style Deep Dish', '', 4); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(5, 'Chicken Wings & Tenderloins', '', 5); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(6, 'Hot Sides', '', 6); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(7, 'Hot Sandwiches', '', 7); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(8, 'Cold Sandwiches', '', 8); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(9, 'Pastas', '', 9); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(10, 'Fresh Salads', '', 10); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(11, 'Fresh Breads', '', 11); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(12, 'Soups', '', 12); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(13, 'Kids Menu', '', 13); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(14, 'Drinks', '', 14); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(15, 'Desserts', '', 15); Hope I have provided plenty of info on what I got and what I need for it todo Thanks Hey, Im needing some help with an update form that I have created using PHP/MySQL. Basically the form is working great (updating records, retrieving records and showing errors) but there is a problem with the errors. If there are no errors and I edit the existing text input values, the database updates fine. However if I edit the existing text input values and there is an error, the edited input values dont save, they revert back to the values of the database. I understand why this is happening, its because the text inputs are set to show the values of the database so if i edit the existing values and an error occurs or the page is refreshed, the values revert back to the database values. However id like it so that if any text in the text field have been edited and an error occurs, the text stays to how it is until the user by passes any errors and then the database is updated. Hopefully this makes sense. I have attached the php page just incase anybody wants to look into it but any help would be much appreciated! Also, im not looking for someone to just to fix this for me but if someone knows my problem and can guide me in the right direction, that would be great. Google Chrome Developer Tool causes an error when I run the following and there are not any records. I keep getting errors when I try to change it.
<?php $host = 'localhost'; $user = 'root'; $pass = ''; $database = 'ecommerce'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); $keyword = $_GET['keyword']; $dbo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options); $q1 = "SELECT * FROM products INNER JOIN keywords on keywords.keywordID = products.KeywordID and keywords.KeyWord1 = \"$keyword\" "; $counter = 10; $counter1 = 0; foreach ($dbo->query($q1) as $row) {
Hello, i am having an issue when i try to go through multiple pages from a database. The database contains apartment information. I currently have it set to limit my results to 30 per page and this is working correctly, however when i try to scroll to page two like 1..2..3 i am displayed with every apartment listed in the database, and not the certain category that i would like selected. //assigning variables $SESuser_lng = $_COOKIE['SESuser_lng']; $SESuser_admlevel = $_COOKIE['SESuser_admlevel']; $id = $_GET['id']; $pgrow = $_GET['pgrow']; $msg = $_GET['msg']; $ht_filter = $_GET['ht_filter']; //sql query to retrieve result set $htfilter selects the distinct apartment categories $sqlFilter = ($ht_filter > 0 ? " WHERE p.idhotel = $ht_filter" : ""); $sql = "SELECT p.id, p.idhotel, p.nombre, p.thmb, p.archivo, h.nombre FROM prensa p LEFT JOIN hoteles h ON p.idhotel = h.id $sqlFilter ORDER BY p.nombre, h.nombre"; //DB_pager $nav = new DB_Pager('30'); $result = $nav->execute($sql, $dbcnx); //Javascript link creation <span id="display-links"><?php echo $nav->display_links(); ?></span> any help will be greatly appreciated hi, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Sahansevena_ver1\admin\profile\updAdmiInfo.php on line 49 i got this error. here is the coding Code: [Select] <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ $dbuser="root"; $dbpswd="****"; $dbserver="localhost"; $nwuser=$_POST['username']; $c_pw=$_POST['cur_password']; $n_pw=$_POST['conf_password']; //$user=$userName; //$pass=$password; // $dbname="sahansevena"; if($_SERVER['REQUEST_METHOD']=='POST'){ //get username and password from admin login.php $con=mysql_connect($dbserver,$dbuser,$dbpswd); if(!$con){ die('coudnt connect db connection prob'.mysql_error()); }else{ if($c_pw==$n_pw){ $uname=mysql_real_escape_string($username); $pword=mysql_real_escape_string($n_pw); // setDatabase($dbname, $con) ; mysql_select_db($dbname, $con); // $result="update admin set username='$uname',password='$pword'" where limit 0; $result="update admin set username='$uname' , password='$pword', last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname' limit 0"; //Checked to see if any rows were returned from the database // If rows were returned, set a session variable to 1 $result=mysql_query($result); if ($result) { $numRow=mysql_numrows($result); if($numRow>0){ //session_start(); //SESSION['admin']="menuka"; echo "data was suaccesfully updated"; /// header ("Location:config/menu.php"); //mysql_close($con); }else{ //session_start(); echo " problem in updating "; //$_SESSION['login'] = ""; //header ("Location:login.php"); } } else { trigger_error(mysql_error(), E_USER_ERROR); } } } }else{ echo 'error message not post methode'; include(login.php); } ?> please check my code and help me to figur out the error thanks in advance, menukadevinda again my tables are movies| ID(PK) - Titles - Category(FK) - URL 0 Name 1 www.xyz.com categories| ID(PK) - Category 1 Comedy say i create a query SELECT * FROM movies WHERE Category="1" and it gave me all the movies from my table that is in the comedy category which should look like this: ID - Title - Category - URL 0 Name Comedy www.xyz 1 xyz Comedy www.abc etc.. How can i add a drop down menu beside each movie listed in that result that would let me change the category for it and save it ? like this, ID - Title - Category - URL 0 Name Comedy www.xyz [Dropdown] 1 xyz Comedy www.abc [Dropdown] [Save Button] being a newbie im going to guess that i will need a INSERT in here somewhere and not really sure how i would write my result echos. i have been trying all kinds of "update records" forms and cant get them right so i figured it may be easier to just try and create my own. if i could get some example or if you have more simple suggestions I have got myself a bit confused whilst trying to create an 'update selected records' page. In memberlist.php, a set of records is shown, each with a checkbox. When the user clicks on 'Update Selected' it opens up membermultiupdate.php. I cannot get this page to recognise which id's have been passed and put them in an array so only the checked records are shown. The page in question is at http://www.margate-fc.com/memberlist.php. When it opens membermultiupdate.php, there are currently 2 errors.... Code: [Select] Warning: implode() [function.implode]: Invalid arguments passed in /homepages/46/d98455693/htdocs/membermultiupdate.php on line 11 which refers to $update = implode ("','", mysql_real_escape_string ($_POST['checkbox'])) Code: [Select] Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/46/d98455693/htdocs/membermultiupdate.php on line 44which is while ($rowmembers = mysql_fetch_array($members)) I have also tried mysql_fetch_assoc there too. I may be miles out or I may be missing something simple but I have tried for hours now to get my head around this and have not even got to the point where I can see if the actual update side works! Any suggestions would be greatly received and I have put the relevant code from both pages below. Thanks in advance for any help or suggestions Steve memberlist.php The query to get all rows $members = mysql_query(" SELECT * FROM users"); The submit form with checkboxes <form name="form1" method="post" action="membermultiupdate.php"> <?php while ($rowmembers = mysql_fetch_assoc($members)) {echo ' <tr> <td><input type="hidden" name="id[]" value="'.$rowmembers['id'].'" />'.$rowmembers['id'].'</td> <td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="'.$rowmembers['id'].'"></td></td> <td>'.$rowmembers['id'].'</td> <td>'.$rowmembers['username'].'</td> <td>'.$rowmembers['first_name'].'</td> <td>'.$rowmembers['last_name'].'</td> <td>'.$rowmembers['email'].'</td> '; if ($rowmembers['active'] == 1) {echo '<td> YES </td>';} else {echo ' <td>NO </td>';} echo ' <td><a href="memberedit.php?member='.$rowmembers['id'].'"><img src="http://icons.iconarchive.com/icons/custom-icon-design/office/256/edit-icon.png" width="15" height="15" /></a> <img src="http://icons.iconarchive.com/icons/custom-icon-design/office/256/delete-icon.png" width="15" height="15" /></td> </tr>';} ?> <tr> <td colspan="4" align="center"><input type="submit" name="submit" value="Update Selected"></td> </tr> </form> membmultiupdate.php The code bit to try to show all checked rows if (isset ($_POST['submit'])) { if (is_array ($_POST['checkbox'])) { $update = implode ("','", mysql_real_escape_string ($_POST['id'])); $members = mysql_query("SELECT * FROM users WHERE id IN (".$update.") "); } } The form to show all of the checked rows <form name="form1" method="post" action=""> <?php while ($rowmembers = mysql_fetch_array($members)) {echo ' <tr> <td width="200px" align="right" style="font-weight:bold"> <label for="name">Username:</label> </td> <td width="200px" > <input type="text" name="name" value="'.$rowmembers['username'].'" /><br> </td> </tr> <tr> <td width="200px" align="right" style="font-weight:bold"> <label for="name">First Name:</label> </td> <td width="200px" > <input type="text" name="first_name" value="'.$rowmembers['first_name'].'" /><br> </td> </tr> <tr> <td width="200px" align="right" style="font-weight:bold"> <label for="name">Last Name:</label> </td> <td width="200px" > <input type="text" name="last_name" value="'.$rowmembers['last_name'].'" /><br> </td> </tr> <tr> <td width="200px" align="right" style="font-weight:bold"> <label for="name">Email:</label> </td> <td width="200px" > <input type="text" name="email" value="'.$rowmembers['email'].'" /><br> </td> </tr>' ;} ?> <tr> <td colspan="4" align="center"><input type="submit" name="update" value="update"></td> </tr> </form> The code to update the rows from the above form and the return to memberlist.php if($update) { foreach($_POST['id'] as $id) { $sql1=" UPDATE users SET username='".$_POST["name".$id]."' , first_name='".$_POST["first_name".$id]."' , last_name='".$_POST["last_name".$id]."' , email='".$_POST["email".$id]."' , ONOFF='".$_POST["ONOFF".$id]."' WHERE id='".$id."'"; $result1=mysql_query($sql1); } } if($result1){ header("location:memberlist.php"); } Hi,
I am trying to create an admin page for a local Gym Club to allow an Administrator to be able to update club prices which then show on different screens on the site.
I have been able to display the "Prices Admin" page which basically reads a MySQL database table (pricelist), display the description, member price and non-member price and allows the user to update any of these fields.
My problem is that when I try writing the data back to the database with the "UPDATE" statement it fails, what I mean is that nothing updates. I have at the moment commented out the actual update statement and put in a "file_put_contents" command" to try and work out what is in the various fields before the UPDATE is run. I find that the display/INPUT works perfectly well but when I do a foreach on the $record array variable I am getting strange results.
I may not have explained this very well but here are the relevant sections of my code;
// Display and Input section
<div id="admin-area"> I have a problem with an amend to an admin system I am trying to change. The shop stocks different colours of each product and the client wants to be able to update the stock levels of all colours of one product (which all share the same title) on one form. I have tried following some instructions on some sites and tried making my own and I can get it to display the form and the values correctly, but on submission it does nothing but direct me to a page without a title value in the address (e.g. www.example.com/example/stock_level_2.php?title=). I think it may be to do with the arrays I am using, has anyone got any ideas? Here is the code. Form: Code: [Select] <?php $pd_title = str_replace("_"," ",$_REQUEST["title"]); $pd_title = str_replace("%","&#37;",$pd_title); $pd_title = str_replace("/","&#47;",$pd_title); $lookupqueryc = mysql_query("SELECT * FROM product WHERE pd_title = '".$pd_title."' ORDER BY pd_id DESC"); echo '<table><tr><th align="center" class="bodytext">Product<br />ID</th><th align="center" class="bodytext">Product Name</th><th align="center" class="bodytext">Stock Level</th></tr>'; $form = '<form name="frmAmendStock" method="post" action="stock_level_2.php?title="'; $form .= $_GET["title"]; $form .= '" enctype="multipart/form-data">'; echo $form; echo '<input name="submitted" type="hidden" value="true">'; $count=mysql_num_rows($lookupqueryc); echo '<input name="count" type="hidden" value="'; echo $count; echo '">'; while($lookupresultc = mysql_fetch_array($lookupqueryc)){ echo '<tr><td align="center" class="bodytext">'; $id[]=$lookupresultc["pd_id"]; echo $lookupresultc["pd_id"]; echo '</td><td class="bodytext">'; echo $lookupresultc["pd_title"]; if (isset($lookupresultc["pd_colour"]) && $lookupresultc["pd_colour"] !="") { echo " ("; echo $lookupresultc["pd_colour"]; echo ')'; } if ($lookupresultc["pd_stock"] <= 5) { echo '</td><td align="center" class="bodytext" style="border: 2px solid red;">'; echo '<input name="stock[]" type="text" id="stock" value="'; echo $lookupresultc["pd_stock"]; echo '"style="width: 50px;" />'; echo "</td></tr>"; }else{ echo '</td><td align="center" class="bodytext">'; echo '<input name="stock[]" type="text" id="stock" value="'; echo $lookupresultc["pd_stock"]; echo '"style="width: 50px;" />'; echo "</td></tr>"; } } ?> <tr> <td> </td> <td height="35"><a href="javascript: " onClick="javascript:document.forms.frmAmendStock.submit()" class="bodytext"><strong>click here to amend your stock </strong></a></td> </tr> </form> </table> And here is the code it should run on submission: Code: [Select] <?php if (isset($_POST["submitted"])) { for($i=0;$i<$_POST["count"];$i++){ mysql_query("UPDATE product SET pd_stock='$stock[$i]' WHERE pd_id='$id[$i]'"); } } ?>
Hi Guys, <?php $host="xxx"; // Host name $username="xxx"; // Mysql username $password="xxx"; // Mysql password $db_name="xxx"; // Database name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM attendance"; $result=mysql_query($sql); // Count table rows $count=mysql_num_rows($result); ?> <html> <head> <title>Registers</title> </head> <body> <?php include 'Navigation.php';?> <table width="500" border="0" cellspacing="1" cellpadding="0"> <form name="form1" method="post" action=""> <table border="0" cellspacing="1" cellpadding="0" style="width: 1461px; height: 105px"> <tr> <td align="center"><strong>Id</strong></td> <td align="center"><strong>Last Name</strong></td> <td align="center"><strong>First Name</strong></td> <td align="center"><strong>Form</strong></td> <td align="center"><strong>Year Group </strong></td> <td align="center"><strong>Date</strong></td> <td align="center"><strong>Attendance</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center"><? $Student_id[]=$rows['Student_id']; ?><? echo $rows['Student_id']; ?></td> <td align="center"><? $firstname[]=$rows['firstname']; ?><? echo $rows['firstname']; ?></td> <td align="center"><? $lastname[]=$rows['lastname']; ?><? echo $rows['lastname']; ?></td> <td align="center"><? $Form_Group[]=$rows['Form_Group']; ?><? echo $rows['Form_Group']; ?></td> <td align="center"><? $Year_Group[]=$rows['Year_Group']; ?><? echo $rows['Year_Group']; ?></td> <td align="center"><? $Att_Date[]=$rows['Att_Date']; ?><? echo $rows['Att_Date']; ?></td> <td align="center"><input name="Presence[]" type="text" id="Presence" value="<? echo $rows['Presence']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="7" align="center"><input type="submit" name="Submit" value="Submit Register"></td> </tr> </table> </form> </table> <?php // Check if button name "Submit" is active, do this if($Submit){ for($i=0;$i<$count;$i++){ $sql1="UPDATE attendance SET Presence='$Presence[$i]' WHERE Student_id='$Student_id[$i]'"; $result1=mysql_query($sql1); } } if($result1){ header("location:Registers.php"); } mysql_close(); ?>
I know how to pull data from sql table and limit down the results, what i wanted to do is pull data from a sql table 'finished' and list data that has paid='0' this is then limited to show the amount of rows set by variable 'maxPay' here is my list what im pulling atm; <h2>Payment </h2> <?php if($userType[user_type]==28){ $queryPay = mysql_query("SELECT * FROM finished WHERE paid='0'&&method!='FALSE'&&method!='credit';") or die(mysql_error()); $queryAdmin = mysql_query("SELECT maxPay FROM `admin`;") or die(mysql_error()); $row = mysql_num_rows($queryPay); //echo $row."row<br />"; $rowsArray = mysql_fetch_assoc($queryAdmin); $rows = $rowsArray[maxPay]; //echo $rows."rows<br />"; if($rows>$row){ $r=$row; } else{ $r=$rows; } $s=0; while($s<$r){ if($_POST[complete]==TRUE){ mysql_query("UPDATE `finished` SET `paid`='$_POST[paid]' WHERE `auctionID`='$_POST[aid]';"); $_POST[complete] = FALSE; } $s++; } $t=0; while($t<$r){ $queryuser = mysql_query("SELECT * FROM finished WHERE paid='0'&&method!='FALSE'&&method!='credit';") or die(mysql_error()); $user = mysql_result($queryuser, $t, "username"); //echo $user; $item = mysql_result($queryuser, $t, "itemName"); //echo $item; $value = mysql_result($queryuser, $t, "marketPrice"); //echo $value; $method = mysql_result($queryuser, $t, "method"); //echo $method; $id = mysql_result($queryuser, $t, "auctionID"); //echo $id; //echo $method; if($method=='isk'){ ?> <FORM method="post" action="pay.php"> <input type="hidden" name=complete value="TRUE" /> <input type="hidden" name=paid value="YES" /> <input type="hidden" name=username value="<? echo $user; ?>" /> <input type="hidden" name=aid value="<? echo $id; ?>" /> <input type="submit" value="Paid" /><? echo $user." won a ".$item." he selected to receive ".$value."ISK."; echo "<br />"; ?></FORM><? } elseif($method=='ship'){ ?> <FORM method="post" action="pay.php"> <input type="hidden" name=complete value="TRUE" /> <input type="hidden" name=paid value="YES" /> <input type="hidden" name=username value="<? echo $user; ?>" /> <input type="hidden" name=aid value="<? echo $id; ?>" /> <input type="submit" value="Paid" /><? echo $user." won a ".$item." he selected to receive the ship."; echo "<br />"; ?></FORM><? } else{ } $t++; } } else{ echo "You are not an Admin."; } ?> and pay.php: <?php header('Location: /admin.php'); include "connect.php"; echo $_POST[aid]; if($_POST[complete]==TRUE){ $tempID = (($_POST[aid])+1); mysql_query("UPDATE `finished` SET `paid`='$_POST[paid]' WHERE `auctionID`='$tempID';") or die(mysql_error()); $_POST[complete] = FALSE; } ?> at the moment i am listing all my data, and processing it using pay.php, each dataset has a "paid" button, i want to change this to using a checkbox at end of each data row, and a submit button at the bottom. this way i can select which rows to update and tick the checkbox, then click submit and those rows will then be updated the value '0' in db to a value of 'YES'. hope i explained myself clearly enough for some help. im a relative php noob still in training. hello guys moving on from inserting multiple records im now stuck with updating multiple records. i can get most of the details nailed but i need it to match the id's for the table the code i have in the sql part are Code: [Select] if (isset($_POST['submit'])) { //Assign each array to a variable $StaffMember = $_POST['StaffMember']; $referrer = $_POST['referrer']; $referred = $_POST['referred']; $SentOut = $_POST['SentOut']; $today = date("y.m.d H:i:s"); $user_id = $_SESSION['user_id']; $IssueNum = $_POST['Referrerid']; $limit = count($StaffMember); $values = array(); // initialize an empty array to hold the values for($k=0;$k<$limit;$k++){ $msg[] = "$limit New KPI's Added"; $values[$k] = "( '{$StaffMember[$k]}', '{$referrer[$k]}', '{$referred[$k]}', '{$SentOut[$k]}', '{$today}', '{$user_id}' )"; // build the array of values for the query string } $query = "UPDATE `Referrer` (StaffMember, referer, referred, SentOut, SentOutDate, SentOutBy) VALUES " . implode( ', ', $values ) . " WHERE IssueNum= '{$IssueNum[$k]}'"; echo $query; } i obviously want the records updating where the issuenumber is the same and if the check box in the form is ticked help with this one? I making an web app for teachers to assess their students online. The problems I am currently having are on select only one record is displayed and after update no records are displayed in the form even though it was successfully updated.. The program has two files, index.php and process.php. The problems started when got the class name into the query to search and display the class. $result = $mysqli->query("SELECT * FROM data WHERE classroom = '".$classroom."' ORDER BY '.name';") or die($mysqli->error); The query works but doesn't order by name I would like. I would be grateful if anyone could cast an eye over it and give me some tips. Thanks guys. The beers are on me if anyone can sort it, but you'll have to come to Phnom Penh, Cambodia as that is where I live. Anyway here's the code. process.php <html> <?php session_start(); $mysqli = new mysqli("localhost","ray","password","reports") or die(mysqli_error($mysqli)); $id = 0; $update = false; $name = ''; $classroom = ''; if (isset($_GET['edit'])){ $id = $_GET['edit']; $update = true; $result = $mysqli->query("SELECT * FROM data WHERE id=$id") or die($mysqli->error()); if(isset($result->num_rows) && $result->num_rows > 0) { $row = $result->fetch_array(); $name = $row['name']; $classroom = $row['classroom']; $pacomment = $row['pacomment']; } } if (isset($_POST['update'])){ $id = $_POST['id']; $pacomment = $_POST['pacomment']; $mysqli->query("UPDATE data SET pacomment= '$pacomment' WHERE id=$id") or die($mysqli->error); $_SESSION['message'] = "Record has been updated!"; $_SESSION['msg_type'] = "warning"; header('location: index.php'); } index,php <?php require_once 'process.php'; ?> <!--************************************** Setup Messages **************************************** --> <?php if (isset($_SESSION['message'])): ?> <div class="alert alert-<?=$_SESSION['msg_type']?>"> <?php echo $_SESSION['message']; unset($_SESSION['message']); ?> </div> <?php endif ?> <!--**************************************End Setup Messages *********************************************** --> <?php ?> <!DOCTYPE html> <html> <head> <title>Home of English Reports</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <style>= body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: #008080; } .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #4CAF50; color: white; } </style> </head> <body style="background-color:linen;"> <!--************************************** End Setup Page Styles ************************************* --> <div class="container"> <form action="index.php" method = get> <label for="classroom">Class name:</label><br> <input type="text" id="classroom" name="classroom" value="107i am"><br> <input type="submit" value="Submit"> </form> </div> <?php $resultcomment = $mysqli->query("SELECT EnglishComment FROM comments"); ?> <!-- ************************************** Begin Connect DB ************************************************ --> <div class="container" align-content-center> <?php $classroom = (isset($_GET['classroom']) ? $_GET['classroom'] : null); $result = $mysqli->query("SELECT * FROM data WHERE classroom = '".$classroom."' ORDER BY '.name';") or die($mysqli->error); ?> <!-- ************************************** End Connect DB **************************************************** --> <div class="row justify-content-center"> <form action="process.php" method="POST"> <input type="hidden" name="id" value="<?php echo $id; ?>"> <div class="form-group"> <h1><label><?php echo $name?></label></h1> </div> <form action="process.php" method="POST"> <input type="hidden" name="id" value="<?php echo $id; ?>"> <div class="form-group"> <h3><label>PA Teacher's Comment</label></h3> <select name = "pacomment"> <?php while($rows = $resultcomment-> fetch_assoc()) { $EnglishComment = $rows['EnglishComment']; echo "<option value='$EnglishComment'>$name.$EnglishComment</option>"; } ?></h2> </select><br> <p> <div class="form-group"> <?php if ($update == true): ?> <button type="submit" class="btn btn-info" name="update">Update</button> <?php else: ?> <!-- <button type="submit" class="btn btn-primary" name="save">Save</button> --> <?php endif; ?> </div> </form> <!-- ************************************** Begin Setup Table Headers ****************************************** --> <div class="row justify-content-center"> <table class="table" width = "20%" border = "5" cellpadding = "1";> <thead> <tr> <th><center>Action</center></th> <th><center>ID</center></th> <th>Name and Comment</th> </tr> </thead> <!-- ************************************** End Setup Classlist Table Headers ****************************************** --> <!-- ****** Loop thru Every Record From $result Query Variable and get variables and echo each variable into the table rows ********** --> <?php while ($row = $result->fetch_assoc()): ?> <tr> <td> <center><a href="index.php?edit=<?php echo $row['id']; ?>" class="btn btn-info">Assess</a></center> </td> <!-- ************************************** Put data into Classlist table rows ****************************************** --> <td><center><?php echo $row['studentid']; ?></center></td> <td><?php echo $row['name']." ".$row['pacomment'] ?></td> </tr> <?php endwhile; ?> <!-- ****************** End While() Loop **************************** --> </table> <!-- *************** End of Classlist Table ****************************************** --> </div> </div> </div> </body> </html>
Edited July 25, 2020 by raymon Hi all Complete noob here..... What I have to do is create a new database every year, but I can't just import last years data completely, only records when needed. I can do it myself in PHPMyAdmin, but I don't want my employees touching mysql directly. What I am trying to do is write a php script that will serach for a reocrd in last years database and if it exists insert it into the new database if it doesn't exists bring up a form so it can be entered. Any help would be greatly appreciated. Thanx ZZ Code: [Select] <?php ob_start(); session_start(); $pagerank=2; if ($rank < $pagerank){ header('Location:main.php?id=lowrank.php'); } else{ $name1 = $_GET["name"]; $type2 = $_GET['type']; Echo "Your seach for ".$name1." gave the following results: "; $records_per_page = 15; $total = mysql_result(mysql_query("SELECT COUNT(*) FROM systems WHERE '$type2' LIKE '%$name1%'"), 0) or die(mysql_error()); $page_count = ceil($total / $records_per_page); Echo $total." Records Found"; echo "<table border=0>"; $page = 1; if (isset($_GET['page']) && $_GET['page'] >= 1 && $_GET['page'] <= $page_count) { $page = (int)$_GET['page']; } $skip = ($page - 1) * $records_per_page; $result = mysql_query("SELECT * FROM systems WHERE $type2 LIKE '%$name1%' ORDER BY Security DESC LIMIT $skip, $records_per_page") or die(mysql_error()); echo "<table border=1>"; echo "<td>System Name</td><td>Security</td><td>Class</td>"; while ($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td valign =top>".$row['System Name']."</td>"; echo "<td valign =top>".round($row['Security'],1)."</td>"; echo "<td valign =top>".$row['System Type']."</td>"; echo "</tr>"; } echo "</table>"; echo "<br>"; for ($i = 1; $i <= $page_count; ++$i) { echo '<a href="main.php?id=' . $_GET['id'] .'&name='.$name1.'&type='.$type1. '&page=' . $i . '">' . $i . '</a> '; } } ?> The above code takes data entered in a form and is suppose to show the matching results, but no records are showing, it works when I replace the $name1 and $type2 with the actual values, any ideas? I created this database Code: [Select] <?php $mysqli = mysqli_connect('localhost', 'admin', 'jce123', 'php_class'); if(mysqli_connect_errno()) { printf("connection failed: %s\n", mysqli_connect_error()); exit(); }else{ $q = mysqli_query($mysqli, "DROP TABLE IF EXISTS airline_survey"); if($q){echo "deleted the table airline_survey....<br>";} else{echo "damm... ".mysqli_error($mysqli);} $sql = "CREATE TABLE airline_survey ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, staff CHAR(10) NOT NULL, luggage CHAR(10) NOT NULL, seating CHAR(10) NOT NULL, clean CHAR(10) NOT NULL, noise CHAR(10) NOT NULL )"; $res = mysqli_query($mysqli, $sql); if($res === TRUE) { echo "table created"; } else { printf("Could not create table: %s\n", mysqli_error($mysqli)); } mysqli_close($mysqli); } ?> When I look at it it looks fine. I have a form that sends data to this script: Code: [Select] <?php $con = mysql_connect('localhost', 'admin', 'abc123'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("php_class", $con); foreach ($_POST as $key => $value) { $staff = ""; $luggage = ""; $seating = ""; $clean = ""; $noise = ""; switch($key){ case "staff": $staff = $value; break; case "luggage": $luggage = $value; break; case "seating": $seating = $value; break; case "clean": $clean = $value; break; case "noise": $noise = $value; break; default: echo "we must be in the twilight zone"; } echo $staff."<br>"; [color=red] mysql_query("INSERT INTO airline_survey (staff, luggage, seating, clean, noise) VALUES ($staff, $luggage, $seating, $clean, $noise)");[/color] } ?> as you can see right before the insert query I test one of the variables to see if it has the string I'm expecting and it does. The problem is the script runs without giving me an error message but the data never gets inserted into the table. hello every body...
two
I'm creating an IPN in paypal for my membership site but the problem I'm facing is that on successfull verification of the purchase, four rows are getting inserted in the database...
The code is
<?php require '../db.php'; $paypalmode = '.sandbox'; $req = 'cmd=' . urlencode('_notify-validate'); foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www'.$paypalmode.'.paypal.com')); $res = curl_exec($ch); curl_close($ch); if (strcmp ($res, "VERIFIED") == 0) { $transaction_id = $_POST['txn_id']; $payerid = $_POST['payer_id']; $firstname = $_POST['first_name']; $lastname = $_POST['last_name']; $payeremail = $_POST['payer_email']; $paymentdate = $_POST['payment_date']; $paymentstatus = $_POST['payment_status']; $mdate= date('Y-m-d h:i:s',strtotime($paymentdate)); $otherstuff = json_encode($_POST); $date = date("y-m-d"); $q = $pdo->connect()->query("INSERT INTO payment (mid,username,amount,paypal_id,txn_id,received_date) VALUES('{$_SESSION['user_id']}','{$_SESSION['uname']}','{$_POST['mc_gross']}','{$_POST['payer_email']}','{$_POST['txn_id']}','$date')"); $q->execute(); $q1 = $pdo->connect()->query("UPDATE members SET amount_loaded = amount_loaded + {$_SESSION['amount']} WHERE mid = '{$_SESSION['user_id']}'"); $q1->execute(); //header("Location: funds.php"); echo "verified"; } ?>two for the payment and in the members table, the amount is getting doubled. (i.e if anybody purchases For $2, it shows $4 in the database....) Any help will be really appreciated... I have a problem . I 've been trying for a long time to make an update for php mysql to change the data. but every time I do not manage to make it work with a form. but it works if I only if I put this ($ sql = "UPDATE users SET username = 'value' WHERE id = 10 " ; ) so it only works when I put the value of the id. but I want in an html form to indicate what I want to change and what id goes. but I have tried so long that I do not feel like I so want someone help me. make the same database and same as my records and make the code and test it if it works show me please my database name : web test my table called : users my records are called : id int ( 11) AUTO_INNCREMENT username , varchar ( 255 ) password , varchar ( 255 ) first_name , varchar ( 255 ) last_name , varchar ( 255 ) email, varchar ( 255 ) Age, int ( 11) Look, my update.php is like this now <?php $servername = "localhost"; $username = "root"; $password = "....."; $dbname = "webtest"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "UPDATE users SET password='cotton candy' WHERE id=10"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?> but now i have still have to go into the php file to change the valeu or the id but i looked on site and youtube how to put it in a simple html form but it still does not work. i want it in a html from. I want that when I enter the ID that the data of the user appears and that I can change any valeu separately. Hi. When a record is added its done via a form and processed via inserts.php. I need to use the same form but to recall the data (by id) so it can be editted. Cant work it out though. Help would be well appreciated! edit.php: <CENTER><B>Update a Vehicle</B></CENTER> <BR> <?php $query="SELECT * FROM cars"; $result=mysql_query($query); $i=0; while ($i < $num) { $carname=mysql_result($result,$i,"CarName"); $cartitle=mysql_result($result,$i,"CarTitle"); $carprice=mysql_result($result,$i,"CarPrice"); $carmiles=mysql_result($result,$i,"CarMiles"); $cardesc=mysql_result($result,$i,"CarDescription"); ?> <form action="showroomedit.php" method="post"> <CENTER>Vehicle Name:</CENTER> <CENTER><input type="text" name="CarName" value="<?php echo $carname; ?>"></CENTER> <br> <CENTER>Vehicle Type:</CENTER> <CENTER><input type="text" name="CarTitle" value="<?php echo $cartitle; ?>"></CENTER> <br> <CENTER>Vehicle Price:</CENTER> <CENTER><input type="text" name="CarPrice" value="<?php echo $carprice; ?>"></CENTER> <br> <CENTER>Vehicle Mileage:</CENTER> <CENTER><input type="text" name="CarMiles" value="<?php echo $carmiles; ?>"></CENTER> <br> <CENTER>Vehicle Description:</CENTER> <CENTER><textarea name="CarDescription" rows="10" cols="30" value="<?php echo $cardesc; ?>"></textarea></CENTER> <br> <CENTER><input type="Submit"></CENTER> </form> </TD> cant work out why it isnt working... |