PHP Edit/Delete multiple rows in mysql - php

Good evening, I'm trying to make a single php page wich can edit/delete multiple rows in mysql:
<html>
<head>
<title>Update/Delete Test Page</title>
</head>
<body>
<?
include 'connect.php';
if(isset($_POST['edit'])) // from button name="delete"
{
$title = $_POST['title'];
$description = $_POST['description'];
if(!empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$ed = $check;
$sql = "UPDATE events SET title = '$title', description ='$description' WHERE id = $ed";
}
}
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>
<?php
include ("connect.php");
if(isset($_POST['delete'])) // from button name="delete"
{
if(!empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$del = $check;
$sql = "DELETE from events where id = $del";
$result = $mysqli->query($sql) or die(mysqli_error($mysqli));
}
}
?>
<?php
include 'connect.php';
$query = 'SELECT id, title, description FROM events WHERE evdate = "1/9/2013" order by title asc';
$result2 = $mysqli->query($query) or die(mysqli_error($mysqli));
echo '<br><br><br>';
echo '<b><div align="center"> "1/9/2013"</div></b>';
if ($result2) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action=".$_SERVER['PHP_SELF'].">";
echo "<table cellspacing='0' cellpadding='3'>
<th align='left'>Interval orar</th>
<th align='left'>Eveniment</th>
<th align='left'></th>
";
while ($row = $result2->fetch_object()) {
$title = $row->title;
$description = $row->description;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "
<tr>
<td align='left'><input type='text' name='title' size='20' value='$title'></td>
<td align='left'><input type='text' name='description' size='50' value='$description'></td>
<td align='left'><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
</tr>
";
}
// when the loop is complete, close off the list.
echo "</table>
<p>
<input id='edit' type='submit' class='button' name='edit' value='Edit'/>
<input id='delete' type='submit' class='button' name='delete' value='Delete'/>
</p>
</form>";
}
?>
</body>
</html>
Connect.php looks like this:
<?php
$db_host = "localhost";
$db_username = "calendar";
$db_pass = "calendar";
$db_name = "ecalendar";
$con = mysql_connect ("$db_host", "$db_username", "$db_pass") or die ("could not connect to mysql database");
mysql_select_db("$db_name") or die ("no database");
$mysqli = new MySQLi($db_host, $db_username, $db_pass, $db_name) or die(mysqli_error());
?>
The delete works fine, but the edit doesn't do anything...
Table looks like this:
Start/End Time Event (Checkbox is here)
08:00-10:00 test1 X
10:00-12:00 test2 X
When I try to edit test2 to test2xx I get this in Firebug POST :
title=08%3A00-10%3A00&description=test1&title=10%3A00-12%3A00&description=test2xx&checkbox%5B%5D=53&edit=Edit
If I delete I get this (and it works)
title=08%3A00-10%3A00&description=test1&title=10%3A00-12%3A00&description=test2&checkbox%5B%5D=53&delete=Delete
Edit works but only for the last row (test2), if I try to edit the row above (test1), it insted updates it with the values of the last row (test2)

Guess you need del_id not id
$sql = "UPDATE events SET title = '$title', description ='$description' WHERE id = $del_id ";

1-look your value value=$id in your chekbob
change it to value= '$id'
2-and also , the delete query is with mysqli
but the update query is with mysql ??
3- u dont have to include connect.php 3 times
4- also what previous answer about the variable $del_id.
5- u are missing closing tag td
6- u are missing closing }
7- try this
<html>
<head>
<title>Update/Delete Test Page</title>
</head>
<body>
<?php
include 'connect.php';
if(isset($_POST['edit'])) // from button name="edit"
{
$checkbox = $_POST['checkbox']; //from name="checkbox[]"
$countCheck = count($_POST['checkbox']);
for($i=0;$i<$countCheck;$i++)
{
$del_id = $checkbox[$i];
$sql3 = "UPDATE events SET title = '$title', description ='$description' WHERE id = '$del_id' ";
$result3 = $mysqli->query($sql3) or die(mysqli_error($mysqli));
if (!$result3)
{
die(mysqli_error($mysqli)) ;
}
echo "1 record added";
}
}
if(isset($_POST['delete'])) // from button name="delete"
{
$checkbox = $_POST['checkbox']; //from name="checkbox[]"
$countCheck = count($_POST['checkbox']);
for($i=0;$i<$countCheck;$i++)
{
$del_id = $checkbox[$i];
$sql = "DELETE from events where id = '$del_id' ";
$result = $mysqli->query($sql) or die(mysqli_error($mysqli));
}
}
$query = 'SELECT id, title, description FROM events WHERE evdate = "1/9/2013" order by title asc';
$result2 = $mysqli->query($query) or die(mysqli_error($mysqli));
echo '<br><br><br>';
echo '<b><div align="center"> "1/9/2013"</div></b>';
if ($result2) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action=".$_SERVER['PHP_SELF'].">";
echo "<table cellspacing='0' cellpadding='3'>
<th align='left'>Interval orar</th>
<th align='left'>Eveniment</th>
<th align='left'></th>
";
while ($row = $result2->fetch_object()) {
$title = $row->title;
$description = $row->description;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "
<tr>
<td align='left'><input type='text' name='title' size='20' value='$title'></td>
<td align='left'><input type='text' name='description' size='50' value='$description'></td>
<td align='left'><input type='checkbox' name='checkbox[]' id='checkbox[]' value='$id' /></td>
</tr>
";
}
// when the loop is complete, close off the list.
echo "</table>
<p>
<input id='edit' type='submit' class='button' name='edit' value='Edit'/>
<input id='delete' type='submit' class='button' name='delete' value='Delete'/>
</p>
</form>";
}
?>
</body>
</html>

id=$del_id under for loop,double check your SQL statements and variables bound to them.

gave up on the code above and went with this example from
http://bohemiawebsites.com/PHP-MYSQL-Update-Multiple-Rows.html
Everything works if anybody needs it...

Related

How to update multiple rows in SQL table based on id using one button

table.php
<?php
include('../connections/conn.php');
include('../php/login.php');
$sql = "SELECT * FROM person";
$records = mysqli_query($conn, $sql)
?>
<html>
<head>
<title>Table</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
</tr>
<?php
while($row = mysqli_fetch_array($records)){
$name = $row['Name'];
$age = $row['Age'];
$salary = $row['Salary'];
$id = $row['id'];
echo "<tr><form action=update.php method=post>";
echo "<td><input type=text name=pname value='$name'></td>";
echo "<td><input type=text name=age value='$age'></td>";
echo "<td><input type=text name=salary value='$salary'></td>";
echo "<input type=hidden name=id value='$id'></td>";
echo "<td><input type=submit>";
echo "</form></tr>";
}
?>
</table>
</body>
</html>
(this part of the code displays the table and its values)
Update.php
<?php
include('../connections/conn.php');
include('../php/login.php');
$sql = "UPDATE person SET
Name='$_POST[pname]',Age='$_POST[age]',Salary='$_POST[salary]' WHERE
id='$_POST[id]'";
if(mysqli_query($conn, $sql)){
header("refresh:1 url=table.php");
}
else{
echo"Not Update";
}
$records = mysqli_query($conn, $sql)
?>
(this part is for updating the table)
I have got the code to update the contents of a table using buttons however I would like to just have one button that will update the whole table. At the moment I use a button per row to update that particular row.
Just use this
$sql = "UPDATE person SET
Name='$_POST[pname]',Age='$_POST[age]',Salary='$_POST[salary]' WHERE
id in('$_POST[id]')";

php mysql UPDATE command wont update

All the data is loaded into a table, each row as a button. Once the button has been pressed, the row has to be updated. But when I click on the button, nothing happens. The text box on the rows return to its original value... It is really starting to cheese me off
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'dragondrivingschooldb'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='$_POST[txtfirstname]' WHERE BookingID='$_POST[txtid]' "); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT * FROM booking"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form action=EditStudent.php method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name=update type=submit value=update /> </td>"; //once press update row this button is apart of
echo "<td> <input type=text value=" . $row['BookingID'] . " name=txtid /> </td>";
echo "<td> <input type=text value=" . $row['FirstName'] . " name=txtfirstname /> </td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
mysqli_close($con); //Close connection
?>
</html>
I think that BookingID it is an integer, so your update line need to be:
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID=" . $_POST['txtid'] . ""); //excute UpDate Query
EDIT:
I tested your script and the problem was that you closed the form outside the while loop. Now its working
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'all_tests'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE test_1 SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID='" . $_POST['txtid'] . "'"); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT *FROM test_1"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name='btnUpdate' type='submit' value='update' /> </td>"; //once press update row this button is apart of
echo "<td> <input type='text' value=" . $row['BookingID'] . " name='txtid' /> </td>";
echo "<td> <input type='text' value=" . $row['FirstName'] . " name='txtfirstname' /> </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con); //Close connection
?>
at first check that $_POST[txtid] has value or not. and be sure that field name is correct or incorrect.
There are no input field in your html that has name btnUpdate. What I can see its name is update. Therefore your row:
if (isset($_POST['btnUpdate'])) {
would never be true

Only updating last database record - Array required?

Could someone help me out, I am only new to PHP and SQL. I have created a database, and want to update it using a form on a HTML page. It all works fine except it only updates the last record. I presume this is because I need an array but am unsure how to do this. WOuld anyone have some good examples or point me in the right direction?
The code is as follows:
Display Page
<?php
$con=mysqli_connect("xx","xx","xx","xx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM webquestion");
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' >";
echo "<table class='webquestion' >
<tr>
<th width='12%'>Department</th>
<th width='15%'>Name</th>
<th width='25%'>E-mail</th>
<th width='20%'>Message</th>
<th width='20%'>Notes</th>
<th width='8%'>Delete</th>
</tr>";
while ($row = $result->fetch_object()) {
$department = $row->department;
$name = $row->name;
$email = $row->email;
$message = $row->message;
$notes = $row->notes;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "<tr>
<td>$department</td>
<td>$name</td>
<td>$email</td>
<td>$message</td>
<td><input type='text' name='notes' id='notes' value='$notes' />
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td><input type='hidden' name='id' value=$id />
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items' style='float:left'/>
</table><p><input id='update' type='submit' class='button' name='update' value='Update' style='float:left'/></p>
</form>
<form action='showContactUs.php' >
<input type='submit' value='Refresh Records' style='float:left'>
</form>";
}
?>
PHP Code
<?php
if(isset($_POST['update'])) // from button name="update"
$hostname = 'xx';
$username = 'xx';
$password = 'xx';
$dbname = 'xx';
/*** create a new mysqli object with default database***/
$mysqli = #new mysqli($hostname, $username, $password, $dbname);
/* check connection */
if(!mysqli_connect_errno())
{
/*** if we are successful ***/
echo 'Connected Successfully<br />';
/*** sql to UPDATE an existing record ***/
$notes = $_POST['notes'];
$sql = "UPDATE webquestion
SET notes = '$notes'
WHERE id = '$id'";
/*** execute the query ***/
if($mysqli->query($sql) === TRUE)
{
echo mysqli_affected_rows($mysqli). ' Records UPDATED successfully<br />';
}
else
{
echo 'Unable to UPDATE Records: '.$sql.'<br />' . $mysqli->error;
}
/*** close connection ***/
$mysqli->close();
}
else
{
/*** if we are unable to connect ***/
echo 'Unable to connect';
exit();
}
?>
Thanks for your help.
To pass an array via POST simply add a '[]' to the name atribute:
<td><input type='text' name='notes[]' id='notes' value='$notes' />
<td><input type='hidden' name='id[]' value=$id />
Then on the server side you would do:
$notes = $_POST['notes']; //notes array
foreach($_POST['id'] as $index=>$id) //traverse the ids array
{
$note = $notes[$index]; //Get the note on the same row as id
/*** sql to UPDATE an existing record ***/
$sql = "UPDATE webquestion SET notes = '$note' WHERE id = '$id'";
/*** execute the query ***/
if($mysqli->query($sql) === TRUE)
{
echo mysqli_affected_rows($mysqli). ' Records UPDATED successfully<br />';
}
else
{
echo 'Unable to UPDATE Records: '.$sql.'<br />' . $mysqli->error;
}
}
If you want to update several rows at the same time by matching with their IDs, you need an array of IDs:
array(25,33,26,24)
or any other type of array.
Then you should loop through your array and update the db accordingly:
for($i=0; $i < count($id_array); $i++)
{
$id = $id_array[$i];
$sql = "UPDATE webquestion
SET notes = '$notes'
WHERE id = '$id'";
// and the rest of SQL update
}

Database not updating with MYSQLI

I'm beginner at PHP and I'm using a tutorial I found on the web to work a new piece of a new CMS I'm building. The problem is that the tutorial works just fine but when I start to alter it to my use it cannot connect to the database to update. I receive my error "Database Error: Unable to update record." I can add and delete but not update.
Index.php
<html>
<head>
<title>MySQLi Tutorial</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM family WHERE fid = ".$mysqli->real_escape_string($_GET['fid'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}
}
$query = "SELECT * FROM family";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results ){
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>name</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>";
echo "<a href='edit.php?fid={$fid}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$fid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<script type='text/javascript'>
function delete_user( fid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and fid to the record to be deleted
window.location = 'index.php?action=delete&fid=' + fid;
}
}
</script>
</body>
</html>
add.php
<html>
<head>
<title>MySQLi Create Record</title>
</head>
<body>
<!--we have our html form here where user information will be entered-->
<form action='#' method='post' border='0'>
<table>
<tr>
<td>Firstname</td>
<td><input type='text' name='name' /></td>
</tr>
<td></td>
<td>
<input type='hidden' name='action' value='create' />
<input type='submit' value='Save' />
<a href='index.php'>Back to index</a>
</td>
</tr>
</table>
</form>
<?php
$action = isset($_POST['action']) ? $_POST['action'] : "";
if($action=='create'){
//include database connection
include 'db_connect.php';
//write query
$query = "insert into family
set
name = '" . $mysqli->real_escape_string($_POST['name']) ."'
";
if( $mysqli->query($query) ) {
echo "User was created.";
}else{
echo "Database Error: Unable to create record.";
}
$mysqli->close();
}
?>
</body>
</html>
edit.php
<?php
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update users
set
name = '".$mysqli->real_escape_string($_POST['name'])."',
where
fid='".$mysqli->real_escape_string($_REQUEST['fid'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
$query = "select fid, name
from family
where fid='".$mysqli->real_escape_string($_REQUEST['fid'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$fid = $row['fid'];
$name = $row['name'];
?>
<!--we have our html form here where new user information will be entered-->
<form action='#' method='post' border='0'>
<table>
<tr>
<td>Firstname</td>
<td><input type='text' name='name' value='<?php echo $name; ?>' /></td>
</tr>
<tr>
<td></td>
<td>
<!-- so that we could identify what record is to be updated -->
<input type='hidden' name='fid' value='<?php echo $fid ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
<a href='index.php'>Back to index</a>
</td>
</tr>
</table>
</form>
>
I have been unable to find the proper language to fix this but I believe it's because I"m using some form of multiples but I am not familiar with the mysqli/php languages to fix it.
Thank you
You need to remove the comma at the end of:
name = '".$mysqli->real_escape_string($_POST['name'])."',
the query should be:
$query = "update users
set
name = '".$mysqli->real_escape_string($_POST['name'])."'
where
fid='".$mysqli->real_escape_string($_REQUEST['fid'])."'";

Search SQL with Date Range and Checkbox

I've been trying to develop a code where I have a form to search SQL tables according to date ranges and a checkbox status.
I already have worked out the search query for the dates, but I haven't been able to make it work with the checkbox. I would like to combine both features in one search but I can't figure it out.
For ex: Search between "01/01/2012" and "12/31/2012" where status is "DONE! (Checkbox=Checked)".
Here is the code I'm using to do the search:
The Form
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF'];?>">
<table>
<tr>
<td style="text-align:center; padding-top:15px;">
<span>From&nbsp:</span>
<input type = "date" name = "OLD">
To:
<input type = "date" name = "NEW">
Status:
<input type='checkbox' name='Status' value='DONE'/>
</td>
</tr>
<tr>
<td style="text-align:center; padding-top:15px;">
<button type = "submit" name = "search" value = "Search" class="button orange">Search</button>
<button type = "reset" value = "Clear" class="button orange">Reset</button>
</td>
</tr>
</table>
</form>
The PHP
<?php
if(!isset($_POST['search']))
{
?>
<?php
}
else
{
$OLD = trim($_POST['from']);
$NEW = trim($_POST['to']);
$connection = mysql_pconnect("HOST", "USER", "PASS") or die("Connection failed. ".myslq_error());
mysql_select_db("DATABASENAME") or die("Unable to select db. ".mysql_error());
$query = "SELECT * FROM table WHERE Date >= '$OLD' AND Date <= '$NEW' ORDER BY date ASC";
$result = mysql_query($query) or die(mysql_error());
echo "<table class='table' id='SearchResult' cellspacing='0' cellpadding='0'>";
echo "<tr class='rowa'><b>";
echo "<td class='col1 cell'>Name</td>";
echo "<td class='col2 cell'>Last Name</td>";
echo "</tr>";
echo "</table>";
while($record = mysql_fetch_object($result))
{
echo "<table class='table' id='SearchResult' cellspacing='0' cellpadding='0'>";
echo "<tr class='rowb'>";
echo "<td class='col1 cell'>".$record->Name."</td>";
echo "<td class='col2 cell'>".$record->LastName."</td>";
echo "</tr>";
echo "</table>";
}
}
?>
Who can lead me in the right way to accomplish this?! Thanks a lot!
You can do it like this:
else
{
$OLD = trim($_POST['from']);
$NEW = trim($_POST['to']);
$status = isset($_POST['Status']) ? "AND status = 'DONE' " :"AND status = 'NOT DONE' ";
$connection = mysql_pconnect("HOST", "USER", "PASS") or die("Connection failed. ".myslq_error());
mysql_select_db("DATABASENAME") or die("Unable to select db. ".mysql_error());
$query = "SELECT * FROM table WHERE Date >= '$OLD' AND Date <= '$NEW' ".$status."ORDER BY date ASC";
$result = mysql_query($query) or die(mysql_error());
I think the query composition must be something like that:
$query = "SELECT * FROM table WHERE 1 = 1 "
if ($_POST['MyCheckbox']=="checked")
$query = $query . " and Date >= '$OLD' AND Date <= '$NEW' ORDER BY date ASC";

Categories