I'm trying to create a form which allows you to update a database table using php.
I'm kinda new to PHP so excuse me if I make a stupid mistake in the code.
This is my edit.php code:
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cats");
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php
while($row = mysqli_fetch_array($result))
{
$name = $row['name'];
$email = $row['email'];
$rank = $row['rank'];
$birth = $row['birth'];
$joined = $row['joined'];
$steamid = $row['steamid'];
?>
<td width="100"></td>
<td><?=$name?></td>
</tr>
<tr>
<td width="100">Email</td>
<td><input name="emailid" type="text" value="<?=$email?>"></td>
</tr>
<tr>
<td width="100">Rank</td>
<td><input name="rankid" type="text" value="<?=$rank?>"></td>
</tr>
<tr>
<td width="100">Birth</td>
<td><input name="birthid" type="text" value="<?=$birth?>"></td>
</tr>
<tr>
<td width="100">Joined</td>
<td><input name="joinedid" type="text" value="<?=$joined?>"></td>
</tr>
<tr>
<td width="100">Steamid</td>
<td><input name="steamidid" type="text" value="<?=$steamid?>"></td>
</tr>
<?php } ?>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$name = $row['nameid'];
$email = $row['emailid'];
$rank = $row['rankid'];
$birth = $row['birthid'];
$joined = $row['joinedid'];
$steamid = $row['steamidid'];
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
$retval = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
echo "Updated data successfully\n";
}
mysqli_close($con);
?>
</body>
</html>
It shows the table and information but the updating isn't working.
Updated data successfully
I've checked the database but it's not updating anything.
Dear i think you change the record based on Name because you can use $name in where clause and you can also change the Name than never true where clause so that your query execute successfully but not effected on any of the row.
you want to get for editable record and that's unique id base update row it will defiantly work.
Try to use PHP PDO database access functions, your code as it stands is vulnerable to SQL-Injection! PDO will also make debugging and working with the database much easier.
I think your check for "update" in $_POST is not working because update is not a field inside your form but the submit button itself, try to check for one of the fields instead.
Informations:
With mysqli_error() you need to write about which connection you want to get errors, like this:
mysqli_error($con);
With mysqli_query() you need to give two parameters, connection and query like this:
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
How to debug:
If you want to check that UPDATE query return any error you can do something like this:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
You can try to debug your query with something like this:
$sql = "UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';";
echo $sql; // this output write in your phpMyadmin to check if there are any errors.
$update = mysqli_query($con, $sql);
Other problem we got:
1. I think also you should have else in your code, f.ex.:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
} else {
echo "Updated data successfully\n";
}
2. You are not getting data from $_POST it should be like:
$name = $_POST['nameid']; // not $row['nameid']
$email = $_POST['emailid'];
$rank = $_POST['rankid'];
$birth = $_POST['birthid'];
$joined = $_POST['joinedid'];
$steamid = $_POST['steamidid'];
More about used functions:
PHP: mysqli::$error
PHP: mysqli::query
In your case it is Procedural style
Related
I have this Add Edit Delete form, the problem is:
when I put everything and I click on ADD it says "Data added successfully." but the data isn't in my table of phpAdmin and it not shows in the page...
Or is simply because my hoster doens't work with MySQLi but with MySQL?
Without talking about SQL Injections because Im not so expert and dont know how protect from that, this pages will be protected with login area so only restricted members will access to it.
index.php
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM `user` ORDER BY id DESC"); // using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Steam Username</td>
<td>Steam Password</td>
<td>Steam Guard Code</td>
<td>Update</td>
</tr>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['steamUE']."</td>";
echo "<td>".$res['steamPW']."</td>";
echo "<td>".$res['steamGC']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
</body>
</html>
add.html
<html>
<head>
<title>Add Data</title>
</head>
<body>
Home
<br/><br/>
<form action="add.php" method="post" name="form1">
<table width="25%" border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE"></td>
</tr>
<tr>
<td>Steam Password</td>
<td><input type="text" name="steamPW"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
</body>
</html>
edit.php
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = mysqli_real_escape_string($mysqli, $_POST['id']);
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE `user` SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM `user` WHERE id='$id'");
while($res = mysqli_fetch_array($result))
{
$steamUE = $res['steamUE'];
$steamPW = $res['steamPW'];
$steamGC = $res['steamGC'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamUE" value="<?php echo $steamUE;?>"></td>
</tr>
<tr>
<td>Steam Username</td>
<td><input type="text" name="steamPW" value="<?php echo $steamPW;?>"></td>
</tr>
<tr>
<td>Steam Guard Code</td>
<td><input type="text" name="steamGC" value="<?php echo $steamGC;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
delete.php
<?php
//including the database connection file
include("config.php");
//getting id of the data from url
$id = $_GET['id'];
//deleting the row from table
$result = mysqli_query($mysqli, "DELETE * FROM `user` WHERE id='$id'");
//redirecting to the display page (index.php in our case)
header("Location: index.php");
?>
add.php
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$steamUE = mysqli_real_escape_string($mysqli, $_POST['steamUE']);
$steamPW = mysqli_real_escape_string($mysqli, $_POST['steamPW']);
$steamGC = mysqli_real_escape_string($mysqli, $_POST['steamGC']);
// checking empty fields
if(empty($steamUE) || empty($steamPW) || empty($steamGC)) {
if(empty($steamUE)) {
echo "<font color='red'>Steam Username field is empty.</font><br/>";
}
if(empty($steamPW)) {
echo "<font color='red'>Steam Password field is empty.</font><br/>";
}
if(empty($steamGC)) {
echo "<font color='red'>Steam Guard Code field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$result = mysqli_query($mysqli, "INSERT INTO `user` (steamUE,steamPW,steamGC) VALUES ('$steamUE','$steamPW','$steamGC')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
</body>
</html>
config.php
<?php
/*
// mysql_connect("database-host", "username", "password")
$conn = mysql_connect("localhost","root","root")
or die("cannot connected");
// mysql_select_db("database-name", "connection-link-identifier")
#mysql_select_db("test",$conn);
*/
/**
* mysql_connect is deprecated
* using mysqli_connect instead
*/
$databaseHost = 'sql.website.com';
$databaseName = '';
$databaseUsername = '';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
It not doesn't says or shows any errors or any other problems, it says only data added successfully and nothing else. I don't understand why it doesn't add any data in my tables, i checked everything again and again, maybe because i'm tired but i tried to rename tables names but nothing change, is the same...
Spotted three errors,
add.php: Column names should be without ''. Check the following
$result = mysqli_query($mysqli, "INSERT INTO user (steamUE,steamPW,steam_GC) VALUES ('$steamUE','$steamPW','$steamGC')");
edit.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "UPDATE user SET steamUE='$steamUE',steamPW='$steamPW',steamGC='$steamGC' WHERE id='$id'");
delete.php: '' missing from $id. Check the following
$result = mysqli_query($mysqli, "DELETE * FROM user WHERE id='$id'");
If the connection with DB is successful, it must work (and this answer deserves a green tick from you :D).
Or is simply because my hoster doens't work with MySQLi but with
MySQL?
Wherever I faced issues, I got some error or a blank page.
Check your dB connection. Turn to mysqli, declair it with $sql with (errno), but call your param before $sql. Use if condition to check your connection. On your add please use prepared with $stmnt and execute it.
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 want to create a table with input fields where student records can be inserted. The name of the students are in the first column of the table fetched from the database with a while loop. The other columns contain fields for inputing the student scores. The challenge I'm facing is how to insert the records of all the students in different row of a table called result_sec into the database. I've search for similar post but couldn't get a suitable answer. Below is the code. Thanks in advance.
<?php require('header.php'); ?>
<?php
$query_form = sprintf("SELECT * FROM regform LIMIT 2");
$form = mysqli_query($conn, $query_form) or die(mysqli_error($conn));
$formdata = mysqli_fetch_assoc($form);
if(isset($_POST['submit']))
{
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
foreach($exes as $key => $exe)
{
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam) VALUES ('$exe', '$asss[$key]', '$ca1s[$key]', '$ca2s[$key]', '$exams[$key]')";
}
$insert = mysqli_multi_query($conn, $sql);
}
?>
<form method="POST">
<table>
<thead>
<tr>
<th>Name</th>
<th>Ass.</th>
<th>Exe.</th>
<th>1st C.A.</th>
<th>2nd C.A.</th>
<th>Exam</th>
</tr>
</thead>
<tbody>
<?php do { ?>
<tr>
<td><?php echo $formdata['surname']." ".$formdata['firstname']; ?></td>
<td><input name="ass[]" size="1px"/></td>
<td><input name="exe[]" size="1px" /></td>
<td><input name="ca1[]" size="1px" /></td>
<td><input name="ca2[]" size="1px" /></td>
<td><input name="exam[]" size="1px" /></td>
<input type="hidden" name="regformid[]" value="<?php echo $formdata['regformid'];?>" />
</tr>
<?php } while ($formdata = mysqli_fetch_assoc($form)); ?>
</tbody>
</table>
<button type="submit">Insert Student Record</button>
</form>
<?php require('footer.php'); ?>
See If this resolve your problem
if(isset($_POST['submit'])){
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
//You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($exes as $i => $exe) {
$exee = mysqli_real_escape_string($exe);
$ass = mysqli_real_escape_string($asss[$i]);
$ca1 = mysqli_real_escape_string($ca1s[$i]);
$ca2 = mysqli_real_escape_string($ca2s[$i]);
$exam = mysqli_real_escape_string($exams[$i]);
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam)
VALUES ('$exee', '$ass', '$ca1', '$ca2', '$exam')";
$insert = mysqli_multi_query($conn, $sql);
}
}
I have a super easy question. I have a form that echoes out a mySQL record that the user can update. I make my changes, and it tells me that the update is successful, but when I look at the table, the changes do not go through. What is the problem here?
This is the first script.
<?php
require_once("models/config.php");
?>
<table border=1>
<tr>
<td align=center>Edit Form</td>
</tr>
<tr>
<td>
<table>
<?
$personid=$_SERVER['QUERY_STRING'];
$order = "SELECT * FROM persons where personid='$personid'";
$result = mysqli_query($mysqli,$order);
$row = mysqli_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="id" value="<? echo "$row[personid]"?>">
<tr>Person ID:<? echo "$row[personid]"?></tr>
<tr>
<td>First Name</td>
<td>
<input type="text" name="firstname"
size="20" value="<? echo "$row[firstname]"?>">
</td>
</tr>
<tr>
<td>Surname</td>
<td>
<input type="text" name="surname" size="40"
value="<? echo "$row[surname]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Edit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
Which then goes through to this:
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname='$firstname', surname='$surname' WHERE personid='$personid'";
$result = mysqli_query($mysqli,$order);
if (!$result) {
echo "Error entering data! <BR>";
echo mysql_error();
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
Is there something I am missing here?
Thanks in advance.
You are sending a hidden input named id and trying to use a $_POST['personid']
correct that
You may also pay attention to the comments you had (SQL Injection's one at least)
Your form sends the id in the field id, while you refer to it as personid.
The reason why this appears to be working, is that the update in itself is correct. $personid is treated as an empty string, so the update correctly updates all records that have an empty personid, which is no record at all.
OK, so here is a revised script with prepared statements. The script is working in the sense that updates are being made to the records. Two questions:
1) is this safe from My-SQL injections?
2) This is updating records successfully, but now it is echoing out "Error entering data!", how come?
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname=?, surname=? WHERE personid=?";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "ssi", $_POST['firstname'], $_POST['surname'], $_POST['personid']);
mysqli_stmt_execute($stmt);
$result = mysqli_query($mysqli,$stmt);
if (!$result) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
I'm sure the second question is a rather boneheaded one - do I just reverse the conditions?
I know there are multiple questions here on SO regarding this same issue already and I've looked into them but didn't quite get a satisfying answer. So here goes my question,
I have a form which consists of a few textboxes and checkboxes. It looks like this,
The user can select multiple checkboxes. I'm trying to insert the values(not the displaying text string) of those checkboxes into a MySQL table. It should look like this,
One Service ID(SID) can have multiple Locations(Loc_Code). Those location codes (CO, GQ) are the values of the checkboxes.
I've written this following code so far.
<html>
<head>
</head>
<body>
<?php
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new ServiceID */
$query = "SELECT SID FROM taxi_services ORDER BY SID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row["SID"];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
$new_id = $id_letter . $id_num;
//Selecting locations
$query = "SELECT Loc_Code, Name FROM districts";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<?php
if(isset($_POST["savebtn"]))
{
//inserting the new service information
$id = $_POST["sid"];
$name = $_POST["name"];
$cost = $_POST["cost"];
if($_POST["active"] == "on") $active = 1; else $active = 0;
$query = "INSERT INTO taxi_services(SID, Name, Cost, Active) VALUES('$id', '$name', '$cost', '$active')";
$result = mysql_query($query, $conn);
//inserting the location details
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
if (!$result || !$result5)
{
die("Error " . mysql_error());
}
else
{
?>
<script type="text/javascript">
alert("Record added successfully!");
</script>
<?php
}
mysql_close($conn);
}
?>
<div id="serv">
<b>Enter a new taxi service</b>
<br/><br/>
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Service ID</td>
<td><input type="text" name="sid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" style="text-align:right" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="cost" style="text-align:right" onkeypress="return isNumberKey(event)" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="checkbox" name="active" /></td>
</tr>
</table>
</div>
<div id="choseLoc">
Locations <br/><br/>
<table border="0">
<?php
$a = 0;
while($row = mysql_fetch_array($result))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $row['Loc_Code']; ?>" /></td>
<td style="text-align:left"><?php echo $row["Name"]; ?></td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</form>
</div>
</body>
</html>
It inserts the Service details correctly. But when it inserts location data, a problem like this occurs,
I selected 4 checkboxes and saved. The 4 location codes gets saved along with the service ID. But as you can see from the screenshot above, a bunch of empty rows gets inserted too.
My question is how can I stop this from happening? How can I insert the data from the checkboxes only I select?
Thank you.
One way would be to only loop over the checkboxes that were submitted:
//inserting the location details
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
I reiterate here the SQL injection warning given above: you would be much better off preparing an INSERT statement and then executing it with parameters. Using PDO, it would look something like:
//inserting the location details
$stmt = $dbh->prepare('
INSERT INTO service_locations(SID, Loc_Code) VALUES(:id, :loc)
');
$stmt->bindValue(':id', $id);
$stmt->bindParam(':loc', $loc_id);
foreach($_POST["checkbox2"] as $loc_id) $stmt->execute();
from these sentence:
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
i find the problem is that the value of loc_code must be the last loction you selected. because in this loop, the value of loc_code will replaced everytime. if you want to insert all the location, you should put it on the one sentence, like INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id'), the value of $loc_id should be CO,GQ,GL.
This is happening because the checkboxes that weren't ticked still get posted, they just have empty values. Before you do your insert to service_locations just check if $loc_id is empty or not, only do the insert if it isn't.