PHP - Delete Separate Mysql Records With A Button
Hi, I'm new to the forum so this could go in the MySQL section but I'm not sure.
I am trying to make a page that will list all records from a column in HTML table and have a delete button to remove a specific record. I have got to the part where I have listed the records in a table. Note: Only records from a specific column ('links') are printed. Here is the code: Code: [Select] $con = mysql_connect("localhost","***","***"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("***", $con); $result = mysql_query("SELECT * FROM main"); echo "<table border='1'> <tr> <th>Current links</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['links'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); How would I go about adding a delete button next to each record to delete that specific record? Thanks for any help. Similar TutorialsHello,
First of all I'd like to say thank you for all the great information on the forums, I've been reading a lot on here lately.
I've started to make a website where users can log in and submit items to a database, which is then displayed on another page.
If Tom and Bill both post 10 items, all 20 items will be displayed on the "listings" page, however on the main log in screen Tom will only see his own 10 items and Bill will see his own 10 items.
This is all working perfectly, however, I now need to add a delete button so that they can delete specific items.
I have loosely followed this tutorial here to get the table to display as I want it (amongst a few other things, such as the user logins) http://www.wickham43...mphptomysql.php
I've added the delete button in the PHP loop for each row, I just can't figure out how to delete the specific row when clicked.
Any help would be really appreciated
Edited by eklem, 22 October 2014 - 08:10 AM. Hi all. Here is my scripts which allow user to check multiple rows of data and delete it , but it require select data and click for twice to delete the rows , what should be the error? Code: [Select] <form name="frmSearch" method="post" action="insert-add.php"> <table width="600" border="1"> <tr> <th width="50"> <div align="center">#</div></th> <th width="91"> <div align="center">ID </div></th> <th width="198"> <div align="center">First Name </div></th> <th width="198"> <div align="center">Last Name </div></th> <th width="250"> <div align="center">Mobile Company </div></th> <th width="100"> <div align="center">Cell </div></th> <th width="100"> <div align="center">Workphone </div></th> <th width="100"> <div align="center">Group </div></th> </tr> </form> <? echo "<form name='form1' method='post' action=''>"; while($objResult = mysql_fetch_array($objQuery)) { echo "<tr>"; echo "<td align='center'><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"$objResult[addedrec_ID]\"></td>"; echo "<td>$objResult[addedrec_ID] </td>"; echo "<td>$objResult[FirstName]</td>"; echo "<td>$objResult[LastName] </td>"; echo "<td>$objResult[MobileCompany] </td>"; echo "<td>$objResult[Cell] </td>"; echo "<td>$objResult[WorkPhone] </td>"; echo "<td>$objResult[Custgroup] </td>"; echo "</tr>"; } echo "<td colspan='7' align='center'><input name=\"delete\" type=\"submit\" id=\"delete\" value=\"Delete\">"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) // from button name="delete" { $checkbox = ($_POST['checkbox']); //from name="checkbox[]" $countCheck = count($_POST['checkbox']); for($d=0;$d<$countCheck;$d++) { $del_id = $checkbox[$d]; $sql = "DELETE from UserAddedRecord where addedrec_ID = $del_id"; $result2=mysql_query($sql) or trigger_error(mysql_error());;; } if($result2) { $fgmembersite->GetSelfScript(); } else { echo "Error: ".mysql_error(); } } echo "</form>"; Thanks for every reply. Hi all, I'm just wondering how everyone deletes their records using PHP or if you can give me any recommendations. Not really deleting, but I use UPDATE and change the deleteStatus column value. What is the best / recommended way, with a customer confirmation? Hi Guys, How come i am unable to delete a record with the same id from multi records with the following php code? $rid = "SELECT month_ID FROM monthA WHERE userID = '".$_POST['userID']."' AND thisMonth = '".$_POST['month']."' AND thisYear = '".$_POST['year']."'"; $rid_month = mysql_query($rid); $row = mysql_fetch_array($rid_month); $month_ID = $row["month_ID"]; $rid = "SELECT * FROM monthB WHERE month_ID = '$month_ID'"; $rid_month = mysql_query($rid); $row = mysql_fetch_array($add_member); while ($row = mysql_fetch_array($rid_month)) { $month_ID = $row["month_ID"]; $rid = "DELETE FROM monthBB WHERE month_ID = '$month_ID' "; $result = mysql_query($rid); } $rid = "SELECT * FROM monthC WHERE month_ID = '$month_ID' "; $rid_month = mysql_query($rid); while ($row = mysql_fetch_array($rid_month)) { $month_ID = $row["month_ID"]; $rid = "DELETE FROM monthCC WHERE month_ID = '$month_ID' "; $result = mysql_query($rid); } $rid = "DELETE FROM monthA WHERE month_ID = '$month_ID' "; $result = mysql_query($rid); I have tried a number of ways without any luck. How ever if i use this code? mysql_query("DELETE FROM monthA WHERE month_ID = '$month_ID'"); It allows me to delete one row from one table only. Please advise Hi all. I built an online finance tracking thingy for myself and I got it to work using the following database table and PHP code. I didn't write the PHP code, rather, I edited it to suit my needs. It works great for my needs. I have a way to enter records and view the last 180 records in a table. The thing is, while viewing the table, I would lke to be able to edit and delete records. I don't know enough to be able to do this. Can it be done? I realize my PHP code would probably, for the most part, be totally different. Thanks for any help with this. Here is my DB table structu Code: [Select] DROP TABLE IF EXISTS `money`; CREATE TABLE IF NOT EXISTS `money` ( `id` int(5) NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `type` varchar(18) NOT NULL, `checking` decimal(5,2) NOT NULL DEFAULT '0.00', `cash` decimal(5,2) NOT NULL DEFAULT '0.00', `description` varchar(25) NOT NULL, `who` varchar(25) NOT NULL, `note` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; And here is the PHP: Code: [Select] <?php $result = mysql_query ('SELECT date, type, checking, cash, who, description, note' . ' FROM money' . ' ORDER BY date DESC LIMIT 0,180') or die(mysql_error()); echo "<table border='1' cellpadding='5'>"; echo "<tr><th>Date</th><th>Type</th><th>Checking</th><th>Cash</th><th>Who?</th><th>Description</th><th>Note</th></tr>"; while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>"; echo $row['date']; echo "</td><td>"; echo $row['type']; echo "</td><td>"; echo $row['checking']; echo "</td><td>"; echo $row['cash']; echo "</td><td>"; echo $row['who']; echo "</td><td>"; echo $row['description']; echo "</td><td>"; echo $row['note']; echo "</td></tr>"; } echo "</table>"; ?> I need Delete Duplicate Email Records That Are Attached To One Account But Can Be Found In Multiple Accounts I have a table, consumer_mgmt. It collects consumer information from various forms. These forms are available through different pages that are part of a business package. A business can offer these signups to gather names and emails from consumers for various types of specials they may offer. So a consumer my be in the consumer_mgmt table 5, 10, 15 times for that particular business. But, that consumer may be in the consumer_mgmt table multiple times for a different business. So multiple times for multiple businesses. I need to remove duplicates for each business account so the consumer is only the consumer_mgmt only once for each business. There are approximately 15,000 rows currently in the consumer_mgmt table. I'm not sure where to begin on the logic. Since there are multiple business accounts that the emails are attached to, would one have to build a case for each loop? I'm trying to set it so that it will delete an entire populated directory based upon a value in the database then after finishing that to go back and delete that row in the database. my current code is Code: [Select] <?php $page_title = "Central Valley LLC | Photo Addition" ?> <?php include("header.php"); ?> <?php include("nav.html"); ?> <div id="content"> <form action="delprod.php" method="post" enctype="multipart/form-data"> <label for="which">Choose A Product To Remove:</label> <?php $con = mysql_connect("localhost","phoenixi_cv","centraladmin"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phoenixi_cvproducts", $con); $result = mysql_query("SELECT * FROM Products"); echo "<select name=\"which\">"; while($row = mysql_fetch_array($result)) { echo "<option "; echo "value=\"" . $row['id'] . "\">"; echo $row['Name'] . "</option>"; } echo "</select>"; mysql_close($con); ?> <br /> <input type="submit" name="submit" value="Submit" /> </form> </div><!--#content--> <?php include("footer.html") ?> and the delete script Code: [Select] <?php $con = mysql_connect("localhost","phoenixi_cv","centraladmin"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phoenixi_cvproducts", $con); $result = mysql_query("SELECT id FROM Products WHERE id=$_POST['which']"); $row = mysql_fetch_array($result) chdir('assets'); chdir('images'); $mydir = $row . '/'; $d = dir($mydir); while($entry = $d->read()) { if($entry!="." && $entry!="..") { unlink($_POST['which'] . '/' . $entry); } } rmdir($mydir); $result = mysql_query("DELETE * FROM Producs WHERE id=$_POST['which']"); ?> Thank you in advance for all your help. any easier ways of approaching this will be welcome as well Hi i have a search page that pulls the results from 3 different tables within my database it is shows a snippet of each record with a submit button which shows the full record in a pop up form if the user decides to click on it. The problem i am having is that lets say for example the contract table pulls down 3 results, the button next to the snippet for the first result will open the desired pop up. However the button for the other 3 records directs to a different form for another table. Does anyone have any idea <?php require "header.php"; ?> <main> <link href="style.css" rel="stylesheet" type="text/css"> <script>storedata.js</script> <div class="wrapper-main"> <div class="welcomelogged1"> <p>Searching For A Starter<p> </div> <form action="" method="post"> <select name="WeekComm" id="WeekComm"> <option value="Enter Week No To Search">Enter Week No To Search</option> <option value="WC 6th April">WC 6th April</option> <option value="WC 13th April">WC 13th April</option> <option value="WC 20th April">WC 20th April</option> <option value="WC 27th April">WC 27th April</option> </select> <input type="submit" name="Search" value="Search Starters" style="color: #FFFFFF; font-weight: bold; background-color: #81BC47;"></td> <br> <br> <br> </form> <form class ="formrecpaye" name="formrecpaye" id="formrecpaye" target="print_popup" action="searchrecordpaye.php" method="POST" onsubmit="window.open('searchrecordpaye.php','print_popup','width=1500,height=950');"> <table> <th class="resulttitle" colspan="8" style="text-align: center"><label name="Paye">PAYE New Starters</label></th> <Tr> <th class="blank"> </th> <th width="175px">Week Commencing</th> <th width="175px">First Name</th> <th width="175px">Last Name</th> <th width="175px">Consultant</th> <th width="150px">Start Date</th> <th width="175px">Client Name</th> <th width="130px">Action</th> </Tr> <?php require 'includes/dbh.inc.php'; if (isset($_POST['Search'])) { $WeekComm = $_POST['WeekComm']; $query = "SELECT * FROM paye where WeekComm='$WeekComm' "; $query_run = mysqli_query($conn,$query); while($row = mysqli_fetch_array($query_run)) { ?> <tr> <td align="center"><input readonly width="175px" type="hidden" name="id" value="<?php echo $row['id'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="WeekComm" value="<?php echo $row['WeekComm'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="FirstName" value="<?php echo $row['FirstName'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="LastName" value="<?php echo $row['LastName'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="Consultant" value="<?php echo $row['Consultant'] ?>"></td> <td align="center"><input readonly width="150px" type="date" name="StartDate" value="<?php echo $row['StartDate'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="ClientName"value="<?php echo $row['ClientName'] ?>"></td> <td align="center"><input type="submit" name="showdata1" action="searchrecordpaye.php" onclick="storedata()" value="View Record" style="color: #FFFFFF; font-weight: bold; background-color: #81BC47;"></td> </tr> </form> <?php } } ?> <form class ="formreccon" name="formreccon" id="formreccon" target="print_popup" action="searchrecordcon.php" method="POST" onsubmit="window.open('searchrecordcon.php','print_popup','width=1500,height=950');"> <table> <th class="resulttitle" colspan="8" style="text-align: center"><label name="ContractResultTitel">Contract New Starters</label></th> <Tr><th class="blank"> </th> <th width="175px">Week Commencing</th> <th width="175px">First Name</th> <th width="175px">Last Name</th> <th width="175px">Consultant</th> <th width="150px">Start Date</th> <th width="175px">Client Name</th> <th width="130px">Action</th> </Tr> <?php require 'includes/dbh.inc.php'; if (isset($_POST['Search'])) { $WeekComm = $_POST['WeekComm']; $query = "SELECT * FROM contract where WeekComm='$WeekComm' "; $query_run = mysqli_query($conn,$query); while($row = mysqli_fetch_array($query_run)) { ?> <tr> <td align="center"><input readonly width="175px" type="hidden" name="id" value="<?php echo $row['id'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="WeekComm" value="<?php echo $row['WeekComm'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="FirstName" value="<?php echo $row['FirstName'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="LastName" value="<?php echo $row['LastName'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="Consultant" value="<?php echo $row['Consultant'] ?>"></td> <td align="center"><input readonly width="150px" type="date" name="StartDate" value="<?php echo $row['StartDate'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="ClientName"value="<?php echo $row['ClientName'] ?>"></td> <td align="center"><input type="submit" name="showdata2" action="searchrecordcon.php" onclick="storedata()" value="View Record" style="color: #FFFFFF; font-weight: bold; background-color: #81BC47;"></td> </tr> </form> <?php } } ?> <form class ="formrecperm" name="formrecperm" id="formrecperm" target="print_popup" action="searchrecordperm.php" method="POST" onsubmit="window.open('searchrecordperm.php','print_popup','width=1500,height=950');"> <table> <th class="resulttitle" colspan="8" style="text-align: center"><label name="PermResultTitel">Permanent New Starters</label></th> <Tr> <th class="blank"> </th> <th width="175px">Week Commencing</th> <th width="175px">First Name</th> <th width="175px">Last Name</th> <th width="175px">Consultant</th> <th width="150px">Start Date</th> <th width="175px">Client Name</th> <th width="130px">Action</th> </Tr> <?php require 'includes/dbh.inc.php'; if (isset($_POST['Search'])) { $WeekComm = $_POST['WeekComm']; $query = "SELECT * FROM permanent where WeekComm='$WeekComm' "; $query_run = mysqli_query($conn,$query); while($row = mysqli_fetch_array($query_run)) { ?> <tr> <td align="center"><input readonly width="175px" type="hidden" name="id" value="<?php echo $row['id'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="WeekComm" value="<?php echo $row['WeekComm'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="FirstName" value="<?php echo $row['FirstName'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="LastName" value="<?php echo $row['LastName'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="Consultant" value="<?php echo $row['Consultant'] ?>"></td> <td align="center"><input readonly width="150px" type="date" name="StartDate" value="<?php echo $row['StartDate'] ?>"></td> <td align="center"><input readonly width="175px" type="text" name="ClientName"value="<?php echo $row['ClientName'] ?>"></td> <td align="center"><input type="submit" name="showdata3" action="searchrecordperm.php" onclick="storedata()" value="View Record" style="color: #FFFFFF; font-weight: bold; background-color: #81BC47;"></td> </tr> </form> <?php } } ?>
as standard the page displays like this
if i click on the 2nd result down on "contract new starters" a pop up windows opens with the address http://localhost/loginsystem/searchrecordpaye.php when i should be directed to http://localhost/loginsystem/searchrecordcon.php I am directed here if i select the first result in the list has anyone any ideas? Thanks
To accomplish the layout I was looking for, I used the following code: for ($i=1; $i<=7; $i++) { //set day of week for display as title of columns $dow=date("l", strtotime($year.'W'."$weekno"."$i")); echo "<td class=\"wvcolumn\" valign=\"top\"> <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" align=\"center\" width=\"$daycolumn\"> <tr><th class=\"wvtitle\" valign=\"bottom\" align=\"center\" width=\"$daycolumn\"><a class=\"titledate\" href=\"createticket.php?action=o&month=".date("m", strtotime($year.'W'."$weekno"."$i"))."&date=".date("d", strtotime($year.'W'."$weekno"."$i"))."&year=".date("Y", strtotime($year.'W'."$weekno"."$i"))."\">$dow, ".date("F d", strtotime($year.'W'.$weekno."$i"))."</a> <a onClick=\"window.open('http://www.batchgeo.com')\" title=\"Map $dow's Appointments\" href=\"mapday.php?week=$weekno&year=$year&day=$i\"><img width=\"20\" style=\"border-style: none\" src=\"../images/icon_globe.png\"></a></th></tr>"; if(date("Y-m-d")==date("Y-m-d", strtotime($year.'W'."$weekno"."$i"))) { $query = "SELECT fieldtickets.ticketnumber, fieldtickets.business, title, apptdatetime, DATE_FORMAT(apptdatetime,'%h:%i %p') AS fapptdatetime, status, billstatus, type, assigntech, clients.business FROM fieldtickets LEFT JOIN clients ON fieldtickets.business = clients.id WHERE status='Open' AND (type = 'Field' OR type = 'Phone') AND apptdatetime BETWEEN '".date("Y-m-d", strtotime($year.'W'."$weekno"."$i"))." 00:00:00' AND '".date("Y-m-d", strtotime($year.'W'."$weekno"."$i"))." 23:59:59' UNION SELECT fieldtickets.ticketnumber, fieldtickets.business, title, apptdatetime, DATE_FORMAT(apptdatetime,'%h:%i %p') AS fapptdatetime, status, billstatus, type, assigntech, clients.business FROM fieldtickets LEFT JOIN clients ON fieldtickets.business = clients.id WHERE status = 'Pending' ORDER BY status ASC, apptdatetime ASC"; } else { $query = "SELECT fieldtickets.ticketnumber, fieldtickets.business, title, apptdatetime, DATE_FORMAT(apptdatetime,'%h:%i %p') AS fapptdatetime, status, billstatus, type, assigntech, clients.business FROM fieldtickets LEFT JOIN clients ON fieldtickets.business = clients.id WHERE status='Open' AND (type = 'Field' OR type = 'Phone') AND apptdatetime BETWEEN '".date("Y-m-d", strtotime($year.'W'.$weekno."$i"))." 00:00:00' AND '".date("Y-m-d", strtotime($year.'W'.$weekno."$i"))." 23:59:59' ORDER BY apptdatetime ASC"; } $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ //if ticket is open show appt time and business, if ticket pending display DELIVERY and business name if($row[status]=="Open") { $href="createticket.php?action=e&ticket=".$row[ticketnumber]; $time=$row[fapptdatetime]; $delivery=""; } elseif($row[status]=="Pending") { $href="createticket.php?action=c&ticket=".$row['ticketnumber'].""; $time=""; $delivery="DELIVER"; } echo "<tr><td valign=\"top\"><a title=\"".$row[ticketnumber]." - ".$row[title]."\" class=\"".$row[status]."\" href=\"$href\"><span>$delivery$time ".substr($row['business'], 0, $displaychars)."</span></a></td></tr>\n"; } echo "</table>"; } echo "</td></tr> </table>"; Output is similar to this, and any existing "deliveries" are displayed under the current day. _________________________________________________ ______________ | Monday | Tuesday | Wednesday | Thursday | Friday | |appointments |appointments |appointments |appointments |appointments This works great, but requires 5 separate queries. My database is very small for now, so its not a big deal, but I know this can be done much more efficiently. How can I query the whole week and put appointments in their corresponding tables (days)? Thank you for your help! I am trying to make a filter to show posts from mutual friends between you and the persons profile you're on, I have somewhat of an idea on how to write the mysql query (it needs to be just one query, not two(which would be the easy way of doing it)). the "friends" table has: "friend_1" and "friend_2" and the "posts" table: "to_id" and "from_id" The PHP variables would be: "$session" and "$id" id would be the users Id of the profile you're on. Thanks, any help would be appreciated. Hello all, I am new to php coding and have a couple of problems with editing records in my database! I have two files below one test.php and edit.php. In the test.php the code outputs the records into a table. The problem is with the edit link as when it is selected I wish to be able to edit a record by a form, which is on edit.php. I am trying bring up the movie's information on the form to be edited. Currently on the form i get; Quote Movie: movie Gen Genre Year: year Any ideas how I can edit the record and then return to the test.php page? Code: [Select] test.php <html> <body style="background-color:#669999;"> <table width="490"border=0><tr> <td colspan="2" style="background-color:#FFA500;"> <div id="header" <h3 style="color:black">This is my first web-page! Below is a database of some of my favourite movies! </h3> </td> </tr> <?php //connecting to server $con = mysql_connect("localhost","root","NYOXAkly"); if (!$con) { die('could not connect: ' . mysql_error()); } //selecting movie database mysql_select_db("my_mov",$con); //Check if add button is active, start this if(isset($_REQUEST['add'])) { echo "<meta http-equiv=\"refresh\"content=\"0;URL=form.php\">"; } $result = mysql_query("SELECT * FROM Films ORDER BY filmID"); ?> <!-------------------------------creating table------------------------------------------------------------------------------------> <table width="490" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <form name="test1" method="post" action="test.php"> <table width="490" border="10" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"><tr> <td bgcolor="#FFFFFF"></td> <td align="center" colspan="6" bgcolor="#FFFFFF">Movie Database</td></tr> <td align="center" bgcolor="#FFFFFF">filmID</td> <td align="center" bgcolor="#FFFFFF">Movie</td> <td align="center" bgcolor="#FFFFFF">Genre</td> <td align="center" bgcolor="#FFFFFF">Year</td> <td align="center" bgcolor="#FFFFFF">Edit</td> <td align="center" bgcolor="#FFFFFF">Delete</td> </tr> <?php while($rows=mysql_fetch_array($result)) { ?> <tr> </td> <td bgcolor="#FFFFFF"><? echo $rows['filmID']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['movie']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['genre']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['year']; ?></td> <td bgcolor="#FFFFFF"> <a href="edit.php?filmID=<?php echo 'filmID';?>">Edit</a> <td bgcolor="#FFFFFF"> <a href="delete.php?filmID=<?php echo 'filmID';?>">Delete</a> </td> </tr> <?php } echo print_r(error_get_last()); mysql_close(); ?> <!--add button--> <tr> <td colspan="15" align="left" bgcolor="#FFFFFF"> <input name='add' type="submit" filmID="add" value="Add A New Record" action="form.php?"> </td> </tr> </table> </form> <br/> By C.M.D.W <br/> <?php echo date("Y/m/d") . "<br />"; ?> </body> </html> Code: [Select] edit.php <html> <body style="background-color:#669999;"> <!------------------Creates a form ----------------------> <br /> <form action="" method="post"> <fieldset> <legend>Enter your movies into database here!</legend> Movie: <input type ="text" name="movie" value="<?php echo 'movie';?>"> <br /> Gen <input type ="text" name="genre" value="<?php echo 'genre';?>"/> <br /> Year: <input type ="text" name="year" value="<?php echo 'year';?>"/> <br /> <input type="submit" name="name" value="Submit" /> </fieldset> </form> <?php //connecting to server $con = mysql_connect("localhost","root","NYOXAkly"); if (!$con) { die('could not connect: ' . mysql_error()); } //selecting movie database mysql_select_db("my_mov",$con); if (isset($_POST['submit'])) { // confirm that the 'id' value is a valid integer if (is_numeric($_POST['filmID'])) // get form data $filmID = $_POST['filmID']; $movie = mysql_real_escape_string(htmlspecialchars($_POST['movie'])); $genre = mysql_real_escape_string(htmlspecialchars($_POST['genre'])); $year = mysql_real_escape_string(htmlspecialchars($_POST['year'])); // check that fields are filled in if ($movie == '' || $genre == '' || $year == '') { // generate error message $error = 'ERROR: Please fill in all required fields!'; } else { // save the data to the database } mysql_query("UPDATE players SET movie='$movie', genre='$genre', year='$year' WHERE filmID='$filmID'") or die(mysql_error()); // once saved, redirect back to the view page header("Location: test.php"); } } if (isset($_GET['filmID']) && is_numeric($_GET['filmID']) && $_GET['filmID'] > 0) { // query db $id = $_GET['filmID']; $result = mysql_query("SELECT * FROM Films WHERE filmID=$FilmID") or die(mysql_error()); $row = mysql_fetch_array($result); // check that the 'id' matches up with a row in the databse if($row) { // get data from db $movie = $row['movie']; $genre = $row['genre']; $year = $row['year']; }} ?> <br/> <br/> <a href="test.php">Return To Home Page</a> <br/> <br/> By C.M.D.W <br/> <?php echo date("Y/m/d") . "<br />"; ?> </body> </html> Thanks Chris Hi guys, I am trying to UPDATE some records on a mySQL database but can't seem to find out why it is not working. This is my code. Code: [Select] <?php $latitude = $_POST['lat_location']; $longitude = $_POST['long_location']; $unique_ID = $_POST['unique_ID']; include('connect2.php'); $query = mysql_query("SELECT * FROM user_location WHERE unit = '$unique_ID'"); $numrows = mysql_num_rows($query); if ($numrows == 1) { $query2="UPDATE user_location SET lat = '$latitude', long = '$longitude' WHERE unit = '$unique_ID'"; mysql_query($query2); $test = "matches"; } else { mysql_query("INSERT INTO user_location VALUES ('','$unique_ID','$latitude','$longitude')"); $test = "not match"; } echo $test . "<br />"; echo $numrows; ?> The script receives the data via the POST method and assigns it to variables. Then I query the database for one of those variables and check how many results are found. If 0 results are found then a new record is created on the database, but if there is 1 record found then the record that is found has to be UPDATED. When the result is 0 the scripts creates the new record fine, but if the result is 1 it doesn't update. I just can't figure out why. Any help will be greatly appreciated. Thanks in advanced, Hey guys just wandered if you can help me on my website in the mailbox section next to the message there is a delete button to obviously delete that current message.
However as I am sure you can appreciate it get tedious when you have 20 messages to do them all at once.
So I am after putting a button at the top of this column in the table that will delete all the messages in there with one click.
Below is the coding of where all this takes place:
function mailbox($mes,$page) { global $config; if(!$page) { $page="1"; } $page=($page - 1); $totalmes=mysql_query("SELECT COUNT(*) FROM messages WHERE toid='".$_SESSION['tid']."' AND rcvddel=0"); $totalmes=mysql_result($totalmes,0); $out[body].=" <div style='float:left;width:69%;margin:5px;'> <table cellspacing='1' cellpadding='1' border='0' width='100%'> <tr> <td width='100%' class='blk_tcon' colspan='5'><b>" . LANG_MAI_MAILBOX . "</b></td> </tr> <tr> <td width='50%' colspan='2' class='blk_tcon_top'>" . LANG_MAI_SUBJECT . "</td> <td width='20%' class='blk_tcon_top'>" . LANG_MAI_FROM . "</td> <td width='25%' class='blk_tcon_top'>" . LANG_MAI_DATE . "</td> <td width='5%' class='blk_tcon_top'></td> </tr>"; $fmail=mysql_query("SELECT id,fromid,subject,active,sent FROM messages WHERE toid='".$_SESSION['tid']."' AND grid='1' AND rcvddel=0 ORDER BY sent DESC LIMIT $page, 15"); while(list($id,$fromid,$subject,$active,$sent)=mysql_fetch_row($fmail)) { $from=mysql_query("SELECT name FROM members WHERE id='$fromid'"); $from=mysql_fetch_array($from); if($fromid == '01') { $froma="Site Challenge"; }else{ $froma="<a href='./profile.php?account=$fromid'>$from[name]</a>"; } if($active == 1) { $icon="<img src='./images/unread.gif' border='0' alt='' />"; $title="<a href='./mailbox.php?action=readmail&mailtype=received&mid=$id'><b>$subject</b></a>"; }else if($active == 2){ $icon="<img src='./images/read.gif' border='0' alt='' />"; $title="<a href='./mailbox.php?action=readmail&mailtype=received&mid=$id'>$subject</a>"; }else{ $icon="<img src='./images/replied.gif' border='0' alt='' />"; $title="<a href='./mailbox.php?action=readmail&mailtype=received&mid=$id'>$subject</a>"; } $out[body].=" <tr> <td width='5%' align='center' class='blk_tcon'>$icon</td> <td width='45%' align='left' class='blk_tcon'>$title</td> <td width='20%' align='center' class='blk_tcon'>$froma</td> <td width='25%' align='center' class='blk_tcon'>$sent</td> <td width='5%' align='center' class='blk_tcon'> <form method='post'> <input type='hidden' name='mail[id]' value='$id' /> <input type='hidden' name='mail[mailtype]' value='received' /> <input type='hidden' name='action' value='delete' /> <input type='submit' class='button' name='submit' value='X' style='color:red; font-weight:bold;' title='" . LANG_MAI_DELETE . "' /> </form> </td> </tr>"; } if($totalmes == 0) { $out[body].=" <tr> <td width='100%' align='center' colspan='5' class='blk_tcon'>" . LANG_MAI_MAILBOX_EMPTY . "</td> </tr>"; } $pagenow=($page + 1); $pages=1; if($pagenow==1) { $skipranks.="[$pages] "; }else{ $skipranks.="<a href='./mailbox.php?page=1'>$pages</a> "; } $arank=1; $brank=15; while($brank < $totalmes) { $arank=($arank + 15); $brank=($brank + 15); $pages++; if($pagenow==$arank) { $skipranks.="[$pages] "; }else{ $skipranks.="<a href='./mailbox.php?page=$arank'>$pages</a> "; } } $out[body].=" <tr> <td width='100%' align='center' class='blk_tcon' colspan='5'>$skipranks</td> </tr> </table> </div> ".TOP_MENU.""; include("$config[html]"); } </tr>"; Im displaying the results of a database by using a while loop... so Im trying to figure out how to delete some entries from the datbase. What I wanted to do is add a button in each result that will have the value "delete"... but I cant figure out how to do this. Im kinda new to mysql. I just want it so when I click the button the result will get deleted from the database. I did some research on this but I cant really grasp the examples. Can anybody help me out with this one? Thanks! I'm sorry to be back so soon, but I'm up against another mystery. I'm using the code below to enter a bunch of css data from a spreadsheet into a mysql table. I think the data file is OK. The array created by the script checks out with print_r. (There are many more records than shown. I truncated it to save space.) The problem is that I get this error regarding my sql statement, not the data or anything else: Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'check, name, phone, email, entry_fee, print_fee, image_name, description, med...' at line 1 in /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php:242 Stack trace: #0 /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php(242): PDO->prepare('INSERT INTO tbl...') #1 {main} thrown in /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php on line 242 I've typed it in a dozen times to make sure there are no errors and keep getting the same error. I tried running a test file and gradually increasing the number of placeholders and at some point I always end up getting the same error, I can delete the most recent addition and it works again. Then I can add another placeholder exactly as before and it works the second time. It feels like a ghost in the machine. Any idea what I am doing wrong? An I typing something I don't see? <?php require '__classes/Db.php'; $csvData = '1,FALSE,Carol Lettko,,,TRUE,FALSE,Carol_Lettko-DSC_3022.jpg,Baby Herons/Brickyard,photo,,, ,,,925-285-0320,cjl164@aol.com,,,Carol_Lettko-DSC_0164.JPG,Heron/Brickyard,photo,,, ,,,,,,,Carol_Lettko-IMG_5723.jpg,Kayaker/Brickyard,photo,,, ,,,,,,,,,,,, 2,FALSE,Louise Williams,,,TRUE,FALSE,Louise_Williams-BirdsOfAFeatherAOPR.jpg,Alligator with Words,Book Excerpt,,, ,,,510-232-9547,lkw@louisekwilliams.com,,,Louise_Williams-Hope-TheFairyChickenAOPR.jpg,Hope The Fairy Chicken,,,, ,,,The d exatrfrfvct/.*tygrvurr,,,,,,,,, ,,,,,,,,,,,, 3,TRUE,Dorothy Leeland,,lelanddorothy@gmail.com,TRUE,FALSE,DJ_Lee-bridge at dusk 700px width.jpg,Bridge,photo,,, ,,,,,,,DJ_Lee-friends 700px width.jpg,Friends,photo,,, ,,,,,,,DJ_Lee-hybiscus 700 px wide.jpg,Hibiscus,photo,,, ,,,,,,,,,,,, 4,FALSE,Rita Gardner,,,TRUE,FALSE,Rita_Gardner-Explosion - Gardner photo.JPG,Explosion,photo,,, ,,,,tropicrita@msn.com,,,Rita_Gardner-Ferry Point tables and chair - Gardner.JPG,Ferry Point Tables,photo,, , ,,,,,,,Rita_Gardner-Forks - Gardner photo.JPG,Forks,photo,,, ,,,,,,,,,,,, '; $lines = explode(PHP_EOL, $csvData); $array1 = array(); foreach ($lines as $line) { $array1[] = str_getcsv($line); } $stmt = $pdo->prepare("INSERT INTO tbl_person_data (number, check, name, phone, email, entry_fee, print_fee, image_name, description, medium, select, orient, site) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); foreach ($array1 as $row) { $stmt->execute('$row'); } echo '<pre>'; print_r($array1); echo '</pre>'; ?>
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,I'm hoping someone can help me:). When I add foreign keys to the database in MySQL I CAN change the primary key field and the corresponding indexed field will automatically change giving me the same value which is exactly what i want. The issue is when I try to insert the values using my php code i get the 'cannot update child error'. I have not selected a value for the unique_id field as I want it to inherit the value from the primary key. Here's my code as simplified as I could do it. <?php //this calls the class productupload and instantiates the function insert_form to insert values into the db. $product = new productUpload(); $product->insert_form();?> //This calls the insert_form function and inserts info into tables <?php class productUpload extends DatabaseObject{ protected static $table_name="itm_details"; protected static $db_fields =array('id','unique_id','itm_cat','itm_make','itm_model','itm_desc','itm_cond','itm_date_from','itm_date_to','itm_add_date'); public $id; public $unique_id; public $itm_cat; public $itm_make; public $itm_model; public $itm_desc; public $itm_cond; public $itm_date_from; public $itm_date_to; public $itm_add_date; Heres the function insert_form which grabs the form submitted data. Note I have not defined a value for $unique_id public function insert_form(){ global $database; //set the object attributes to the form the parameters if(isset($_POST['submit'])) { $result = array( $this->itm_cat =(!empty($_POST['itm_cat'])) ? trim($_POST['itm_cat']) : NULL, $this->itm_make =(!empty($_POST['itm_make'])) ? trim($_POST['itm_make']) : NULL, $this->itm_model = (!empty($_POST['itm_model'])) ? trim($_POST['itm_model']) : NULL, $this->itm_desc =(!empty($_POST['itm_desc'])) ? trim($_POST['itm_desc']) : NULL, $this->itm_cond =(!empty($_POST['itm_cond'])) ? trim($_POST['itm_cond']) : NULL, $this->itm_date_from =(!empty($_POST['itm_date_from'])) ? trim($_POST['itm_date_from']) : NULL, $this->itm_date_to =(!empty($_POST['itm_date_to'])) ? trim($_POST['itm_date_to']) : NULL, $this->itm_add_date = date("Y-m-d H:m:s")); //check date is numeric //if(is_numeric($_POST['itm_date_from'])) { //$this->itm_date_from = $_POST['itm_date_from']; //} //check date is numeric //if(is_numeric($_POST['itm_date_to'])) { //$this->itm_date_to = $_POST['itm_date_to']; //} if($result){ $result = $this->create(); } } } //here's the create function referred to above which sanitises the posted data and inserts it into the db. public function create() { global $database; $attributes = $this->sanitised_attributes(); $sql = "INSERT INTO ".self::$table_name."("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)) { $this->id = $database->insert_id(); return true; } else { return false; } } Hi guys, I need your help. I am checking on a database as I want to see if the records have been updated or not. Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbtable'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $username = clean($_GET['user']); $password = clean($_GET['pass']); $test = clean($_GET['test']); $public = clean($_GET['public']); if (isset($_GET['user']) && (isset($_GET['pass']))) { if($username == '' || $password == '') { $errmsg_arr[] = 'username or password are missing'; $errflag = true; } } elseif (isset($_GET['user']) || (isset($_GET['test'])) || (isset($_GET['public']))) { if($username == '' || $test == '' || $public == '') { $errmsg_arr[] = 'user or others are missing'; $errflag = true; } } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $qry="SELECT * FROM members WHERE username='$username' AND passwd='$password'"; $result=mysql_query($qry) or die('Error:<br />' . $qry . '<br />' . mysql_error()); if ($username && $password) { if(mysql_num_rows($result) > 0) { $qrytable1="SELECT images, id, test, links, Public FROM user_channel_list WHERE username='$username'"; $result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error()); while ($row = mysql_fetch_array($result1)) { echo "<p id='test'>"; echo $row['test'] . "</p>"; echo '<p id="images"> <a href="images.php?test=test&id='.$row['id'].'">Images</a></td> | <a href="http://' . $row["links"] . '">Link</a> </td> | <a href="delete.php?test=test&id='.$row['id'].'">Delete</a> </td> | <span id="test">'.$row['Public'].'</td>'; } } else { echo "user not found"; } } elseif($username && $test && $public) { $qry="SELECT * FROM members WHERE username='$username'"; $result1=mysql_query($qry) or die('Error:<br />' . $qry . '<br />' . mysql_error()); if(mysql_num_rows($result1) > 0) { $qrytable1="SELECT Public FROM user_channel_list WHERE username='$username' && test='$test'"; $result2=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error()); if(mysql_num_rows($result2) > 0) { $row = mysql_fetch_row($result2); mysql_query("UPDATE user_list SET Public=('$_GET[public]') WHERE username='$username' AND test='$test'"); echo "update!"; } else { echo "already updated!"; } } else { echo "user not found"; } } } ?> When I run debug the code on my php, if i input the data in a url bar while the records are the same as the data that I enter in the url, i should get the print out on my php "already updated", but I keep getting "update!". Do you know how i can check on mysql database to see if the records have been updated or not?? Hello, This is driving me crazy, as I cannot get it working. I have a database that has a table called 'categories'. I need to retrieve all categories with category_id != '1,2,3'. For this, I can this query: Code: [Select] $q = "SELECT * FROM categories WHERE category_id NOT IN (1,2,3)"; The query executes fine. I need this categories retrieved, to be passed to a Smarty Template Engine powered page. I have: Code: [Select] $q = "SELECT * FROM categories WHERE category_id NOT IN (1,2,3)"; $res = mysql_query($q); while($row=mysql_fetch_array($res)) { Assign('categories',$row); } But when retrieving the array in the Smarty page, with a loop, I only see the last item of the array (the last category). If I go back to the while loop, and add a Code: [Select] print_r($row);, I see two arrays (I have two categories). But the question is: How can I work with those two categories, as I need to use them individually outside the while loop? Any help is appreciated. Best Regards, Richi |