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
}
Related
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
I want to ensure "StaffID" is stored when the "View Contacts" page is loaded from a link, rather than straight from the Login Form
LOGIN FORM:
<?php session_start(); // Start PHP session
$StaffID = isset($_SESSION["StaffID"]) ? $_SESSION["StaffID"] : "";?>
<form name="staffaccess" method="post" action="staff-login.php">
<table border="1" cellpadding="3" cellspacing="1">
<tr>
<td colspan="3"><strong>Staff Login </strong></td>
</tr>
<input type="hidden" name="StaffID" id="StaffID" value="<?php echo $StaffID; ?>" />
<tr>
<td>Username:</td>
<td><input name="StaffUsername" size= "30" type="text" id="StaffUsername" value="<?php echo $StaffUsername; ?>"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="StaffPassword" size= "30" type="text" id="StaffPassword" value="<?php echo $StaffPassword; ?>"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Login"/></td>
</tr>
</table>
</form>
LOGIN CHECK:
<?php session_start(); // Start PHP session?>
<body>
<?php
$_SESSION["StaffUsername"] = isset($_POST["StaffUsername"]) ? $_POST["StaffUsername"] : "";
$_SESSION["StaffPassword"] = isset($_POST["StaffPassword"]) ? $_POST["StaffPassword"] : "";
$_SESSION["StaffID"] = isset($_GET["StaffID"]) ? $_GET["StaffID"] : "";
<?php
//connect to database//
$dbc = mysql_connect("", "", "");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
//select database//
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
// username and password sent from form
$StaffUsername=$_POST['StaffUsername'];
$StaffPassword=$_POST['StaffPassword'];
// To protect MySQL injection (more detail about MySQL injection)
$StaffUsername = stripslashes($StaffUsername);
$StaffPassword = stripslashes($StaffPassword);
$StaffUsername = mysql_real_escape_string($StaffUsername);
$StaffPassword = mysql_real_escape_string($StaffPassword);
$qry=("SELECT * FROM staffaccess WHERE Username= '" . $StaffUsername . "' AND Password= '" .$StaffPassword ."'");
$rst = mysql_query($qry, $dbc);
$row = mysql_fetch_array($rst);
if ($row["Username"]==$StaffUsername && $row["Password"]==$StaffPassword)
{
$_SESSION["StaffID"] = $row["StaffID"];
echo "Your login was successful";
echo "</br></br>";
echo "<a href=list-contacts.php>Continue</a>";
}
else {
echo "Sorry your details are not valid";
echo "</br></br>";
echo "<a href=staff-login.htm>Return</a>";
}
?>
VIEW CONTACTS (i only want this to allow to view contacts that particular user has added)
<?php
//connect to database
$dbc = mysql_connect("", "", "");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
//select database
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
$StaffID = (int)$_GET['StaffId'];
// build sql insert statement
**$qry = "SELECT * FROM contacts WHERE StaffID= $StaffID ORDER by name ASC";**
//run insert satement against database
$rst = mysql_query($qry, $dbc);
// print whether successful or not
if ($rst)
{
if (mysql_num_rows($rst)>0) // check that there are records
{
echo "<table border=\"1\" cellspacing=\"0\">";
/***print out field names***/
echo "<tr>"; // start row
for ($i=0; $i<mysql_num_fields($rst); $i++) // for each field print out field name
{
echo "<th>" . mysql_field_name($rst, $i) . "</th>";
}
echo "<th> </th>";
echo "<th> </th>";
echo "</tr>";
/***print out field values***/
while ($row = mysql_fetch_array($rst)) // fetch each of the rows
{
echo "<tr>";
echo "<td>".$row['ContactID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Address']."</td>";
echo "<td>".$row['Phone']."</td>";
echo "<td>".$row['Mobile']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td><a href='edit-contact.php?id=".$row['ContactID']."'>Edit</a></td>";
echo "<td><a href='delete-contact.php?id=".$row['ContactID']."'>Delete</a></td><tr>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "<b><font color='black'>No records returned.</font></b>";
}
}
else
{
echo "<b><font color='red'>Error: ".mysql_error($dbc) . "</font></b>";
}
?>
you didnt pass the staff id on contact page so you pass the staff id like this
change following change in logincheck page
if ($row["Username"]==$StaffUsername && $row["Password"]==$StaffPassword)
{
echo "Your login was successful";
echo "</br></br>";
echo "Continue";
}
you can also use session for logged user
Depending on you mysql version, you may need to quote your where properties, I'm not sure if this is causing your problem, but it may be related. Also, are you sure that your value for the StaffID field is being correctly inserted into the database?
I checked the code and you are using
echo "<a href=list-contacts.php>Continue</a>";
to send user to see the contacts and in this page you are doing
$StaffID = (int)$_GET['StaffId'];
So you need to pass that value in the query string as
echo "Continue";
<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
frostedc_user, 'pass');
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM movie";// Table name NOT database name
foreach ($pdo->query($query) as $row) {
echo "<table border='1'>";
echo "<tr>";
echo "<td width='150'>".$row['movietitle']."</td>";
echo "<td width='150'>".$row['genre']."</td>";
echo "<td width='150'>".$row['LastViewed']."</td>";
echo "<td width='150'>".$row['Location']."</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
echo "<br>";
echo "
<form>
<p>Please Enter a Movie Title</p>
<input type='text' name='new_movie' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Genre</p>
<input type='text' name='movie_genre' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Last View Date</p>
<input type='text' name='last_view' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Location</p>
<input type='text' name='movie_loca' />
<input type='submit' value='Submit' />
</form>";
$pdo = null;
?>
this is the new updated code. I am trying to use the inputs to enter data into my database.
I have researched how to do this, but so far I haven't got anything to work. Any thoughts? Also would it be easier for me to use include and make the inputs in html? if so could i use them to enter the data into the db?
You are doing 2 wrong things here
First : Mixing PDO with MySQL
Second : $query = "SELECT * FROM myDB"; You cant select from a Database.. You need to do a SELECT from your TABLE ! (Are you sure myDB is your table ?)
As you have tagged your question PDO I have removed all unneeded code from your example.
<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
user, 'password'); //1
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM myTable";// Table name NOT database name
echo "<table>";
echo "<tr>";
foreach ($pdo->query($query) as $row) {//3
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
$pdo = null;//5
?>
The number comments
1 Setting character set Manual
2 Echoing error message only for development.In production you should either do something with it or remove try/catch.
3 As there are no parameters use query()
4 For utf8 Prior to PHP 5.3.6
5 Changed mysql_close();(mysql_) to $pdo = null; (PDO)
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
$conn=mysql_connect($host,$username,$pass)or die(mysql_error());
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM news";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<table>
<tr>
<td>".$row['movietitle']."</td>
<td>".$row['genre']."</td>
<td>".$row['LastViewed']."</td>
<td>".$row['Location']."</td>
</tr>
</table>";
}
// disconnect from the database
mysql_close();
?>
try this code
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
mysql_connect($host,$username,$pass);
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM `tablename`";
$result = mysql_query($query);
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
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'])."'";
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...