I am trying to delete multiple rows with chekboxes. Below is my code
<?php
$host="localhost"; // Host name
$username="****"; // Mysql username
$password="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="****"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result = mysql_query("SELECT * FROM members WHERE dealer='Panzer Protection'");
?>
<form name="form1" method="post" action="">
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td bgcolor="#666666"><input name="checkbox[]" type="checkbox" id="checkbox[]"
value="<? echo $rows['member_id']; ?>"></td>
<td bgcolor="#666666"><? echo $rows['member_id']; ?></td>
<td bgcolor="#666666"><center>
<? echo $rows['member_msisdn']; ?></td>
<td bgcolor="#666666"><center>
<? echo $rows['member_name']; ?></td>
<td bgcolor="#666666"><div align="center"><? echo $rows['dealer']; ?></div>
</td>
<td align="center" bgcolor="#FFFFFF"><a href="control_clientinfo.php?member_id=
<? echo $rows['member_id']; ?>" class="update">Look Up</a></td>
</tr>
<?php
}
?>
<tr>
<td colspan="6" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit"
id="delete" value="Delete"></td>
</tr>
</form> //Forgot form close in past
<?php
// Check if delete button active, start this
if($_POST['delete']){
for($i=0;$i<$count;$i++){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
}
// if successful redirect to
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=control_clientlistdel.php\">";
}
}
mysql_close();
?>
It shows me the list i call and i can tick the boxes. If i hit delete button it just refreshes the screen and the one i ticked is still there
First things first.
It's bad idea to use mysql as it is really old and it's deprecated.
Second, where do you assign your variables ($delete, $count)
you have to check if the delete key of your POST is set:
if (isset($_POST['delete'])) { // Then the form has been submitted
after this, assign your $count variable
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
And everything must work fine.
Final result
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i]; // Parse your value to integer
if ($id > 0) { // and check if it's bigger then 0
mysql_query("DELETE FROM table WHERE member_id = $id");
}
}
}
Check out the mysqli and the PDO drivers for interacting with the database.
not sure if its a typo or not.. but you you have a missing from end tags and <table> in the posted code..
....
<td colspan="6" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
</form> //here
and you need to check the posted $delete value in if condition..the correct way is to use $_POST since you are using method as pos.. here method="post".
updated
if(isset($_POST) && $_POST['delete']){ //here
$count=count($_POST['checkbox']);
for($i=0;$i<$count;$i++){
$sql = "DELETE FROM $tbl_name WHERE id='".$_POST['checkbox'][$i]."'";
mysql_query($sql);
}
}
you can use header() to redirect in php
header( 'Location: http://www.yoursite.com/ontrol_clientlistdel.php' ) ;
Related
Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>
You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">
On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.
Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'
You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.
I try to use the below code to update multiple rows, the below code can view the results of rows but it can not be updated, where is wrong place? How to modify it ?
<?php
$host="localhost"; // Host name
$username="abc"; // Mysql username
$password="abc123"; // Mysql password
$db_name="abc"; // Database name
$tbl_name="BRAddress"; // 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 Database");
$sql="SELECT * FROM $tbl_name WHERE br_no='62779457'";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<form name="form1" method="post" action="">
<tr>
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>BR No.</strong></td>
<td align="center"><strong>Date of Register</strong></td>
<td align="center"><strong>Address</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center">
<? $br_no[]=$rows['br_no']; ?><? echo $rows['br_no']; ?>
</td>
<td align="center">
<input name="br_date_of_register[]" type="date" id="br_date_of_register" value="<? echo $rows['br_date_of_register']; ?>">
</td>
<td align="center">
<input name="br_address[]" type="text" size="60" id="br_address" value="<? echo $rows['br_address']; ?>">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</form>
</table>
<?php
// Check if button name "Submit" is active, do this
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET
br_date_of_register='$br_date_of_register[$i]',
br_address='$br_address[$i]'
WHERE br_no='$br_no[$i]'";
$result1=mysql_query($sql1);
}
}
if($result1){
header("location:update_sample.php");
}
mysql_close();
?>
Thank you very much for your help & support !
I think that you need to change this part
if($Submit){
to
if($_POST('Submit')){
I haven't run the whole or looked at entire code, but you have nothing that defines $Submit variable though from what I see.
Or you can put in
$Submit = $_POST('Submit');
before the if statement.
Let me know how you go.
Cheers
Your POST variable are empty. $br_date_of_register has no value. You must use this like following
$br_date_of_register = $_POST[br_date_of_register];
$br_address = $_POST[br_address];
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET
br_date_of_register='$br_date_of_register[$i]',
br_address='$br_address[$i]'
WHERE br_no='$br_no[$i]'";
$result1=mysql_query($sql1);
}
Edit
if($Submit)
To
if($_SERVER['REQUEST_METHOD'] == "POST")
Considering your Submit check,
you can use this,
if(isset($_POST["Submit"]))
{
}
Further in your SQL statement, do this,
$sql1='UPDATE ' . $tbl_name . ' SET
br_date_of_register = ' . $br_date_of_register[$i] .
' , br_address = ' . $br_address[$i] .
' WHERE br_no = ' . $br_no[$i];
In this code I don't have any error messages but it doesn't delete the data. By the way the database has many records and the names of all the fields are correct.
<?php
if ($connect = mysqli_connect('localhost', 'root', 'adminpass', 'flip'))
{
$id = $_GET['id'];
$sql = "SELECT * FROM threads ORDER BY id DESC";
$query = mysqli_query($connect, $sql);
$num = mysqli_num_rows($query);
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" >
<table border="1" width="400" cellpadding="0" cellspacing="0">
<tr>
<td>#</td>
<td>id</td>
<td>subject</td>
</tr>
<?php
while ($row = mysqli_fetch_array($query))
{
?>
<tr>
<td> <input type="checkbox" name="checkbox[]" value="<?php echo $row['id'] ?>"></td>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['topic'] ?></td>
</tr>
<?php
}
?>
<input type="submit" name="delete" value="delete" >
<?php
if (isset($delete))
{
for ($i = 0; $i < $num; $i++)
{
$del_id = $checkbox[$i];
$sql2 = "DELETE FROM threads WHERE id='$del_id'";
$query2 = mysqli_query($connect, $sql2);
}
if ($query2)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">";
}
}
mysqli_close($connect);
?>
</table>
</form>
What is the problem with it?
You can try this:
<?php
/* ESTABLISH CONNECTION */
$connect=mysqli_connect("localhost","root","adminpass","flip");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if(isset($_POST['delete'])){ /* IF DELETE IS CLICKED */
$checkbox=$_POST['checkbox'];
$hiddencounter=mysqli_real_escape_string($connect,$_POST['hiddencounter']); /* PREVENT A BIT OF SQL INJECTION */
for($i=0;$i<$hiddencounter;$i++){ /* FOR LOOP BASED ON THE NUMROWS BELOW */
if(!empty($checkbox[$i])){ /* IF THE CHECKBOX IS TICKED */
$del_id=mysqli_real_escape_string($connect,$checkbox[$i]); /* PREVENT A BIT OF SQL INJECTION */
$sql2="DELETE FROM threads WHERE id='$del_id'";
$query2=mysqli_query($connect,$sql2); /* IMPLEMENT THE DELETE QUERY */
}
} /* END OF FOR LOOP */
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">";
} /* END OF ISSET DELETE */
?>
<form action="" method="POST" > <?php /* YOU CAN LEAVE THE ACTION BLANK, TO SUBMIT THE FORM ON THE PAGE ITSELF */ ?>
<table border="1" width="400" cellpadding="0" cellspacing="0">
<tr>
<td>#</td>
<td>id</td>
<td>subject</td>
</tr>
<?
$sql="SELECT * FROM threads ORDER BY id DESC";
$query=mysqli_query($connect,$sql);
$num=mysqli_num_rows($query);
/* SUBMIT THE NUMBER OF ROWS QUERIED THROUGH HIDDEN INPUT */
echo "<input type='hidden' name='hiddencounter' value='$num'>";
while($row=mysqli_fetch_array($query)){ /* FETCH DATA */
?>
<tr>
<td><input type="checkbox" name="checkbox[]" value="<?php echo $row['id'] ?>"></td>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['topic'] ?></td>
</tr>
<?
} /* END OF WHILE LOOP $QUERY */
?>
<input type="submit" name="delete" value="delete" >
<?php
mysqli_close($connect);
?>
</table>
</form>
Explanation why your code did not work:
Your isset($delete): where does $delete variable came from?
Your for loop doesn't determine if the checkboxes submitted has values or not.
Your <meta> redirect. It redirects to delete.php after the for loop, so that is the reason you don't see any errors. But I'm pretty sure you would see some errors if you remove the <meta> redirect.
Even if the delete is working, you wouldn't see the result right after because the delete query is after your fetching of data.
You have an error in your Variable:
if (isset($delete))
Should be:
if (isset($_POST['$delete']))
I don't see where $delete variable is ever set in your code. At the moment $delete is not set, therefor if(isset($delete)) is false.
To me it would appear you are trying to use Registered Globals. Or you just forgot to set $delete to one of your $_GET[] or $_POST[] variables.
"Warning
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0."
PHP manual - Security Globals
Predefined Variables
I want to update a database using this code but it fails every time and I cannot find why the form fails. if someone could help, i would appreciate that alot!!
These are the codes i use to update the DB (these are three files total)
When you go to my editor you will see this screen.(everything works exept the update) it says cannot update data. it doesn't show any other errors.
did i miss something?
<html>
<body>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
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);
?>
<head>
<style>
div
{
fload:center;
width:1000px;
margin:0 0 15px 20px;
padding:15px;
border:1px solid black;
}
</style>
<div align="center">
</head>
<img src="http://www.emiclaer.nl/Portals/39/Tuinen.jpg" alt="DTlogo.img" width="880" height="280">
</div>
<body style="margin:15px;">
<div>
Druk op <font color="blue"><u>Update</u></font> om de App te Updaten.<br>
<p></p>
<center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td colspan="4"><strong>Iphone aanbiedingen.</strong> </td>
</tr>
<tr>
<td align="center"><strong>Naam</strong></td>
<td align="center"><strong>Omschrijving</strong></td>
<td align="center"><strong>Prijs</strong></td>
<td align="center"><strong>Promotext</strong></td>
<td align="center"><strong>URL</strong></td>
<td align="center"><strong>Image URL</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['naam']; ?></td>
<td><? echo $rows['omschrijving']; ?></td>
<td><? echo $rows['promotext']; ?></td>
<td><? echo $rows['prijs']; ?></td>
<td><? echo $rows['url']; ?></td>
<td><? echo $rows['iurl']; ?></td>
<td align="center">Update</td>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
<?php
mysql_close();
?>
</div>
</center>
</form>
</body>
</html>
This is the second screen you will go to
<html>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<head>
<style>
div
{
fload:center;
width:1000px;
margin:0 0 15px 20px;
padding:15px;
border:1px solid black;
}
</style>
<div align="center">
</head>
<img src="http://www.emiclaer.nl/Portals/39/Tuinen.jpg" alt="DTlogo.img" width="880" height="280">
</div>
<body style="margin:15px;">
<div>
Vul hier de updates in.<br>
<p></p>
<center>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update Iphone App</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Naam</strong></td>
<td align="center"><strong>Omschrijving</strong></td>
<td align="center"><strong>Prijs</strong></td>
<td align="center"><strong>Promotext</strong></td>
<td align="center"><strong>URL</strong></td>
<td align="center"><strong>Image URL</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<form name="form1" method="post" action="updateform.php">
<tr>
<td> </td>
<td align="center">
<input name="inp_naam" type="text" id="inp_naam" value="<? echo $rows['naam']; ?>">
</td>
<td align="center">
<input name="inp_omschrijving" type="text" id="inp_omschrijving" value="<? echo $rows['omschrijving']; ?>" size="15">
</td>
<td>
<input name="inp_prijs" type="text" id="inp_prijs" value="<? echo $rows['prijs']; ?>" size="15">
</td>
<td align="center">
<input name="inp_promotext" type="text" id="inp_promotext" value="<? echo $rows['promotext']; ?>">
</td>
<td align="center">
<input name="inp_url" type="text" id="inp_url" value="<? echo $rows['url']; ?>" size="15">
</td>
<td>
<input name="inp_iurl" type="text" id="inp_iurl" value="<? echo $rows['iurl']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</form>
</td>
<td> </td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
<?php
// close connection
mysql_close();
?>
</body>
</html>
This Code is what has to Update the database. (i have updated this one to most comments on the page, mysqli and PDO don't work for me.)
<html>
<body>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$inp_naam=$_POST['inp_naam'];
$inp_prijs=$_POST['inp_prijs'];
$inp_promotext=$_POST['inp_promotext'];
$inp_url=$_POST['inp_url'];
$inp_iurl=$_POST['inp_iurl'];
$id=$_POST['id'];
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect Host");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE `$db_name`.`$tbl_name`
SET `naam` = '$inp_naam',
`omschrijving` = '$inp_omschrijving',
`prijs` = '$inp_prijs',
`promotext` = '$inp_promotext',
`url` = '$inp_url',
`iurl` = '$inp_iurl'
WHERE `$tbl_name`.`id` = '$id'";
$result = mysql_query($conn, $sql);
if (!$result) {
// if successfully updated.
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
} else {
die('cannot update DataBase'. mysql_error());
}
?>
</body>
</html>
To
<html>
<body>
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry your not loggedin, please login to gain acces. Here to login');}
?>
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
session_start();
// Connect to server and select database.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect Host");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE tblProducts
SET naam = '".$_POST['inp_naam']."',
omschrijving = '".$_POST['inp_omschrijving']."',
prijs = '".$_POST['inp_prijs']."',
promotext = '".$_POST['inp_promotext']."',
url = '".$_POST['inp_url']."',
iurl = '".$_POST['inp_iurl']."'
WHERE id = '".$_POST['inp_id']."'";
$result = mysql_query($sql,$conn);
if (!result) {
// if successfully updated.
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
} else {
die('cannot update DataBase'. mysql_error());
}
mysql_close();
?>
</body>
</html>
Thank you alot for your time!
Mysqli.
// Connect to database
$con=mysqli_connect("$host","$user","$pass","$db_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Get id from URL bar
$id=$_GET['id']
// connect to table
$sql="SELECT * FROM `tblProducts` WHERE `id` = '$id'";
$result=mysqli_query($con,$sql);
// get table information
$rows=mysqli_fetch_array($result,MYSQLI_ASSOC);
mysqli_free_result($result);
?>
First of all, the syntax for your query is incorrect. The SQL query should be passed as the first parameter, with the connection identifier as the second, for example:
$result = mysql_query($sql, $conn);
Secondly, your UPDATE query contains invalid characters. You should use backticks to escape field names in MySQL,not quotes. Update your code as follows:
$sql="UPDATE `$db_name`.`$tbl_name`
SET `naam` = '$inp_naam',
`omschrijving` = '$inp_omschrijving',
`prijs` = '$inp_prijs',
`promotext` = '$inp_promotext',
`url` = '$inp_url',
`iurl` = '$inp_iurl'
WHERE `$tbl_name`.`id` = $id";
You'll see that I also removed the erroneous squared brackets ([]) as well.
Please be advised that mysql_* functions are now deprecated. You should look into MySQLi or PDO. Also be advised that your code is wide open to SQL injection. You should learn about sanitizing your input, and in particular, Prepared Statements.
I am not sure this ' is the correct symbol for using with table and column names.
UPDATE '$db_name'.'$tbl_name'
SET 'naam' = ['$inp_naam'], 'omschrijving' = ['$inp_omschrijving'], 'prijs' = ['$inp_prijs'], 'promotext' = ['$inp_promotext'], 'url' = ['$inp_url'], 'iurl' = ['$inp_iurl']
WHERE '$tbl_name'.'id' = $id
Maybe you wanted to use ` ?
$sql="UPDATE '$db_name'.'$tbl_name'
SET naam = ['$inp_naam'], omschrijving = ['$inp_omschrijving'], prijs = ['$inp_prijs'], promotext = ['$inp_promotext'], url = ['$inp_url'], iurl = ['$inp_iurl']
WHERE '$tbl_name'.id = $id";
Remove single quote from column name
This code of yours has some serious security issues. You are writing POST/GET-variables without quoting to an SQL query, which let's users inject SQL into your query (see http://xkcd.com/327/ :)).
For DB interaction I usually use PDOs (http://www.php.net/manual/de/pdo.prepare.php).
Your code will look like this:
$sth = $dbh->prepare('UPDATE '.$db_name.'.'.$tbl_name.' SET naam = ?, omschrijving = ?, prijs = ?, promotext = ?, url = ?, iurl = ? WHERE '.$tbl_name.'.id = ?');
$sth->execute(array($inp_naam, $inp_omschrijving, $inp_prijs, $inp_promotext, $inp_url, $inp_iurl, $id));
Edit: Without PDO this would look like this:
$sql = "UPDATE ".$db_name.".".$tbl_name." SET"
." naam = '".mysql_real_escape_string($inp_naam)
."', omschrijving = '".mysql_real_escape_string($inp_omschrijving)
."', prijs = '".mysql_real_escape_string($inp_prijs)
."', promotext = '".mysql_real_escape_string($inp_promotext)
."', url = '".mysql_real_escape_string($inp_url)
."', iurl = '".mysql_real_escape_string($inp_iurl)
."' WHERE ".$tbl_name.".id = '".mysql_real_escape_string($id)."'");
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="toybox"; // Database name
$tbl_name="Emp"; // 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);
// echo $count;
?>
<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>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</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['EmpId']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows['EmpId']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['FirstName']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['LastName']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['Email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if($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_multiple.php
if($result){
echo " Record have been deleted";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
Rather than doing a query for each iteration of your delete-loop, I would build all of the indexes up into a string, and use something like the following:
DELETE FROM tableName
WHERE id IN (1,2,12,53)
Also, your submit button won't come through as $delete, but instead $_POST["delete"]. And with your connection:
mysql_connect("$host", "$username", "$password")
You really ought not use variables like strings (generally) - this should be written as:
mysql_connect($host, $username, $password)
Furthermore, you've got a few more problems in and around your delete-logic. For instance, I pointed out already that your <input type='submit' name='delete' /> button will be known as $_POST["delete"] once it is registered on the server. Likewise, your checkboxes, having an id value of checkbox[] will simply be known as $_POST["checkbox"] on the server.
Also, your $count variable, used in your delete-logic, is based on the earlier query that selected all of the records to show them. It does not reflect the number of checkboxes to be deleted, it reflects the number of records that were shown. As such, your for loop should not be based on it:
for ($i = 0; $i < count($_POST["checkbox"]); $i++)
{
// delete $_POST["checkbox"][$i];
}
And again, I would suggest you build a string of values and run a single query instead of multiple.
Working Code .. Consider Point 1 2 and 3
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("funconnect") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM members")
or die(mysql_error());
$count=mysql_num_rows($result);
echo "<form name='sendmail' method='post' action='memberList.php'><table border='1'>";
echo "<tr> <th>Select</th> <th>Name</th> </tr>";
// keeps getting the next row until there are no more to get
$countSn = 0;
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
$chkname = "checkbox".$countSn; #Point 1- Create defferent name for checkboxex like checkbox0, checkbox1
echo "<tr><td><input type='checkbox' name=".$chkname." value=".$row['m_id']." /></td>";
echo "</td><td>";
echo $row['m_name'];
echo "</td></tr>";
$countSn++;
}
echo '<tr><td colspan=2><input name="delete" type="submit" id="delete" value="Delete"></td></tr></table></form>';
$delete=$_POST['delete'];
$checkbox=$_POST['checkbox'];
// Check if delete button active, start this
if($delete){
for($i=0;$i<$count;$i++){
$cname = "checkbox".$i;# Point 2- Create check box name like checkbox0, checkbox1
$checkbox=$_POST[$cname]; #Point 3 - Retrieve data against name
echo $i."===".$checkbox."<br />";
//echo $del_id;
//$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
//$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
//echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";
}
}
mysql_close();
?>