form data does not commit to MySQL database [duplicate] - php

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
Tried searching the other threads but found nothing that helps:
The code below is part of a form, this passes the data from the form to the DB, the connection has been tested and works.
When the submit button is pressed, nothing happens, no echo for success or failure, and no new record in the database. I can't seem to find what the issue is:
<?php
if(isset($_POST['submit'])){
require '/connectDB.php';
try {
$stmt = $db->prepare("INSERT INTO tbl_matchOfficials
(MO_FN, MO_LN, MO_Gender, MO_DOB, MO_DOD,
Nationality, twitterHandle, Active, TMO)
VALUES ('$_POST[MO_FN]', '$_POST[MO_LN]',
'$_POST[MO_Gender]', '$_POST[MO_DOB]',
'$_POST[MO_DOD]', '$_POST[Nationality]',
'$_POST[twitterHandle]', '$_POST[Active]',
'$_POST[TMO]')");
$stmt->bindParam('MO_FN', $MO_FN);
$stmt->bindParam('MO_LN', $MO_LN);
$stmt->bindParam('MO_Gender', $MO_Gender);
$stmt->bindParam('MO_DOB', $MO_DOB);
$stmt->bindParam('MO_DOD', $MO_DOD);
$stmt->bindParam('Nationality', $Nationality);
$stmt->bindParam('twitterHandle', $twitterHandle);
$stmt->bindParam('Active', $TMO);
$stmt->bindParam('TMO', $TMO);
$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$db = null;
}
?>
Appreciate your help.
EDIT:
It's clear from the awesome assistance below that there is something else wrong, here is the whole code for the form. The form displays and holds the data as it should, it just won't insert and echo back (good or bad).
<!DOCTYPE HTML>
<html>
<head>
<title>New Match Official</title>
<style>
.error {color: #FF0000;}
</style>
<!-- Load jQuery from Google's CDN -->
<!-- Load jQuery UI CSS -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<!-- Load jQuery JS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- Load jQuery UI Main JS -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<!-- Load SCRIPT.JS which will create datepicker for input field -->
<script src="script.js"></script>
<script src="script1.js"></script>
<link rel="stylesheet" href="runnable.css" />
</head>
<h1>
New Match Official
</h1>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit'])){
require '/connectDB.php';
try {
$stmt = $db->prepare("INSERT INTO tbl_matchOfficials
(MO_FN, MO_LN, MO_Gender, MO_DOB, MO_DOD,
Nationality, twitterHandle, Active, TMO)
VALUES (:MOFN, :MOLN,
:MOGender, :MODOB,
:MODOD, :Nationality,
:twitterHandle, :Active,
:TMO)");
$stmt->bindParam(':MOFN', $_POST['MO_FN']);
$stmt->bindParam(':MOLN', $_POST['MO_LN']);
$stmt->bindParam(':MOGender', $_POST['MO_Gender']);
$stmt->bindParam(':MODOB', $_POST['MO_DOB']);
$stmt->bindParam(':MODOD', $_POST['MO_DOD']);
$stmt->bindParam(':Nationality', $_POST['Nationality']);
$stmt->bindParam(':twitterHandle', $_POST['twitterHandle']);
$stmt->bindParam(':Active', $_POST['Active']);
$stmt->bindParam(':TMO', $_POST['TMO']);
$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$db = null;
}
?>
<?php
// define variables and set to empty values
$MO_FN = $MO_LN = $MO_Gender = $MO_DOB = $MO_DOD = $Nationality = $twitterHandle = $Active = $TMO = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$MO_FN = test_input($_POST["MO_FN"]);
$MO_LN = test_input($_POST["MO_LN"]);
$MO_Gender = test_input($_POST["MO_Gender"]);
$MO_DOB = test_input($_POST["MO_DOB"]);
$MO_DOD = test_input($_POST["MO_DOD"]);
$Nationality = test_input($_POST["Nationality"]);
$twitterHandle = test_input($_POST["twitterHandle"]);
$Active = test_input($_POST["Active"]);
$TMO = test_input($_POST["TMO"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$FNErr = $LNErr = $GenderErr = $NationalityErr = $ActiveErr = $TMOErr = "";
$MO_FN = $MO_LN = $MO_Gender = $Nationality = $Active = $TMO = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["MO_FN"])) {
$FNErr = "First Name is required";
} else {
$MO_FN = test_input($_POST["MO_FN"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$MO_FN)) {
$FNErr = "Only letters and white space allowed";
}
}
if (empty($_POST["MO_LN"])) {
$LNErr = "Last Name is required";
} else {
$MO_LN = test_input($_POST["MO_LN"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$MO_LN)) {
$LNErr = "Only letters and white space allowed";
}
}
if (empty($_POST["MO_Gender"])) {
$GenderErr = "Gender is required";
} else {
$MO_Gender = test_input($_POST["MO_Gender"]);
}
if (empty($_POST["Nationality"])) {
$NationalityErr = "Nationality is Required (i.e. AUS for Australia)";
} else {
$Nationality = test_input($_POST["Nationality"]);
}
if (empty($_POST["Active"])) {
$ActiveErr = "Please state if Match Official is still active";
} else {
$Active = test_input($_POST["Active"]);
}
if (empty($_POST["TMO"])) {
$TMOErr = "Please state if Match Official performs the role of a TMO";
} else {
$TMO = test_input($_POST["TMO"]);
}
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="MO_FN" value="<?php echo $MO_FN;?>"><span class="error">* <?php echo $FNErr;?></span></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="MO_LN" value="<?php echo $MO_LN;?>"><span class="error">* <?php echo $LNErr;?></span></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="MO_Gender" <?php if (isset($MO_Gender) && $MO_Gender=="Male") echo "checked";?> value="Male">Male
<input type="radio" name="MO_Gender" <?php if (isset($MO_Gender) && $MO_Gender=="Female") echo "checked";?> value="Female">Female
<span class="error">* <?php echo $GenderErr;?></span></td>
</tr>
<tr>
<td>Date of Birth:</td>
<td><input type="text" id="datepicker" name="MO_DOB" value="<?php echo $MO_DOB;?>"></td>
</tr>
<tr>
<td>Date of Death:</td>
<td><input type="text" id="datepicker1" name="MO_DOD" value="<?php echo $MO_DOD;?>"></td>
</tr>
<tr>
<td>Nationality (TLA):</td>
<td><input type="text" maxlength="3" name="Nationality" value="<?php echo $Nationality;?>"><span class="error">* <?php echo $NationalityErr;?></span></td>
</tr>
<tr>
<td>Twitter Handle:</td>
<td><input type="text" name="twitterHandle" value="<?php echo $twitterHandle;?>"></td>
</tr>
<tr>
<td>Active Referee:</td>
<td><input type="radio" name="Active" <?php if (isset($Active) && $Active=="Yes") echo "checked";?> value="Yes">Yes
<input type="radio" name="Active" <?php if (isset($Active) && $Active=="No") echo "checked";?> value="No">No
<span class="error">* <?php echo $ActiveErr;?></span></td>
</tr>
<tr>
<td>TMO:</td>
<td><input type="radio" name="TMO" <?php if (isset($TMO) && $TMO=="Yes") echo "checked";?> value="Yes">Yes
<input type="radio" name="TMO" <?php if (isset($TMO) && $TMO=="No") echo "checked";?> value="No">No
<span class="error">* <?php echo $TMOErr;?></span></td>
</tr>
<tr>
<td><br><br><input type="submit"></td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo "<table>";
echo "<tr><td>First Name: </td><td>$MO_FN</td></tr>";
echo "<tr><td>Last Name: </td><td>$MO_LN</td></tr>";
echo "<tr><td>Gender: </td><td>$MO_Gender</td></tr>";
echo "<tr><td>Date of Birth: </td><td>$MO_DOB</td></tr>";
echo "<tr><td>Date of Death: </td><td>$MO_DOD</td></tr>";
echo "<tr><td>Nationality: </td><td>$Nationality</td></tr>";
echo "<tr><td>Twitter Handle: </td><td>$twitterHandle</td></tr>";
echo "<tr><td>Active: </td><td>$Active</td></tr>";
echo "<tr><td>TMO: </td><td>$TMO</td></tr>";
echo "</table>"
?>
</body>
</html>

PDO uses Named Placeholders for the variables inside the query. More information about that can be found here: Prepared statements and stored procedures
That said, try this instead. Unless something else is going on, it should solve your problem:
<?php
error_reporting(E_AL‌​L);
ini_set('display_err‌​ors', 1);
if(isset($_POST['submit'])){
require '/connectDB.php';
try {
$stmt = $db->prepare("INSERT INTO tbl_matchOfficials
(MO_FN, MO_LN, MO_Gender, MO_DOB, MO_DOD,
Nationality, twitterHandle, Active, TMO)
VALUES (:MOFN, :MOLN,
:MOGender, :MODOB,
:MODOD, :Nationality,
:twitterHandle, :Active,
:TMO)");
$stmt->bindParam(':MOFN', $_POST['MO_FN']);
$stmt->bindParam(':MOLN', $_POST['MO_LN']);
$stmt->bindParam(':MOGender', $_POST['MO_Gender']);
$stmt->bindParam(':MODOB', $_POST['MO_DOB']);
$stmt->bindParam(':MODOD', $_POST['MO_DOD']);
$stmt->bindParam(':Nationality', $_POST['Nationality']);
$stmt->bindParam(':twitterHandle', $_POST['twitterHandle']);
$stmt->bindParam(':Active', $_POST['Active']);
$stmt->bindParam(':TMO', $_POST['TMO']);
$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$db = null;
}
?>

For those who follow this in future, answer was to add a name="submit" to the submit button code!
After that also came a connection error, but that was because my connectDB.php file is in the root (I am on MAMP) and so needed the initial / removed.
Thanks to everyone for the quick and awesome assistance.

Related

Button function for all fetch row

I am doing project for my university. I create a page where user can send friend request. Here I fetch data from another table and put button for each row data.
My problem is that when one button click other row button also was change to friend request. I need a solution for it.
How to make one add friend request button is equal to one row id and how to avoid other button affected whenever click particular row.
My code is included below. I hope you guys will help me. Thanks in advance.
<?php
session_start();
$_SESSION['myid'];
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID ORDER BY
tutor_register.register_ID='".$_SESSION['myid']."'desc";
$result= mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
$username = $row['username'];
$profile = $row['profile'];
$email = $row['email'];
$address=$row['address'];
$gender=$row['gender'];
$main_subject=$row["main_subject"];
$subject_add=$row["subject_add"];
$rate_main=$row["rate_main"];
$rate_add=$row["rate_add"];
$qualification=$row["qualification"];
?>
<table><form method="post">
<tr class="border_bottom">
<td height="230"><img src='<?php echo $profile;?>'width="200" height="200"/> </td><td><td></td></td>
<?php
if($register_ID == $_SESSION['myid']){
?>
<td><label>Your Profile</label></td>
<?php
} else {
?>
<form method="post">
<td><button class='friendBtn unfriend' name="" data-type="unfriend">Unfriend</button>
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/></td> </form>
<?php
}
}
?>
</tr>
</div>
</table>
</form>
<?php
if(isset($_POST['id']) ) {
$user_id = $_SESSION['myid'];
$friend_id = $_POST['id'];
$sql="INSERT INTO friends(user_id,status,friend_id)" ."VALUES('$user_id','yes','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['id']=$row['id'];
} else {}
}
}
?>
</body>
</html>
You need to replace the following block in your code:
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>
With the one mentioned below. This will solve your problem.
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes' && $row['register_ID']==$_SESSION['id']){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>

Data transfer between php pages using sessions

I am trying to transfer data between php pages using session. My code is as below:
check_code.php:
<?php
session_start();
echo "<form action=\"check_code.php\" method=\"post\">";
echo "<h2>Your Name. *</h2><input type='text' name='user_name'>";
echo "<br><br>";
echo "<h2>Your age. *</h2><input type='text' name='age'>";
echo "<br><br>";
echo "<br><br><br>";
echo "<div><input type='submit' value='Review'></div>";
echo "</form>";
?>
<?php
if((empty($_POST['user_name'])) || (empty($_POST['age'])) ) {
echo "<h2>Please enter your user name and age</h2>";
} else {
echo "<form action=\"page2.php\" method=\"post\">";
$user_name = $_POST['user_name'];
$age = $_POST['age'];
echo "Below are the details entered:<br>";
echo "Name: $user_name";
echo "Age: $age";
echo "Select any one: ";
echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox"
name="subject[]" value="Science">Science</td>';
echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox"
name="subject[]" value="Math">Math</td>';
echo "<br>";
$_SESSION['user'] = $_POST['user_name'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['subject'] = $_POST['subject'];
echo "<input type=\"submit\" value='Add to DB' >";
echo "</form>";
}
?>
page2.php:
<?php
session_start();
$user_name = $_SESSION['user'];
$age = $_SESSION['age'];
$subject = $_SESSION['subject'];
echo "<h2>Below are the details entered:</h2><br>";
echo "<h2>Name: </h2>$user_name";
echo "<h2>Age: </h2>$age";
echo "<h2>Subject selected: </h2>";
for ($i=0;$i<sizeof($subject);$i++) {
echo " $subject[$i] ";
}
?>
The name and age get displayed in the final page (page2.php). The subject does not get passed to the next page. What mistake am I making here?
Any help would be appreciated!!!
The code you gave had some issues, so I rewrote your code and you might try the one below:
check_code.php file:
<?php session_start(); ?>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label>Your name</label>
<input type="text" name="name" />
<br>
<label>Your age</label>
<input type="number" name="age" />
<hr>
<button type="submit" name="review">Review</button>
<?php if(isset($_SESSION['details'])) { ?>
<button type="submit" name="unset">Unset</button>
<?php } ?>
</form>
<?php
if(isset($_SESSION['details'])) {
if(isset($_POST['unset'])) { // If pressed "unset", remove the session and the values and restart
unset($_SESSION);
session_destroy();
}
}
if(isset($_POST['review'])) {
if(!empty($_POST['name']) && !empty($_POST['age'])) { // If fields are not empty
?>
<p>Your Details:</p>
<table>
<tr>
<td>Name<td>
<td><?php echo $_POST['name']; ?></td>
</tr>
<tr>
<td>Age<td>
<td><?php echo $_POST['age']; ?></td>
</tr>
</table>
<?php
$_SESSION['details'] = array(
'name' => $_POST['name'],
'age' => $_POST['age']
// Storing them in array as $_SESSION['details'][name/age/whatever]
);
}
else {
echo 'Please fill in the fields.';
}
}
if(isset($_SESSION['details'])) {
?>
<p><?php echo $_SESSION['details']['name']; /* Stored name in session */ ?>, Please Select Subject:</p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label>Science</label>
<input type="checkbox" name="subject[]" value="science" />
<br>
<label>Math</label>
<input type="checkbox" name="subject[]" value="math" />
<hr>
<button type="submit" name="send">Remember My Choice</button>
</form>
<?php
if(isset($_POST['send'])) { // If you send the second form, then...
if(isset($_POST['subject'])) { // If selected subject
$_SESSION['subject'] = array();
for($i = 0; $i < count($_POST['subject']); $i++) {
$_SESSION['subject'][] = $_POST['subject'][$i]; // store all values of "subject" in the session
}
}
header('location: page2.php');
}
}
Explanation:
You wanted the user to choose a subject after submitting the form, and defined it when the user can not check subject - line 33. when the user can not define the variable, you can continue - but with errors - and that's what I got when I tried your code.
So what I did was the following steps:
Send the first form with the name and the age
Define $_SESSION variable named "details" (as array that held the required information)
If this variable exists - then allow the user to select a subject.
Then, when you choose one (or more) subjects, they're saved too in the session:
page2.php file:
<?php
session_start();
if(isset($_SESSION['details'])) {
?>
<p>Your name is <?php echo $_SESSION['details']['name']; ?> and your age is <?php echo $_SESSION['details']['age']; ?></p>
<?php if(isset($_SESSION['subject'])) { ?>
<p>And your subject(s) are <?php echo implode(', ', $_SESSION['subject']); ?></p>
<?php } else { ?>
<p>You don't have any subject</p>
<?php
}
}
else {
die('An Error Occurred');
}
On page2.php I checked if the details are set. if they are, then we can proceed and check if the subject(s) are set too. In case details are not set, the connection will die and print an error message. If you don't set the subject, you'll get a message about it, too.
Important note:
Your code, and this one too are vulnerable. Do not use these in a server, unless you take care about XSS protection. You may escape characters and use Regular expressions to "Sanitize" the input.
You can replace your current code with this one.
I hope it will be helpful

Building a checkbox list from a database query and retaining the checkbox after a form submit

I am trying to build a simple form which queries a database, grabs a list of email addresses and then creates a table based on the results. What I would like it to do is retain the checked boxes after a submission but am having trouble figuring it out based on the way I've created my table. I can do it no problem if I manually build the table but that defeats the purpose. Here is the code I am working with, again the only change I would like it to do is retain the checked boxes.
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style/style.css"/>
</head>
<body>
<?php include('include/connect.php'); ?>
<h1>This is a test</h1>
<div class="emailform">
<form action="" method="post">
<table id="emails">
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
</table>
<br/><br/>
<input id="manual" type="text" name="select[]"><br/><br/><br/>
<button type="submit" name="SubmitButton">Select Email Addresses</button>
</form>
</div>
<?php
if(isset($_POST['SubmitButton'])){
if(isset($_POST['select'])){
$shift = $_POST['select'];
if (count($shift) > 1 ){
$list = implode(", ", $shift);
echo $list;
} else {
echo "$shift[0] <br/>";
}
}
}
?>
</body>
</html>
Help would be appreciated, thanks
Just check if the current email in the loop exists in $_POST['select'], if it is, you check it, if it is not, clear the check. This check will be displayed in the input checkbox as <?php echo $checked;?> :
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
// IF EMAIL EXISTS IN $_POST, CHECK IT.
$checked = "";
if(isset($_POST['select'])){
$shift = $_POST['select'];
$list = implode(", ", $shift);
if (strpos($list,$email)===false)
$checked = ""; // EMAIL NOT IN $_POST.
else $checked = "checked"; // EMAIL IS IN $_POST.
}
?>
<tr><td><input type="checkbox" name="select[]" <?php echo $checked;?>
value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
Check if $row['Email'] isn't empty, then output "checked" attribute.
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"<?php if($row['Email'] != false) { echo ' checked'; } ?>><?php echo $email; ?></td></tr>
<?php
}
?>

Printing session variable content in PHP

Hi I have the following as my login script. (The script is not yet sanitized.) But I have an issue here. Once a successful log in attempt is made I need to echo the loggedUser but the information doen't get printed once echoed. Can someone pls help me understand where I have gone wrong?
Code as follows;
<?php
SESSION_start();
?>
<!doctype html>
<html>
<head></head>
<body>
<div>
<?php
include ("connect_db/index.php");
if(isset($_SESSION['loggedUser']))
{
echo '<div>User :'.$_SESSION['loggedUser'].'</div>';
}
else
{
echo "
<div id='u2'>
<form name='form1' method='post' action='''>
<table border='1'>
<tr>
<td>User Name: </td>
<td><label for='textfield'></label>
<input type='text' name='UnameZoom' id='UnameZoom' class='txss'></td>
<td> Password: </td>
<td><label for='txss'></label>
<input type='password' name='PwordZoom' id='PwordZoom' class='txss'></td>
<td> <input type='submit' name='loggedUser' id='loggedUser' class='mylog' value='Login'></td>
</tr>
</table>
</form>
<p> </p>
<p> </p>
</div>";
if(isset($_POST['loggedUser']))
{
$un = $_POST['UnameZoom'];
$pw = $_POST['PwordZoom'];
if($un=='' || $pw == '')
{echo "Empty fields"; return;}
$SQLSz = "SELECT pword FROM users WHERE username='$un'";
$rVz = mysqli_query($db,$SQLSz) or die ("SQL Error!!!");
$roVz = mysqli_fetch_array($rVz);
if($pw == $roVz['pword'])
{
$result = mysqli_query($db,"SELECT Lname AS Lna FROM users WHERE username='$un'");
$row11 = mysqli_fetch_assoc($result);
$sum = $row11['Lna'];
$_SESSION['loggedUser'] = $sum;
echo $_SESSION['loggedUser'];
}
else
{
echo "No user found";
}
}
}
?>
<div></body></html>
I think problem is in your variable. It can be array but u cant echo array. try dump your variable with var_dump.
As already mentioned - SESSION_start() shall be session_start()
Try another statement for displaying your SESSION array - for example:
echo '<pre>';
print_r($_SESSION);
echo '</pre'>;
This will show you all session keys in a nice and readable way

form submit not working

I have a table that prints out all available cameras. It uses a form to change these settings. The problem is that the form only updates the last camera in the entry. In other words if I change the form and hit "Apply" for the last camera in the list it will work. If I change the form for any other camera in this list it changes the one to have the same settings as the last camera in the list. There are no issues with any values as far as I can tell.
Sorry for the long dump here, but without being able to narrow down the problem I thought I should include the bulk of it:
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
$query_camera_name = "SELECT camera_id, camera_name, camera_status, camera_quality, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
if (isset($_POST['apply_changes'])) {
//process changes to camera options
$camera_id = $_POST['camera_id'];
$camera_status = check_input($_POST['camera_status']);
$camera_name = check_input($_POST['camera_name'], "You entered an empty camera name. Enter another name and apply changes.");
$camera_quality = check_input($_POST['camera_quality']);
$query_insert_camera = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'", `camera_name` ="'.$camera_name.'", `camera_quality` ="'.$camera_quality.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_insert_camera);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']);
}
echo "<html>";
echo "<head>";
<link href="dashboard/webcam_widget.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function oncameraSubmit(camera_id)
{
document.active_cameras.camera_id.value = camera_id;
return confirm('Apply changes?');
}
</script>
<?php
echo "</head>";
echo "<body>";
if (!isset($result_cameras))
{
//TODO
}
else
{
if ($num_rows == 0)
{
echo '<b><i><center>You currently have no cameras setup. Add a Camera below.</center></i></b>';
}
else
{
?>
<form name="active_cameras" action="<?php htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="hidden" name="camera_id" value="" />
<table id="webcam-table">
<thead>
<tr>
<th>Camera Type</th>
<th>Name</th>
<th>Quality</th>
<th>Status</th>
<th>Camera Actions</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_rows;$i++)
{
//camera_status
if ($result_cameras[$i]["camera_status"] == "ENABLED")
{
$enabled_option = "value='ENABLED' selected='selected'";
$disabled_option = "value='DISABLED'";
}
else
{
$enabled_option = "value='ENABLED'";
$disabled_option = "value='DISABLED' selected='selected'";
}
//camera_quality
if ($result_cameras[$i]["camera_quality"] == "HIGH")
{
$high_option = "value='HIGH' selected='selected'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MEDIUM")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM' selected='selected'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MOBILE")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE' selected='selected'";
}
else
{
//TODO proper logging
}
//camera_type
if ($result_cameras[$i]["camera_type"] == "WEBCAM")
{
$webcam = "value='WEBCAM' selected='selected'";
$axis = "value='AXIS'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "AXIS")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS' selected='selected'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "IPCAM")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS'";
$other = "value='IPCAM' selected='selected'";
}
else
{
//TODO
}
?>
<tr>
<td>
<select name="camera_type">
<option <?php echo $webcam; ?>>Webcam</option>
<option <?php echo $axis; ?>>AXIS</option>
<option <?php echo $other; ?>>Other</option>
</select>
</td>
<td>
<input type="text" size="32" maxlength="64" name="camera_name" value="<?php echo $result_cameras[$i]["camera_name"]; ?>" />
</td>
<td>
<select name="camera_quality">
<option <?php echo $high_option; ?>>High</option>
<option <?php echo $medium_option; ?>>Medium</option>
<option <?php echo $mobile_option; ?>>Mobile</option>
</select>
</td>
<td>
<select name="camera_status">
<option <?php echo $enabled_option; ?>>Enabled</option>
<option <?php echo $disabled_option; ?>>Disabled</option>
</select>
</td>
<td>
<input type="submit" name="apply_changes" value="Apply" onClick="javascript:return oncameraSubmit(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/>
</td>
</tr>
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
}
}
It looks like you have multiple HTML elements with the same name. As such, you want to get back an array of values when the form is posted.
As such, Get $_POST from multiple checkboxes looks like it might be helpful.
Alternatively, extend oncameraSubmit so that it stores all the data in a hidden input field (not just the id). Then when you update the database, use these hidden fields.
Your form element names are clashing. When you define a form element e.g. 'camera_status' twice, you will only receive the last value in the POST.
Use form array notation, e.g.: "camera_status[]" or even better "camera_status[$id]". Then your PHP code will recieve arrays as POST data and you will be able to update everything at once.

Categories