PHP - Unable To Delete The Rows From The Database
Hi,
I have created a table named multipath with database name "mydatabase".. I have created a table to store the data in the tables. Check boxes are created to select one row each to delete. But I am unable to delete the rows. Why?? Here's my PHP code <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="mydatabase"; // Database name $tbl_name="multipath"; // Table 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 $tbl_name"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="form1" method="post" action=""> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td bgcolor="#FFFFFF"> </td> <td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td> </tr> <tr> <td align="center" bgcolor="#FFFFFF">#</td> <td align="center" bgcolor="#FFFFFF"><strong>Path ID</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Path</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> <td bgcolor="#FFFFFF"><?php echo $rows['path_id']; ?></td> <td bgcolor="#FFFFFF"><?php echo $rows['path']; ?></td> </tr> <?php } ?> <tr> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <? // Check if delete button active, start this if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM $tbl_name WHERE id='$del_id'"; $result = mysql_query($sql); } // if successful redirect to delete.php if($result){ echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">"; } } mysql_close(); ?> </table> </form> </td> </tr> </table> Please u can reply me at sawyerford007ATgmail DOTcom Similar TutorialsHey everyone i having some trouble updating records in my databse using checkbox from a form. I can update the records, but i can't figure out how to remove records at the same time. I've posted the code that i'm using to update below foreach($_POST['tag'] as $k=>$l){ $tag = mysql_real_escape_string($_POST['tag'][$k]); $check_tags = mysql_query("SELECT * FROM file_cats WHERE category='$tag'") or die(mysql_error()); $num_tags = mysql_num_rows($check_tags); if($num_tags==0){ $add_tag = mysql_query("INSERT into file_cats (fileID, category) VALUES('$fileID', '$tag')") or die(mysql_error()); } } This code inserts new records based on what the user checked. If it exist it won't add a new row, if it doesn't exist then it will add a new row. but like i said how can remove a row if the box is no longer checked? I've tried using foreach(empty($_POST['tag'] as $k => $l){ $tag = empty($_POST['tag']['$k']; } But that didn't work basically nothing was deleted. Has anyone done something like this before? if so i would appreciate any help you could give <body> <?php include 'sql.php'; $query = "SELECT * FROM validation"; $result = mysqli_query($con , $query); $rows = mysqli_fetch_assoc($result) ; $totals = mysqli_num_rows($result) ; ?> <div id="css"> <form > <table width="80%" border="0" cellpadding="2" cellspacing="2" > <caption><h2>Personal Details of Customers</h2></caption> <tr class="white"> <td bgcolor="#330033"> </td> <td bgcolor="#330033"> Id Number </td> <td bgcolor="#330033"> Full Name </td> <td bgcolor="#330033"> Email Address </td> <td bgcolor="#330033"> Website </td> <td bgcolor="#330033"> Comment </td> <td bgcolor="#330033"> Time </td> </tr> <?php while($rows=mysqli_fetch_assoc($result) { <tr> <input type="raido" name="ID" value="<?php echo $rows['ID']; ?>" /> <td bgcolor="#FFFFCC"><?php echo $rows['ID'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Name'];?> </td> <td bgcolor="#FFFFCC"><?php echo $rows['Email'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Website'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Comment'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Time'];?></td> <td> </td> <td> <a href="delete.php? ID= "$rows[ID]" /"> <input type="submit" name="del" value="Delete" /> </a> <input type="button" name= "edit" value="Edit" /> </td> </tr> }?> </table> </form> </div> </body> Hi,
I wish to find out is there any possible that I can delete some data inside my php website but inside my sql database, the record will still at there?
Thank you.
in my code i have $query = "DELETE " . $DBPrefix . "bids WHERE auction = " . $Auction['id']; $system->check_mysql(mysql_query($query), $query, __LINE__, __FILE__); but if WHERE auction = " . $Auction['id'] doesnt match anything i returns the error Quote You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE auction = 8' at line 1 I really dont understand why its returning an error is this just a case of having to add some code to check if theres anything that actualy needs deleting first? Can I use php to delete multiple rows that have a checkbox selected. I'm not sure how to go about doing this. Any suggestions? I have a table with several fields, one of which is an amount of days after which the row will be deleted. Every time the script is run, I want to check for old entries and delete them. How would I do this? Hey Guys. I have tried looking this up on Google but the only answers I am finding is using there where clause. I wanted to know if I can update or delete a range of rows like from id 100-200. Is there a way to do that? Thanks!
Hello all, im new to this forum, im a noobie, just started coding about 3 weeks ago, don't be too hard on me.
My question is I wan't to check for challenges a user's team posted that have not been excepted after 1 day, then auto refund the user's team back there credits, and then also delete all the challenges. So far here is my code.
//Delete all matches not accepted after 1 day $arrayin = array(); $autorefund = mysql_query("SELECT * FROM `challenges` WHERE `a` = " . $team['id'] . " " . "AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < " . ((int) time()) . ")"); if (mysql_num_rows($autorefund) > 0) { while ($autorefund = mysql_fetch_assoc($autorefund)) { $arrayin[] = $autorefund['id']; mysql_query("UPDATE `teams` SET `balance` = `balance` + " . $autorefund['credits'] . " " . "WHERE `id` IN (" . mysql_real_escape_string(implode(',', $arrayin)) . ")"); mysql_query("DELETE FROM `challenges` WHERE `a` IN " . "(" . mysql_real_escape_string(implode(',', $arrayin)) . ") " . "AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 " . "AND (`expires` < " . ((int) time()) . ")"); } }FYI here is the code i had, it works fine, however it will only delete 1 challenge per team, not all of there challenges. $autorefund = mysql_query("SELECT * FROM `challenges` WHERE `a` = " . $team['id'] . " AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < ".((int)time()).")"); if (mysql_num_rows($autorefund) > 0) { while ($autorefund = mysql_fetch_assoc($autorefund)) { if ($autorefund['accepted'] == 0 and $autorefund['expires'] < time()) { mysql_query("UPDATE `teams` SET `balance` = `balance` + " . $autorefund['credits'] . " WHERE `id` = " . $team['id'] . ""); mysql_query("DELETE FROM `challenges` WHERE `a` = " . $team['id'] . " AND `accepted` = 0 AND `completed` = 0 AND `chtype` = 1 AND (`expires` < ".((int)time()).")); } } }I inherited this script, its using deprecated statements, i know im not skilled to rewrite the entire site to use prepared statements. This is my code is display my database (member_details) after user sign up but when a user register first name = <script>window.location="google.com"</script> This error occur=(The requested URL /yy2/html/google.com was not found on this server) Code: [Select] <?php session_start(); include ('includes/database_connection.inc.php'); $conn = connectDatabase(); if($_SESSION['uid'] == ''){ // redirect unauthenticate user to login page. header('Location: login.php'); } if($_GET['task'] == 'delete' && $_GET['id'] != ''){ // delete function here $sql="DELETE FROM Newest Where ID='".mysql_real_escape_string($_GET['id'])."'"; mysql_query($sql,$conn); header('Location: member_list.php'); } if($_POST['Logout']){ session_destroy(); header('Location: login.php'); } ?> <html><head><title>Member Details</title> </head> <body> <div style=" margin: 350px "> <?php $sql="SELECT * FROM Newest"; $rs = mysql_query($sql,$conn) or die( mysql_error() ); $list = "<table border=\"1\" cellpadding= \"2\">"; $list .= "<tr><th>First Name</th>"; $list .="<th>Last Name</th>"; $list .= "<th>User Name</th>"; $list .= "<th>Email</th>"; $list .= "<th>Edit User</th>"; $list .= "<th>Delete User</th>"; $list .= "<th>Change Password</th>"; While( $row = mysql_fetch_array($rs) ) { $list .= "<tr>"; $list .= "<td>".$row["name"]."</td>"; $list .= "<td>".$row["last"]."</td>"; $list .= "<td>".$row["user"]."</td>"; $list .= "<td>".$row["email"]."</td>"; $list .= "<td><a href='member_details.php?id=".$row['ID']."'>Edit</a></td>"; $list .= "<td><a onclick='return confirm(\"Are you sure to delete ".$row["name"]." \")' href='member_list.php?id=".$row["ID"]."&task=delete'>Delete</a></td>"; $list .= "<td><a href='Password.php?id=".$row['ID']."'>Click Here</a></td> </tr>"; } $list .= "</table>"; echo ( $list ); ?> <form method="post" action="member_list.php"><br> <div style="margin : 0px 600px"> <style type="text/css"> body {background:#F5F5F5 url('http://images.apple.com/downloads/dashboard/travel/images/traveltodolist_20070724165034.jpg') no-repeat top;; }</style> <input type="submit" name="Logout" value="logout" /> </form> </body> </html> MOD EDIT: [code] . . . [/code] BBCode tags added. Hello all, I hope you are doing great.I am using phpmyadmin for the first time.So I created a table called guestbook with 4 attributes: id,name,email,message..Then I created a php file with the following code (saved in htdoc in Xampp folder)and html form which would take the data from the user and insert into the database which could later be retrieved.So far I have just written the insertion code which successfully creates the form but when I click on submit button it opens the same php file with the code and no insertion is made in the database..here is my code..please help me urgently..i have my project deadline very soon. php file called guest.php: <?php $user="root"; $password=""; $database="Guestbook"; $name=$_POST['name']; $email=$_POST['email']; $body=$_POST['body']; $connect("localhost",$user,$password); mysql($connect); @mysql_select_db($database)or die("unable to select db"); $query = mysql_query("INSERT INTO Guestbook(id,name,email,body) VALUES('','$name','$email','$body')"); if(!$query) { echo mysql_errno().':'.mysql_error(); } mysql_close(); ?> html file called new.html: <html> <head> <title>Guestbook</title> </head> <body> <form method="post" action="guest.php" > Name:<input type="text" name="name" size="30"/><br/> Email: <input type="text" name="email" size="30"/><br/> <p>Text:<br/> <textarea name="message" rows="15" cols="60"></textarea></p> <br/> <input type="submit" value="Submit"/> <input type="reset" value="Clear"/> </form> </body> </html> Hi, I need some help here, the one which I have highlighted in red, 'dob' and 'gender', are not inputting any values into my database table. I'm just wondering did I miss out something important, or should I change the 'type' in my database table? Thanks <?php $dob = $_POST['dob']; $gender = $_POST['gender']; /**INSERT into tutor_profile table**/ $query2 = "INSERT INTO tutor_profile (name, nric, dob, gender, race) VALUES ('$name', '$nric', '$dob', '$gender', '$race')"; $results2 = mysqli_query($dbc, $query2) or die(mysqli_error()); ?> <html> <div> <label for="dob" class="label">Date Of Birth</label> <input name="dob" type="text" id="dob"/> </div> </html> <!--Race--> <div> <label for="race" class="label">Race</label> <?php echo '<select name="race" id="race"> <option value="">--Please select one--</option>'; $dbc = mysqli_connect('localhost', '111', '111', '111') or die(mysqli_error()); $query = ("SELECT * FROM race ORDER BY race_id ASC"); $sql = mysqli_query($dbc, $query) or die(mysqli_error()); while($data = mysqli_fetch_array($sql)) { echo'<option value="'.$data['race_id'].'">'.$data['race_name'].'</option>'; } echo '</select><br/>'; mysqli_close($dbc); ?> </div> <?php $GLOBALS['title']="Admission-HMS"; $base_url="http://localhost/hms/"; require('./../../inc/sessionManager.php'); require('./../../inc/dbPlayer.php'); require('./../../inc/fileUploader.php'); require('./../../inc/handyCam.php'); $ses = new \sessionManager\sessionManager(); $ses->start(); if($ses->isExpired()) { header( 'Location:'.$base_url.'login.php'); } else { $name=$ses->Get("loginId"); } $msg=""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST["btnSave"])) { $db = new \dbPlayer\dbPlayer(); $msg = $db->open(); echo '<script type="text/javascript"> alert("'.$msg.'");</script>'; if ($msg = "true") { $userIds = $db->getAutoId("U"); $flup = new fileUploader\fileUploader(); $perPhoto = $flup->upload("/hms/files/photos/",$_FILES['perPhoto'], $userIds[1]); // var_dump($perPhoto); $handyCam=new \handyCam\handyCam(); if (strpos($perPhoto, 'Error:') === false) { $dateNow=date("Y-m-d"); $data = array( 'userId' => $userIds[1], 'userGroupId' => "UG004", 'name' => $_POST['name'], 'studentId' => $_POST['stdId'], 'cellNo' => $_POST['cellNo'], 'gender' => $_POST['gender'], 'dob' => $handyCam->parseAppDate($_POST['dob']), 'passportNo' => $_POST['passportNo'], 'fatherName' => $_POST['fatherName'], 'fatherCellNo' => $_POST['fatherCellNo'], 'perPhoto' => $perPhoto, 'admitDate' => $dateNow, 'isActive' => 'Y' ); $result = $db->insertData("studentinfo",$data); if($result>=0) { $data = array( 'userId' => $userIds[1], 'userGroupId' => "UG004", 'name' => $_POST['name'], 'loginId' => $_POST['stdId'], 'verifyCode' => "vhms2115", 'expireDate' => "2115-01-4", 'isVerifed' => 'Y' ); $result=$db->insertData("users",$data); if($result>0) { $id =intval($userIds[0])+1; $query="UPDATE auto_id set number=".$id." where prefix='U';"; $result=$db->update($query); // $db->close(); echo '<script type="text/javascript"> alert("Admitted Successfully.");</script>'; } else { echo '<script type="text/javascript"> alert("' . $result . '");</script>'; } } elseif(strpos($result,'Duplicate') !== false) { echo '<script type="text/javascript"> alert("Student Already Exits!");</script>'; } else { echo '<script type="text/javascript"> alert("' . $result . '");</script>'; } } else { echo '<script type="text/javascript"> alert("' . $perPhoto . '");</script>'; } } else { echo '<script type="text/javascript"> alert("' . $msg . '");</script>'; } } Hi guys, I am recent working on my php to delete the information in a database. When I insert the value in the url bar something is like: www.mysite.com/delete.php?myfavorites=what ever it is&user=test. When I inserted the value in the url bar, it did not search for the value in a database to delete it while match with the username in the url bar. Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbname'); $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)); } $favorites = clean($_GET['favorites']); $username = clean($_GET['user']); if($favorites == '' && $username == '') { // both are empty $errmsg_arr[] = 'Favorites are missing.'; $errflag = true; if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['favorites'])) { $insert[] = 'favorites = \'' . clean($_GET['favorites']) . '\''; } if(isset($_GET['username'])) { $insert[] = 'username = \'' . clean($_GET['username']) . '\''; } if (count($insert)>0) { $names = implode(',',$insert); if($favorites && $username) { mysql_query("DELETE valuedata FROM favorites WHERE username='$username'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo("The value in favorites are deleted"); } else { echo("failed"); } }else{ echo("failed"); } } } mysql_close($link); ?> If you know how to delete the value in a database for each row while it match with the username in the url, please say so as i would like to know how to do it. Any advise would be much appreciated. Thanks, Mark Hi guys, I need a bit of your help. I have successfully deleted a row in a database after I have inserted the value name with a var function that match with a username in the url bar. Now I would like to delete more than one row, but I don't know how to do this? What I am trying to achieve is to enter the url something like this: www.mysite.com/delete.php?favorites=the value1&use=test It will search for a value in the database and then delete it. But if I add the &favorites=the value2 or more than 2, then search for the values in each row while looking for a username before delete the rows Here's the current code: Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbname'); $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)); } $favorites = clean($_GET['favorites']); $username = clean($_GET['user']); if($favorites == '' && $username == ''){ // both are empty $errmsg_arr[] = 'Both name and email are missing. You must enter one or the other.'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['favorites'])) { $insert[] = 'favorites = \'' . clean($_GET['favorites']) . '\''; } if(($favorites) && isset($username)) { mysql_query("DELETE FROM favorites WHERE username='$username' AND favorites='$favorites'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo "favorites rows is deleted"; } else { echo("favorites are already deleted"); } } } ?> Any advice would be much appreciated. Thanks, Mark I'm working on an old cms I built a few years ago and for some reason my Delete page isn't working. It has to be something simple I'm overlooking. The database connection is made just above this code and is pulling the thumb and title listed by id. When I push delete I'm getting the cmd=delete&id=2 passed on so something is up with my last if statement (I think). Here is the code: if(!isset($cmd)) { //display all the news $result = mysql_query("select * from verizon order by id"); //run the while loop that grabs all the news scripts while($r=mysql_fetch_array($result)) { //grab the title and the ID of the enws $title=$r["title"];//take out the title $id=$r["id"];//take out the id $thumb=$r["thumb"]; echo "<div id='delete'> <table> <tr> <td width='350px'><strong>$title</strong></td><td><a href='verizondelete.php?cmd=delete&id=$id'> Delete</a></td> </tr> <td colspan='2' align='center'><img src='../upload/verizon/$thumb'></td> </table> </div><br />"; } } if($cmd=="delete") { $sql = "DELETE FROM verizon WHERE id='$id'"; $result = mysql_query($sql); echo "<h1 style='text-align:center;'>deleted!</h1>"; } } ?> Hi. I have the following code to delete a row when the date has passed. Code: [Select] $today = date("dmY"); $vLongDate = date("dmY", strtotime($thisDate)); if ($today > $vLongDate) { mysql_query("DELETE FROM events WHERE id < '$id'"); } $today is current date, while $vLongDate is the date that is on my database. Am i doing the if statement correctly?? i trying to delete messages out of my message database but im not sure if i'm using this code right or there stuff missing to it :S delete.php <?php require_once('settings.php'); checkLogin('1 2'); $id=$_GET["msgs"]; mysql_query("DELETE messages FROM messages WHERE message_id='$id'"); ?> link usages to delete <a href="delete.php?msgs=<? echo $row['message_id'] ?>">[X]</a> I am trying to find a way of deleting entries from a database after a certain time, and also when there is another field in the database set to 0. i have got so far with the code (will delete when other field is at 0) but nothing happens when i try to add in the time. my code im trying to use is below mysql_query("DELETE FROM temp_users WHERE book_stage='0' and WHERE time() > [creation+60]"); creation being the name of the field in the database that holds the unix time stamp of when the entry was created. i need the entry to be deleted one hour after it was created if the book_stage hasnt been changed to 1 during this hour. many thanks, gavin Hello i have a text box and a button on my webpage and want to get the text box to find the username i type into it from the database and when it does it will then go to number and delete any text that is under usernames number field as you can see i have no idea how. Code: [Select] $result = mysql_query("DELETE FROM mytable WHERE username='$username1' AND number='$number1'" ); Code: [Select] <form name="form1" method="post" action="p.php"> <p><input type="submit" value="Enter" /></p> <input name="username" type="text" id="username" size="15" maxlength="35" value="<?php echo $username1; ?>" /> </form> No errors come up when I run this but it just doesn't delete the entry. <? $rec = $_POST['stock']; if (!$rec){ die ('Please eneter a stock number'); } $link = mysql_connect("xxxx","xxx","xxx"); mysql_select_db('wadkin', $link) or die( "Unable to select database"); mysql_query("DELETE FROM 'wadkin'.'stocklist' WHERE 'stocklist'.'Stock Number' = $rec") or die ('Query failed'); mysql_close($link); ?> Can someone please correct, (btw I have also tried... "DELETE FROM stocklist WHERE 'Stock Number' = $rec") |